DAGCombiner.cpp revision aee5c3e1052b2e144fdc6461bd602cdc502a93cc
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 "llvm/Target/TargetRegisterInfo.h"
39#include "llvm/Target/TargetSubtargetInfo.h"
40#include <algorithm>
41using namespace llvm;
42
43STATISTIC(NodesCombined   , "Number of dag nodes combined");
44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48STATISTIC(SlicedLoads, "Number of load sliced");
49
50namespace {
51  static cl::opt<bool>
52    CombinerAA("combiner-alias-analysis", cl::Hidden,
53               cl::desc("Turn on alias analysis during testing"));
54
55  static cl::opt<bool>
56    CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57               cl::desc("Include global information in alias analysis"));
58
59  /// Hidden option to stress test load slicing, i.e., when this option
60  /// is enabled, load slicing bypasses most of its profitability guards.
61  static cl::opt<bool>
62  StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63                    cl::desc("Bypass the profitability model of load "
64                             "slicing"),
65                    cl::init(false));
66
67//------------------------------ DAGCombiner ---------------------------------//
68
69  class DAGCombiner {
70    SelectionDAG &DAG;
71    const TargetLowering &TLI;
72    CombineLevel Level;
73    CodeGenOpt::Level OptLevel;
74    bool LegalOperations;
75    bool LegalTypes;
76    bool ForCodeSize;
77
78    // Worklist of all of the nodes that need to be simplified.
79    //
80    // This has the semantics that when adding to the worklist,
81    // the item added must be next to be processed. It should
82    // also only appear once. The naive approach to this takes
83    // linear time.
84    //
85    // To reduce the insert/remove time to logarithmic, we use
86    // a set and a vector to maintain our worklist.
87    //
88    // The set contains the items on the worklist, but does not
89    // maintain the order they should be visited.
90    //
91    // The vector maintains the order nodes should be visited, but may
92    // contain duplicate or removed nodes. When choosing a node to
93    // visit, we pop off the order stack until we find an item that is
94    // also in the contents set. All operations are O(log N).
95    SmallPtrSet<SDNode*, 64> WorkListContents;
96    SmallVector<SDNode*, 64> WorkListOrder;
97
98    // AA - Used for DAG load/store alias analysis.
99    AliasAnalysis &AA;
100
101    /// AddUsersToWorkList - When an instruction is simplified, add all users of
102    /// the instruction to the work lists because they might get more simplified
103    /// now.
104    ///
105    void AddUsersToWorkList(SDNode *N) {
106      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
107           UI != UE; ++UI)
108        AddToWorkList(*UI);
109    }
110
111    /// visit - call the node-specific routine that knows how to fold each
112    /// particular type of node.
113    SDValue visit(SDNode *N);
114
115  public:
116    /// AddToWorkList - Add to the work list making sure its instance is at the
117    /// back (next to be processed.)
118    void AddToWorkList(SDNode *N) {
119      WorkListContents.insert(N);
120      WorkListOrder.push_back(N);
121    }
122
123    /// removeFromWorkList - remove all instances of N from the worklist.
124    ///
125    void removeFromWorkList(SDNode *N) {
126      WorkListContents.erase(N);
127    }
128
129    SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
130                      bool AddTo = true);
131
132    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133      return CombineTo(N, &Res, 1, AddTo);
134    }
135
136    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
137                      bool AddTo = true) {
138      SDValue To[] = { Res0, Res1 };
139      return CombineTo(N, To, 2, AddTo);
140    }
141
142    void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
143
144  private:
145
146    /// SimplifyDemandedBits - Check the specified integer node value to see if
147    /// it can be simplified or if things it uses can be simplified by bit
148    /// propagation.  If so, return true.
149    bool SimplifyDemandedBits(SDValue Op) {
150      unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151      APInt Demanded = APInt::getAllOnesValue(BitWidth);
152      return SimplifyDemandedBits(Op, Demanded);
153    }
154
155    bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
156
157    bool CombineToPreIndexedLoadStore(SDNode *N);
158    bool CombineToPostIndexedLoadStore(SDNode *N);
159    bool SliceUpLoad(SDNode *N);
160
161    void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162    SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163    SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164    SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165    SDValue PromoteIntBinOp(SDValue Op);
166    SDValue PromoteIntShiftOp(SDValue Op);
167    SDValue PromoteExtend(SDValue Op);
168    bool PromoteLoad(SDValue Op);
169
170    void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171                         SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172                         ISD::NodeType ExtType);
173
174    /// combine - call the node-specific routine that knows how to fold each
175    /// particular type of node. If that doesn't do anything, try the
176    /// target-specific DAG combines.
177    SDValue combine(SDNode *N);
178
179    // Visitation implementation - Implement dag node combining for different
180    // node types.  The semantics are as follows:
181    // Return Value:
182    //   SDValue.getNode() == 0 - No change was made
183    //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
184    //   otherwise              - N should be replaced by the returned Operand.
185    //
186    SDValue visitTokenFactor(SDNode *N);
187    SDValue visitMERGE_VALUES(SDNode *N);
188    SDValue visitADD(SDNode *N);
189    SDValue visitSUB(SDNode *N);
190    SDValue visitADDC(SDNode *N);
191    SDValue visitSUBC(SDNode *N);
192    SDValue visitADDE(SDNode *N);
193    SDValue visitSUBE(SDNode *N);
194    SDValue visitMUL(SDNode *N);
195    SDValue visitSDIV(SDNode *N);
196    SDValue visitUDIV(SDNode *N);
197    SDValue visitSREM(SDNode *N);
198    SDValue visitUREM(SDNode *N);
199    SDValue visitMULHU(SDNode *N);
200    SDValue visitMULHS(SDNode *N);
201    SDValue visitSMUL_LOHI(SDNode *N);
202    SDValue visitUMUL_LOHI(SDNode *N);
203    SDValue visitSMULO(SDNode *N);
204    SDValue visitUMULO(SDNode *N);
205    SDValue visitSDIVREM(SDNode *N);
206    SDValue visitUDIVREM(SDNode *N);
207    SDValue visitAND(SDNode *N);
208    SDValue visitOR(SDNode *N);
209    SDValue visitXOR(SDNode *N);
210    SDValue SimplifyVBinOp(SDNode *N);
211    SDValue SimplifyVUnaryOp(SDNode *N);
212    SDValue visitSHL(SDNode *N);
213    SDValue visitSRA(SDNode *N);
214    SDValue visitSRL(SDNode *N);
215    SDValue visitCTLZ(SDNode *N);
216    SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217    SDValue visitCTTZ(SDNode *N);
218    SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219    SDValue visitCTPOP(SDNode *N);
220    SDValue visitSELECT(SDNode *N);
221    SDValue visitVSELECT(SDNode *N);
222    SDValue visitSELECT_CC(SDNode *N);
223    SDValue visitSETCC(SDNode *N);
224    SDValue visitSIGN_EXTEND(SDNode *N);
225    SDValue visitZERO_EXTEND(SDNode *N);
226    SDValue visitANY_EXTEND(SDNode *N);
227    SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228    SDValue visitTRUNCATE(SDNode *N);
229    SDValue visitBITCAST(SDNode *N);
230    SDValue visitBUILD_PAIR(SDNode *N);
231    SDValue visitFADD(SDNode *N);
232    SDValue visitFSUB(SDNode *N);
233    SDValue visitFMUL(SDNode *N);
234    SDValue visitFMA(SDNode *N);
235    SDValue visitFDIV(SDNode *N);
236    SDValue visitFREM(SDNode *N);
237    SDValue visitFCOPYSIGN(SDNode *N);
238    SDValue visitSINT_TO_FP(SDNode *N);
239    SDValue visitUINT_TO_FP(SDNode *N);
240    SDValue visitFP_TO_SINT(SDNode *N);
241    SDValue visitFP_TO_UINT(SDNode *N);
242    SDValue visitFP_ROUND(SDNode *N);
243    SDValue visitFP_ROUND_INREG(SDNode *N);
244    SDValue visitFP_EXTEND(SDNode *N);
245    SDValue visitFNEG(SDNode *N);
246    SDValue visitFABS(SDNode *N);
247    SDValue visitFCEIL(SDNode *N);
248    SDValue visitFTRUNC(SDNode *N);
249    SDValue visitFFLOOR(SDNode *N);
250    SDValue visitBRCOND(SDNode *N);
251    SDValue visitBR_CC(SDNode *N);
252    SDValue visitLOAD(SDNode *N);
253    SDValue visitSTORE(SDNode *N);
254    SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255    SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256    SDValue visitBUILD_VECTOR(SDNode *N);
257    SDValue visitCONCAT_VECTORS(SDNode *N);
258    SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259    SDValue visitVECTOR_SHUFFLE(SDNode *N);
260
261    SDValue XformToShuffleWithZero(SDNode *N);
262    SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
263
264    SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
265
266    bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267    SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268    SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269    SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270                             SDValue N3, ISD::CondCode CC,
271                             bool NotExtCompare = false);
272    SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273                          SDLoc DL, bool foldBooleans = true);
274    SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
275                                         unsigned HiOp);
276    SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277    SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278    SDValue BuildSDIV(SDNode *N);
279    SDValue BuildUDIV(SDNode *N);
280    SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281                               bool DemandHighBits = true);
282    SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283    SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
284    SDValue ReduceLoadWidth(SDNode *N);
285    SDValue ReduceLoadOpStoreWidth(SDNode *N);
286    SDValue TransformFPLoadStorePair(SDNode *N);
287    SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
288    SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
289
290    SDValue GetDemandedBits(SDValue V, const APInt &Mask);
291
292    /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
293    /// looking for aliasing nodes and adding them to the Aliases vector.
294    void GatherAllAliases(SDNode *N, SDValue OriginalChain,
295                          SmallVectorImpl<SDValue> &Aliases);
296
297    /// isAlias - Return true if there is any possibility that the two addresses
298    /// overlap.
299    bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
300                 const Value *SrcValue1, int SrcValueOffset1,
301                 unsigned SrcValueAlign1,
302                 const MDNode *TBAAInfo1,
303                 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
304                 const Value *SrcValue2, int SrcValueOffset2,
305                 unsigned SrcValueAlign2,
306                 const MDNode *TBAAInfo2) const;
307
308    /// isAlias - Return true if there is any possibility that the two addresses
309    /// overlap.
310    bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
311
312    /// FindAliasInfo - Extracts the relevant alias information from the memory
313    /// node.  Returns true if the operand was a load.
314    bool FindAliasInfo(SDNode *N,
315                       SDValue &Ptr, int64_t &Size, bool &IsVolatile,
316                       const Value *&SrcValue, int &SrcValueOffset,
317                       unsigned &SrcValueAlignment,
318                       const MDNode *&TBAAInfo) const;
319
320    /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
321    /// looking for a better chain (aliasing node.)
322    SDValue FindBetterChain(SDNode *N, SDValue Chain);
323
324    /// Merge consecutive store operations into a wide store.
325    /// This optimization uses wide integers or vectors when possible.
326    /// \return True if some memory operations were changed.
327    bool MergeConsecutiveStores(StoreSDNode *N);
328
329  public:
330    DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
331        : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
332          OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
333      AttributeSet FnAttrs =
334          DAG.getMachineFunction().getFunction()->getAttributes();
335      ForCodeSize =
336          FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
337                               Attribute::OptimizeForSize) ||
338          FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
339    }
340
341    /// Run - runs the dag combiner on all nodes in the work list
342    void Run(CombineLevel AtLevel);
343
344    SelectionDAG &getDAG() const { return DAG; }
345
346    /// getShiftAmountTy - Returns a type large enough to hold any valid
347    /// shift amount - before type legalization these can be huge.
348    EVT getShiftAmountTy(EVT LHSTy) {
349      assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
350      if (LHSTy.isVector())
351        return LHSTy;
352      return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
353                        : TLI.getPointerTy();
354    }
355
356    /// isTypeLegal - This method returns true if we are running before type
357    /// legalization or if the specified VT is legal.
358    bool isTypeLegal(const EVT &VT) {
359      if (!LegalTypes) return true;
360      return TLI.isTypeLegal(VT);
361    }
362
363    /// getSetCCResultType - Convenience wrapper around
364    /// TargetLowering::getSetCCResultType
365    EVT getSetCCResultType(EVT VT) const {
366      return TLI.getSetCCResultType(*DAG.getContext(), VT);
367    }
368  };
369}
370
371
372namespace {
373/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
374/// nodes from the worklist.
375class WorkListRemover : public SelectionDAG::DAGUpdateListener {
376  DAGCombiner &DC;
377public:
378  explicit WorkListRemover(DAGCombiner &dc)
379    : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
380
381  virtual void NodeDeleted(SDNode *N, SDNode *E) {
382    DC.removeFromWorkList(N);
383  }
384};
385}
386
387//===----------------------------------------------------------------------===//
388//  TargetLowering::DAGCombinerInfo implementation
389//===----------------------------------------------------------------------===//
390
391void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
392  ((DAGCombiner*)DC)->AddToWorkList(N);
393}
394
395void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
396  ((DAGCombiner*)DC)->removeFromWorkList(N);
397}
398
399SDValue TargetLowering::DAGCombinerInfo::
400CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
401  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
402}
403
404SDValue TargetLowering::DAGCombinerInfo::
405CombineTo(SDNode *N, SDValue Res, bool AddTo) {
406  return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
407}
408
409
410SDValue TargetLowering::DAGCombinerInfo::
411CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
412  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
413}
414
415void TargetLowering::DAGCombinerInfo::
416CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
417  return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
418}
419
420//===----------------------------------------------------------------------===//
421// Helper Functions
422//===----------------------------------------------------------------------===//
423
424/// isNegatibleForFree - Return 1 if we can compute the negated form of the
425/// specified expression for the same cost as the expression itself, or 2 if we
426/// can compute the negated form more cheaply than the expression itself.
427static char isNegatibleForFree(SDValue Op, bool LegalOperations,
428                               const TargetLowering &TLI,
429                               const TargetOptions *Options,
430                               unsigned Depth = 0) {
431  // fneg is removable even if it has multiple uses.
432  if (Op.getOpcode() == ISD::FNEG) return 2;
433
434  // Don't allow anything with multiple uses.
435  if (!Op.hasOneUse()) return 0;
436
437  // Don't recurse exponentially.
438  if (Depth > 6) return 0;
439
440  switch (Op.getOpcode()) {
441  default: return false;
442  case ISD::ConstantFP:
443    // Don't invert constant FP values after legalize.  The negated constant
444    // isn't necessarily legal.
445    return LegalOperations ? 0 : 1;
446  case ISD::FADD:
447    // FIXME: determine better conditions for this xform.
448    if (!Options->UnsafeFPMath) return 0;
449
450    // After operation legalization, it might not be legal to create new FSUBs.
451    if (LegalOperations &&
452        !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
453      return 0;
454
455    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
456    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
457                                    Options, Depth + 1))
458      return V;
459    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
460    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
461                              Depth + 1);
462  case ISD::FSUB:
463    // We can't turn -(A-B) into B-A when we honor signed zeros.
464    if (!Options->UnsafeFPMath) return 0;
465
466    // fold (fneg (fsub A, B)) -> (fsub B, A)
467    return 1;
468
469  case ISD::FMUL:
470  case ISD::FDIV:
471    if (Options->HonorSignDependentRoundingFPMath()) return 0;
472
473    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
474    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
475                                    Options, Depth + 1))
476      return V;
477
478    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
479                              Depth + 1);
480
481  case ISD::FP_EXTEND:
482  case ISD::FP_ROUND:
483  case ISD::FSIN:
484    return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
485                              Depth + 1);
486  }
487}
488
489/// GetNegatedExpression - If isNegatibleForFree returns true, this function
490/// returns the newly negated expression.
491static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
492                                    bool LegalOperations, unsigned Depth = 0) {
493  // fneg is removable even if it has multiple uses.
494  if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
495
496  // Don't allow anything with multiple uses.
497  assert(Op.hasOneUse() && "Unknown reuse!");
498
499  assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
500  switch (Op.getOpcode()) {
501  default: llvm_unreachable("Unknown code");
502  case ISD::ConstantFP: {
503    APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
504    V.changeSign();
505    return DAG.getConstantFP(V, Op.getValueType());
506  }
507  case ISD::FADD:
508    // FIXME: determine better conditions for this xform.
509    assert(DAG.getTarget().Options.UnsafeFPMath);
510
511    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
512    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513                           DAG.getTargetLoweringInfo(),
514                           &DAG.getTarget().Options, Depth+1))
515      return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
516                         GetNegatedExpression(Op.getOperand(0), DAG,
517                                              LegalOperations, Depth+1),
518                         Op.getOperand(1));
519    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
520    return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
521                       GetNegatedExpression(Op.getOperand(1), DAG,
522                                            LegalOperations, Depth+1),
523                       Op.getOperand(0));
524  case ISD::FSUB:
525    // We can't turn -(A-B) into B-A when we honor signed zeros.
526    assert(DAG.getTarget().Options.UnsafeFPMath);
527
528    // fold (fneg (fsub 0, B)) -> B
529    if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
530      if (N0CFP->getValueAPF().isZero())
531        return Op.getOperand(1);
532
533    // fold (fneg (fsub A, B)) -> (fsub B, A)
534    return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
535                       Op.getOperand(1), Op.getOperand(0));
536
537  case ISD::FMUL:
538  case ISD::FDIV:
539    assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
540
541    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
542    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                           DAG.getTargetLoweringInfo(),
544                           &DAG.getTarget().Options, Depth+1))
545      return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
546                         GetNegatedExpression(Op.getOperand(0), DAG,
547                                              LegalOperations, Depth+1),
548                         Op.getOperand(1));
549
550    // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
551    return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
552                       Op.getOperand(0),
553                       GetNegatedExpression(Op.getOperand(1), DAG,
554                                            LegalOperations, Depth+1));
555
556  case ISD::FP_EXTEND:
557  case ISD::FSIN:
558    return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
559                       GetNegatedExpression(Op.getOperand(0), DAG,
560                                            LegalOperations, Depth+1));
561  case ISD::FP_ROUND:
562      return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
563                         GetNegatedExpression(Op.getOperand(0), DAG,
564                                              LegalOperations, Depth+1),
565                         Op.getOperand(1));
566  }
567}
568
569
570// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
571// that selects between the values 1 and 0, making it equivalent to a setcc.
572// Also, set the incoming LHS, RHS, and CC references to the appropriate
573// nodes based on the type of node we are checking.  This simplifies life a
574// bit for the callers.
575static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
576                              SDValue &CC) {
577  if (N.getOpcode() == ISD::SETCC) {
578    LHS = N.getOperand(0);
579    RHS = N.getOperand(1);
580    CC  = N.getOperand(2);
581    return true;
582  }
583  if (N.getOpcode() == ISD::SELECT_CC &&
584      N.getOperand(2).getOpcode() == ISD::Constant &&
585      N.getOperand(3).getOpcode() == ISD::Constant &&
586      cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
587      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
588    LHS = N.getOperand(0);
589    RHS = N.getOperand(1);
590    CC  = N.getOperand(4);
591    return true;
592  }
593  return false;
594}
595
596// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
597// one use.  If this is true, it allows the users to invert the operation for
598// free when it is profitable to do so.
599static bool isOneUseSetCC(SDValue N) {
600  SDValue N0, N1, N2;
601  if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
602    return true;
603  return false;
604}
605
606SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
607                                    SDValue N0, SDValue N1) {
608  EVT VT = N0.getValueType();
609  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
610    if (isa<ConstantSDNode>(N1)) {
611      // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
612      SDValue OpNode =
613        DAG.FoldConstantArithmetic(Opc, VT,
614                                   cast<ConstantSDNode>(N0.getOperand(1)),
615                                   cast<ConstantSDNode>(N1));
616      return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
617    }
618    if (N0.hasOneUse()) {
619      // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
620      SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
621                                   N0.getOperand(0), N1);
622      AddToWorkList(OpNode.getNode());
623      return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
624    }
625  }
626
627  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
628    if (isa<ConstantSDNode>(N0)) {
629      // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
630      SDValue OpNode =
631        DAG.FoldConstantArithmetic(Opc, VT,
632                                   cast<ConstantSDNode>(N1.getOperand(1)),
633                                   cast<ConstantSDNode>(N0));
634      return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
635    }
636    if (N1.hasOneUse()) {
637      // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
638      SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
639                                   N1.getOperand(0), N0);
640      AddToWorkList(OpNode.getNode());
641      return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
642    }
643  }
644
645  return SDValue();
646}
647
648SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
649                               bool AddTo) {
650  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
651  ++NodesCombined;
652  DEBUG(dbgs() << "\nReplacing.1 ";
653        N->dump(&DAG);
654        dbgs() << "\nWith: ";
655        To[0].getNode()->dump(&DAG);
656        dbgs() << " and " << NumTo-1 << " other values\n";
657        for (unsigned i = 0, e = NumTo; i != e; ++i)
658          assert((!To[i].getNode() ||
659                  N->getValueType(i) == To[i].getValueType()) &&
660                 "Cannot combine value to value of different type!"));
661  WorkListRemover DeadNodes(*this);
662  DAG.ReplaceAllUsesWith(N, To);
663  if (AddTo) {
664    // Push the new nodes and any users onto the worklist
665    for (unsigned i = 0, e = NumTo; i != e; ++i) {
666      if (To[i].getNode()) {
667        AddToWorkList(To[i].getNode());
668        AddUsersToWorkList(To[i].getNode());
669      }
670    }
671  }
672
673  // Finally, if the node is now dead, remove it from the graph.  The node
674  // may not be dead if the replacement process recursively simplified to
675  // something else needing this node.
676  if (N->use_empty()) {
677    // Nodes can be reintroduced into the worklist.  Make sure we do not
678    // process a node that has been replaced.
679    removeFromWorkList(N);
680
681    // Finally, since the node is now dead, remove it from the graph.
682    DAG.DeleteNode(N);
683  }
684  return SDValue(N, 0);
685}
686
687void DAGCombiner::
688CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
689  // Replace all uses.  If any nodes become isomorphic to other nodes and
690  // are deleted, make sure to remove them from our worklist.
691  WorkListRemover DeadNodes(*this);
692  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
693
694  // Push the new node and any (possibly new) users onto the worklist.
695  AddToWorkList(TLO.New.getNode());
696  AddUsersToWorkList(TLO.New.getNode());
697
698  // Finally, if the node is now dead, remove it from the graph.  The node
699  // may not be dead if the replacement process recursively simplified to
700  // something else needing this node.
701  if (TLO.Old.getNode()->use_empty()) {
702    removeFromWorkList(TLO.Old.getNode());
703
704    // If the operands of this node are only used by the node, they will now
705    // be dead.  Make sure to visit them first to delete dead nodes early.
706    for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
707      if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
708        AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
709
710    DAG.DeleteNode(TLO.Old.getNode());
711  }
712}
713
714/// SimplifyDemandedBits - Check the specified integer node value to see if
715/// it can be simplified or if things it uses can be simplified by bit
716/// propagation.  If so, return true.
717bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
718  TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
719  APInt KnownZero, KnownOne;
720  if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
721    return false;
722
723  // Revisit the node.
724  AddToWorkList(Op.getNode());
725
726  // Replace the old value with the new one.
727  ++NodesCombined;
728  DEBUG(dbgs() << "\nReplacing.2 ";
729        TLO.Old.getNode()->dump(&DAG);
730        dbgs() << "\nWith: ";
731        TLO.New.getNode()->dump(&DAG);
732        dbgs() << '\n');
733
734  CommitTargetLoweringOpt(TLO);
735  return true;
736}
737
738void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
739  SDLoc dl(Load);
740  EVT VT = Load->getValueType(0);
741  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
742
743  DEBUG(dbgs() << "\nReplacing.9 ";
744        Load->dump(&DAG);
745        dbgs() << "\nWith: ";
746        Trunc.getNode()->dump(&DAG);
747        dbgs() << '\n');
748  WorkListRemover DeadNodes(*this);
749  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
750  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
751  removeFromWorkList(Load);
752  DAG.DeleteNode(Load);
753  AddToWorkList(Trunc.getNode());
754}
755
756SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
757  Replace = false;
758  SDLoc dl(Op);
759  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
760    EVT MemVT = LD->getMemoryVT();
761    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
762      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
763                                                  : ISD::EXTLOAD)
764      : LD->getExtensionType();
765    Replace = true;
766    return DAG.getExtLoad(ExtType, dl, PVT,
767                          LD->getChain(), LD->getBasePtr(),
768                          MemVT, LD->getMemOperand());
769  }
770
771  unsigned Opc = Op.getOpcode();
772  switch (Opc) {
773  default: break;
774  case ISD::AssertSext:
775    return DAG.getNode(ISD::AssertSext, dl, PVT,
776                       SExtPromoteOperand(Op.getOperand(0), PVT),
777                       Op.getOperand(1));
778  case ISD::AssertZext:
779    return DAG.getNode(ISD::AssertZext, dl, PVT,
780                       ZExtPromoteOperand(Op.getOperand(0), PVT),
781                       Op.getOperand(1));
782  case ISD::Constant: {
783    unsigned ExtOpc =
784      Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
785    return DAG.getNode(ExtOpc, dl, PVT, Op);
786  }
787  }
788
789  if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
790    return SDValue();
791  return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
792}
793
794SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
795  if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
796    return SDValue();
797  EVT OldVT = Op.getValueType();
798  SDLoc dl(Op);
799  bool Replace = false;
800  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
801  if (NewOp.getNode() == 0)
802    return SDValue();
803  AddToWorkList(NewOp.getNode());
804
805  if (Replace)
806    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
807  return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
808                     DAG.getValueType(OldVT));
809}
810
811SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
812  EVT OldVT = Op.getValueType();
813  SDLoc dl(Op);
814  bool Replace = false;
815  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
816  if (NewOp.getNode() == 0)
817    return SDValue();
818  AddToWorkList(NewOp.getNode());
819
820  if (Replace)
821    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
822  return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
823}
824
825/// PromoteIntBinOp - Promote the specified integer binary operation if the
826/// target indicates it is beneficial. e.g. On x86, it's usually better to
827/// promote i16 operations to i32 since i16 instructions are longer.
828SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
829  if (!LegalOperations)
830    return SDValue();
831
832  EVT VT = Op.getValueType();
833  if (VT.isVector() || !VT.isInteger())
834    return SDValue();
835
836  // If operation type is 'undesirable', e.g. i16 on x86, consider
837  // promoting it.
838  unsigned Opc = Op.getOpcode();
839  if (TLI.isTypeDesirableForOp(Opc, VT))
840    return SDValue();
841
842  EVT PVT = VT;
843  // Consult target whether it is a good idea to promote this operation and
844  // what's the right type to promote it to.
845  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
846    assert(PVT != VT && "Don't know what type to promote to!");
847
848    bool Replace0 = false;
849    SDValue N0 = Op.getOperand(0);
850    SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
851    if (NN0.getNode() == 0)
852      return SDValue();
853
854    bool Replace1 = false;
855    SDValue N1 = Op.getOperand(1);
856    SDValue NN1;
857    if (N0 == N1)
858      NN1 = NN0;
859    else {
860      NN1 = PromoteOperand(N1, PVT, Replace1);
861      if (NN1.getNode() == 0)
862        return SDValue();
863    }
864
865    AddToWorkList(NN0.getNode());
866    if (NN1.getNode())
867      AddToWorkList(NN1.getNode());
868
869    if (Replace0)
870      ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
871    if (Replace1)
872      ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
873
874    DEBUG(dbgs() << "\nPromoting ";
875          Op.getNode()->dump(&DAG));
876    SDLoc dl(Op);
877    return DAG.getNode(ISD::TRUNCATE, dl, VT,
878                       DAG.getNode(Opc, dl, PVT, NN0, NN1));
879  }
880  return SDValue();
881}
882
883/// PromoteIntShiftOp - Promote the specified integer shift operation if the
884/// target indicates it is beneficial. e.g. On x86, it's usually better to
885/// promote i16 operations to i32 since i16 instructions are longer.
886SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
887  if (!LegalOperations)
888    return SDValue();
889
890  EVT VT = Op.getValueType();
891  if (VT.isVector() || !VT.isInteger())
892    return SDValue();
893
894  // If operation type is 'undesirable', e.g. i16 on x86, consider
895  // promoting it.
896  unsigned Opc = Op.getOpcode();
897  if (TLI.isTypeDesirableForOp(Opc, VT))
898    return SDValue();
899
900  EVT PVT = VT;
901  // Consult target whether it is a good idea to promote this operation and
902  // what's the right type to promote it to.
903  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
904    assert(PVT != VT && "Don't know what type to promote to!");
905
906    bool Replace = false;
907    SDValue N0 = Op.getOperand(0);
908    if (Opc == ISD::SRA)
909      N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
910    else if (Opc == ISD::SRL)
911      N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
912    else
913      N0 = PromoteOperand(N0, PVT, Replace);
914    if (N0.getNode() == 0)
915      return SDValue();
916
917    AddToWorkList(N0.getNode());
918    if (Replace)
919      ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
920
921    DEBUG(dbgs() << "\nPromoting ";
922          Op.getNode()->dump(&DAG));
923    SDLoc dl(Op);
924    return DAG.getNode(ISD::TRUNCATE, dl, VT,
925                       DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
926  }
927  return SDValue();
928}
929
930SDValue DAGCombiner::PromoteExtend(SDValue Op) {
931  if (!LegalOperations)
932    return SDValue();
933
934  EVT VT = Op.getValueType();
935  if (VT.isVector() || !VT.isInteger())
936    return SDValue();
937
938  // If operation type is 'undesirable', e.g. i16 on x86, consider
939  // promoting it.
940  unsigned Opc = Op.getOpcode();
941  if (TLI.isTypeDesirableForOp(Opc, VT))
942    return SDValue();
943
944  EVT PVT = VT;
945  // Consult target whether it is a good idea to promote this operation and
946  // what's the right type to promote it to.
947  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
948    assert(PVT != VT && "Don't know what type to promote to!");
949    // fold (aext (aext x)) -> (aext x)
950    // fold (aext (zext x)) -> (zext x)
951    // fold (aext (sext x)) -> (sext x)
952    DEBUG(dbgs() << "\nPromoting ";
953          Op.getNode()->dump(&DAG));
954    return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
955  }
956  return SDValue();
957}
958
959bool DAGCombiner::PromoteLoad(SDValue Op) {
960  if (!LegalOperations)
961    return false;
962
963  EVT VT = Op.getValueType();
964  if (VT.isVector() || !VT.isInteger())
965    return false;
966
967  // If operation type is 'undesirable', e.g. i16 on x86, consider
968  // promoting it.
969  unsigned Opc = Op.getOpcode();
970  if (TLI.isTypeDesirableForOp(Opc, VT))
971    return false;
972
973  EVT PVT = VT;
974  // Consult target whether it is a good idea to promote this operation and
975  // what's the right type to promote it to.
976  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
977    assert(PVT != VT && "Don't know what type to promote to!");
978
979    SDLoc dl(Op);
980    SDNode *N = Op.getNode();
981    LoadSDNode *LD = cast<LoadSDNode>(N);
982    EVT MemVT = LD->getMemoryVT();
983    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
984      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
985                                                  : ISD::EXTLOAD)
986      : LD->getExtensionType();
987    SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
988                                   LD->getChain(), LD->getBasePtr(),
989                                   MemVT, LD->getMemOperand());
990    SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
991
992    DEBUG(dbgs() << "\nPromoting ";
993          N->dump(&DAG);
994          dbgs() << "\nTo: ";
995          Result.getNode()->dump(&DAG);
996          dbgs() << '\n');
997    WorkListRemover DeadNodes(*this);
998    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
999    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1000    removeFromWorkList(N);
1001    DAG.DeleteNode(N);
1002    AddToWorkList(Result.getNode());
1003    return true;
1004  }
1005  return false;
1006}
1007
1008
1009//===----------------------------------------------------------------------===//
1010//  Main DAG Combiner implementation
1011//===----------------------------------------------------------------------===//
1012
1013void DAGCombiner::Run(CombineLevel AtLevel) {
1014  // set the instance variables, so that the various visit routines may use it.
1015  Level = AtLevel;
1016  LegalOperations = Level >= AfterLegalizeVectorOps;
1017  LegalTypes = Level >= AfterLegalizeTypes;
1018
1019  // Add all the dag nodes to the worklist.
1020  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1021       E = DAG.allnodes_end(); I != E; ++I)
1022    AddToWorkList(I);
1023
1024  // Create a dummy node (which is not added to allnodes), that adds a reference
1025  // to the root node, preventing it from being deleted, and tracking any
1026  // changes of the root.
1027  HandleSDNode Dummy(DAG.getRoot());
1028
1029  // The root of the dag may dangle to deleted nodes until the dag combiner is
1030  // done.  Set it to null to avoid confusion.
1031  DAG.setRoot(SDValue());
1032
1033  // while the worklist isn't empty, find a node and
1034  // try and combine it.
1035  while (!WorkListContents.empty()) {
1036    SDNode *N;
1037    // The WorkListOrder holds the SDNodes in order, but it may contain
1038    // duplicates.
1039    // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1040    // worklist *should* contain, and check the node we want to visit is should
1041    // actually be visited.
1042    do {
1043      N = WorkListOrder.pop_back_val();
1044    } while (!WorkListContents.erase(N));
1045
1046    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1047    // N is deleted from the DAG, since they too may now be dead or may have a
1048    // reduced number of uses, allowing other xforms.
1049    if (N->use_empty() && N != &Dummy) {
1050      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1051        AddToWorkList(N->getOperand(i).getNode());
1052
1053      DAG.DeleteNode(N);
1054      continue;
1055    }
1056
1057    SDValue RV = combine(N);
1058
1059    if (RV.getNode() == 0)
1060      continue;
1061
1062    ++NodesCombined;
1063
1064    // If we get back the same node we passed in, rather than a new node or
1065    // zero, we know that the node must have defined multiple values and
1066    // CombineTo was used.  Since CombineTo takes care of the worklist
1067    // mechanics for us, we have no work to do in this case.
1068    if (RV.getNode() == N)
1069      continue;
1070
1071    assert(N->getOpcode() != ISD::DELETED_NODE &&
1072           RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1073           "Node was deleted but visit returned new node!");
1074
1075    DEBUG(dbgs() << "\nReplacing.3 ";
1076          N->dump(&DAG);
1077          dbgs() << "\nWith: ";
1078          RV.getNode()->dump(&DAG);
1079          dbgs() << '\n');
1080
1081    // Transfer debug value.
1082    DAG.TransferDbgValues(SDValue(N, 0), RV);
1083    WorkListRemover DeadNodes(*this);
1084    if (N->getNumValues() == RV.getNode()->getNumValues())
1085      DAG.ReplaceAllUsesWith(N, RV.getNode());
1086    else {
1087      assert(N->getValueType(0) == RV.getValueType() &&
1088             N->getNumValues() == 1 && "Type mismatch");
1089      SDValue OpV = RV;
1090      DAG.ReplaceAllUsesWith(N, &OpV);
1091    }
1092
1093    // Push the new node and any users onto the worklist
1094    AddToWorkList(RV.getNode());
1095    AddUsersToWorkList(RV.getNode());
1096
1097    // Add any uses of the old node to the worklist in case this node is the
1098    // last one that uses them.  They may become dead after this node is
1099    // deleted.
1100    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1101      AddToWorkList(N->getOperand(i).getNode());
1102
1103    // Finally, if the node is now dead, remove it from the graph.  The node
1104    // may not be dead if the replacement process recursively simplified to
1105    // something else needing this node.
1106    if (N->use_empty()) {
1107      // Nodes can be reintroduced into the worklist.  Make sure we do not
1108      // process a node that has been replaced.
1109      removeFromWorkList(N);
1110
1111      // Finally, since the node is now dead, remove it from the graph.
1112      DAG.DeleteNode(N);
1113    }
1114  }
1115
1116  // If the root changed (e.g. it was a dead load, update the root).
1117  DAG.setRoot(Dummy.getValue());
1118  DAG.RemoveDeadNodes();
1119}
1120
1121SDValue DAGCombiner::visit(SDNode *N) {
1122  switch (N->getOpcode()) {
1123  default: break;
1124  case ISD::TokenFactor:        return visitTokenFactor(N);
1125  case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1126  case ISD::ADD:                return visitADD(N);
1127  case ISD::SUB:                return visitSUB(N);
1128  case ISD::ADDC:               return visitADDC(N);
1129  case ISD::SUBC:               return visitSUBC(N);
1130  case ISD::ADDE:               return visitADDE(N);
1131  case ISD::SUBE:               return visitSUBE(N);
1132  case ISD::MUL:                return visitMUL(N);
1133  case ISD::SDIV:               return visitSDIV(N);
1134  case ISD::UDIV:               return visitUDIV(N);
1135  case ISD::SREM:               return visitSREM(N);
1136  case ISD::UREM:               return visitUREM(N);
1137  case ISD::MULHU:              return visitMULHU(N);
1138  case ISD::MULHS:              return visitMULHS(N);
1139  case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1140  case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1141  case ISD::SMULO:              return visitSMULO(N);
1142  case ISD::UMULO:              return visitUMULO(N);
1143  case ISD::SDIVREM:            return visitSDIVREM(N);
1144  case ISD::UDIVREM:            return visitUDIVREM(N);
1145  case ISD::AND:                return visitAND(N);
1146  case ISD::OR:                 return visitOR(N);
1147  case ISD::XOR:                return visitXOR(N);
1148  case ISD::SHL:                return visitSHL(N);
1149  case ISD::SRA:                return visitSRA(N);
1150  case ISD::SRL:                return visitSRL(N);
1151  case ISD::CTLZ:               return visitCTLZ(N);
1152  case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1153  case ISD::CTTZ:               return visitCTTZ(N);
1154  case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1155  case ISD::CTPOP:              return visitCTPOP(N);
1156  case ISD::SELECT:             return visitSELECT(N);
1157  case ISD::VSELECT:            return visitVSELECT(N);
1158  case ISD::SELECT_CC:          return visitSELECT_CC(N);
1159  case ISD::SETCC:              return visitSETCC(N);
1160  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1161  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1162  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1163  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1164  case ISD::TRUNCATE:           return visitTRUNCATE(N);
1165  case ISD::BITCAST:            return visitBITCAST(N);
1166  case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1167  case ISD::FADD:               return visitFADD(N);
1168  case ISD::FSUB:               return visitFSUB(N);
1169  case ISD::FMUL:               return visitFMUL(N);
1170  case ISD::FMA:                return visitFMA(N);
1171  case ISD::FDIV:               return visitFDIV(N);
1172  case ISD::FREM:               return visitFREM(N);
1173  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1174  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1175  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1176  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1177  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1178  case ISD::FP_ROUND:           return visitFP_ROUND(N);
1179  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1180  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1181  case ISD::FNEG:               return visitFNEG(N);
1182  case ISD::FABS:               return visitFABS(N);
1183  case ISD::FFLOOR:             return visitFFLOOR(N);
1184  case ISD::FCEIL:              return visitFCEIL(N);
1185  case ISD::FTRUNC:             return visitFTRUNC(N);
1186  case ISD::BRCOND:             return visitBRCOND(N);
1187  case ISD::BR_CC:              return visitBR_CC(N);
1188  case ISD::LOAD:               return visitLOAD(N);
1189  case ISD::STORE:              return visitSTORE(N);
1190  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1191  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1192  case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1193  case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1194  case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1195  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1196  }
1197  return SDValue();
1198}
1199
1200SDValue DAGCombiner::combine(SDNode *N) {
1201  SDValue RV = visit(N);
1202
1203  // If nothing happened, try a target-specific DAG combine.
1204  if (RV.getNode() == 0) {
1205    assert(N->getOpcode() != ISD::DELETED_NODE &&
1206           "Node was deleted but visit returned NULL!");
1207
1208    if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1209        TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1210
1211      // Expose the DAG combiner to the target combiner impls.
1212      TargetLowering::DAGCombinerInfo
1213        DagCombineInfo(DAG, Level, false, this);
1214
1215      RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1216    }
1217  }
1218
1219  // If nothing happened still, try promoting the operation.
1220  if (RV.getNode() == 0) {
1221    switch (N->getOpcode()) {
1222    default: break;
1223    case ISD::ADD:
1224    case ISD::SUB:
1225    case ISD::MUL:
1226    case ISD::AND:
1227    case ISD::OR:
1228    case ISD::XOR:
1229      RV = PromoteIntBinOp(SDValue(N, 0));
1230      break;
1231    case ISD::SHL:
1232    case ISD::SRA:
1233    case ISD::SRL:
1234      RV = PromoteIntShiftOp(SDValue(N, 0));
1235      break;
1236    case ISD::SIGN_EXTEND:
1237    case ISD::ZERO_EXTEND:
1238    case ISD::ANY_EXTEND:
1239      RV = PromoteExtend(SDValue(N, 0));
1240      break;
1241    case ISD::LOAD:
1242      if (PromoteLoad(SDValue(N, 0)))
1243        RV = SDValue(N, 0);
1244      break;
1245    }
1246  }
1247
1248  // If N is a commutative binary node, try commuting it to enable more
1249  // sdisel CSE.
1250  if (RV.getNode() == 0 &&
1251      SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1252      N->getNumValues() == 1) {
1253    SDValue N0 = N->getOperand(0);
1254    SDValue N1 = N->getOperand(1);
1255
1256    // Constant operands are canonicalized to RHS.
1257    if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1258      SDValue Ops[] = { N1, N0 };
1259      SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1260                                            Ops, 2);
1261      if (CSENode)
1262        return SDValue(CSENode, 0);
1263    }
1264  }
1265
1266  return RV;
1267}
1268
1269/// getInputChainForNode - Given a node, return its input chain if it has one,
1270/// otherwise return a null sd operand.
1271static SDValue getInputChainForNode(SDNode *N) {
1272  if (unsigned NumOps = N->getNumOperands()) {
1273    if (N->getOperand(0).getValueType() == MVT::Other)
1274      return N->getOperand(0);
1275    if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1276      return N->getOperand(NumOps-1);
1277    for (unsigned i = 1; i < NumOps-1; ++i)
1278      if (N->getOperand(i).getValueType() == MVT::Other)
1279        return N->getOperand(i);
1280  }
1281  return SDValue();
1282}
1283
1284SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1285  // If N has two operands, where one has an input chain equal to the other,
1286  // the 'other' chain is redundant.
1287  if (N->getNumOperands() == 2) {
1288    if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1289      return N->getOperand(0);
1290    if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1291      return N->getOperand(1);
1292  }
1293
1294  SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1295  SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1296  SmallPtrSet<SDNode*, 16> SeenOps;
1297  bool Changed = false;             // If we should replace this token factor.
1298
1299  // Start out with this token factor.
1300  TFs.push_back(N);
1301
1302  // Iterate through token factors.  The TFs grows when new token factors are
1303  // encountered.
1304  for (unsigned i = 0; i < TFs.size(); ++i) {
1305    SDNode *TF = TFs[i];
1306
1307    // Check each of the operands.
1308    for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1309      SDValue Op = TF->getOperand(i);
1310
1311      switch (Op.getOpcode()) {
1312      case ISD::EntryToken:
1313        // Entry tokens don't need to be added to the list. They are
1314        // rededundant.
1315        Changed = true;
1316        break;
1317
1318      case ISD::TokenFactor:
1319        if (Op.hasOneUse() &&
1320            std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1321          // Queue up for processing.
1322          TFs.push_back(Op.getNode());
1323          // Clean up in case the token factor is removed.
1324          AddToWorkList(Op.getNode());
1325          Changed = true;
1326          break;
1327        }
1328        // Fall thru
1329
1330      default:
1331        // Only add if it isn't already in the list.
1332        if (SeenOps.insert(Op.getNode()))
1333          Ops.push_back(Op);
1334        else
1335          Changed = true;
1336        break;
1337      }
1338    }
1339  }
1340
1341  SDValue Result;
1342
1343  // If we've change things around then replace token factor.
1344  if (Changed) {
1345    if (Ops.empty()) {
1346      // The entry token is the only possible outcome.
1347      Result = DAG.getEntryNode();
1348    } else {
1349      // New and improved token factor.
1350      Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1351                           MVT::Other, &Ops[0], Ops.size());
1352    }
1353
1354    // Don't add users to work list.
1355    return CombineTo(N, Result, false);
1356  }
1357
1358  return Result;
1359}
1360
1361/// MERGE_VALUES can always be eliminated.
1362SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1363  WorkListRemover DeadNodes(*this);
1364  // Replacing results may cause a different MERGE_VALUES to suddenly
1365  // be CSE'd with N, and carry its uses with it. Iterate until no
1366  // uses remain, to ensure that the node can be safely deleted.
1367  // First add the users of this node to the work list so that they
1368  // can be tried again once they have new operands.
1369  AddUsersToWorkList(N);
1370  do {
1371    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1372      DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1373  } while (!N->use_empty());
1374  removeFromWorkList(N);
1375  DAG.DeleteNode(N);
1376  return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1377}
1378
1379static
1380SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1381                              SelectionDAG &DAG) {
1382  EVT VT = N0.getValueType();
1383  SDValue N00 = N0.getOperand(0);
1384  SDValue N01 = N0.getOperand(1);
1385  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1386
1387  if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1388      isa<ConstantSDNode>(N00.getOperand(1))) {
1389    // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1390    N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1391                     DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1392                                 N00.getOperand(0), N01),
1393                     DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1394                                 N00.getOperand(1), N01));
1395    return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1396  }
1397
1398  return SDValue();
1399}
1400
1401SDValue DAGCombiner::visitADD(SDNode *N) {
1402  SDValue N0 = N->getOperand(0);
1403  SDValue N1 = N->getOperand(1);
1404  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1405  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1406  EVT VT = N0.getValueType();
1407
1408  // fold vector ops
1409  if (VT.isVector()) {
1410    SDValue FoldedVOp = SimplifyVBinOp(N);
1411    if (FoldedVOp.getNode()) return FoldedVOp;
1412
1413    // fold (add x, 0) -> x, vector edition
1414    if (ISD::isBuildVectorAllZeros(N1.getNode()))
1415      return N0;
1416    if (ISD::isBuildVectorAllZeros(N0.getNode()))
1417      return N1;
1418  }
1419
1420  // fold (add x, undef) -> undef
1421  if (N0.getOpcode() == ISD::UNDEF)
1422    return N0;
1423  if (N1.getOpcode() == ISD::UNDEF)
1424    return N1;
1425  // fold (add c1, c2) -> c1+c2
1426  if (N0C && N1C)
1427    return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1428  // canonicalize constant to RHS
1429  if (N0C && !N1C)
1430    return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1431  // fold (add x, 0) -> x
1432  if (N1C && N1C->isNullValue())
1433    return N0;
1434  // fold (add Sym, c) -> Sym+c
1435  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1436    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1437        GA->getOpcode() == ISD::GlobalAddress)
1438      return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1439                                  GA->getOffset() +
1440                                    (uint64_t)N1C->getSExtValue());
1441  // fold ((c1-A)+c2) -> (c1+c2)-A
1442  if (N1C && N0.getOpcode() == ISD::SUB)
1443    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1444      return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1445                         DAG.getConstant(N1C->getAPIntValue()+
1446                                         N0C->getAPIntValue(), VT),
1447                         N0.getOperand(1));
1448  // reassociate add
1449  SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1450  if (RADD.getNode() != 0)
1451    return RADD;
1452  // fold ((0-A) + B) -> B-A
1453  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1454      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1455    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1456  // fold (A + (0-B)) -> A-B
1457  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1458      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1459    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1460  // fold (A+(B-A)) -> B
1461  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1462    return N1.getOperand(0);
1463  // fold ((B-A)+A) -> B
1464  if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1465    return N0.getOperand(0);
1466  // fold (A+(B-(A+C))) to (B-C)
1467  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1468      N0 == N1.getOperand(1).getOperand(0))
1469    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1470                       N1.getOperand(1).getOperand(1));
1471  // fold (A+(B-(C+A))) to (B-C)
1472  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1473      N0 == N1.getOperand(1).getOperand(1))
1474    return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1475                       N1.getOperand(1).getOperand(0));
1476  // fold (A+((B-A)+or-C)) to (B+or-C)
1477  if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1478      N1.getOperand(0).getOpcode() == ISD::SUB &&
1479      N0 == N1.getOperand(0).getOperand(1))
1480    return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1481                       N1.getOperand(0).getOperand(0), N1.getOperand(1));
1482
1483  // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1484  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1485    SDValue N00 = N0.getOperand(0);
1486    SDValue N01 = N0.getOperand(1);
1487    SDValue N10 = N1.getOperand(0);
1488    SDValue N11 = N1.getOperand(1);
1489
1490    if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1491      return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492                         DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1493                         DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1494  }
1495
1496  if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1497    return SDValue(N, 0);
1498
1499  // fold (a+b) -> (a|b) iff a and b share no bits.
1500  if (VT.isInteger() && !VT.isVector()) {
1501    APInt LHSZero, LHSOne;
1502    APInt RHSZero, RHSOne;
1503    DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1504
1505    if (LHSZero.getBoolValue()) {
1506      DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1507
1508      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1509      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1510      if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1511        return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1512    }
1513  }
1514
1515  // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1516  if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1517    SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1518    if (Result.getNode()) return Result;
1519  }
1520  if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1521    SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1522    if (Result.getNode()) return Result;
1523  }
1524
1525  // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1526  if (N1.getOpcode() == ISD::SHL &&
1527      N1.getOperand(0).getOpcode() == ISD::SUB)
1528    if (ConstantSDNode *C =
1529          dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1530      if (C->getAPIntValue() == 0)
1531        return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1532                           DAG.getNode(ISD::SHL, SDLoc(N), VT,
1533                                       N1.getOperand(0).getOperand(1),
1534                                       N1.getOperand(1)));
1535  if (N0.getOpcode() == ISD::SHL &&
1536      N0.getOperand(0).getOpcode() == ISD::SUB)
1537    if (ConstantSDNode *C =
1538          dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1539      if (C->getAPIntValue() == 0)
1540        return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1541                           DAG.getNode(ISD::SHL, SDLoc(N), VT,
1542                                       N0.getOperand(0).getOperand(1),
1543                                       N0.getOperand(1)));
1544
1545  if (N1.getOpcode() == ISD::AND) {
1546    SDValue AndOp0 = N1.getOperand(0);
1547    ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1548    unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1549    unsigned DestBits = VT.getScalarType().getSizeInBits();
1550
1551    // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1552    // and similar xforms where the inner op is either ~0 or 0.
1553    if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1554      SDLoc DL(N);
1555      return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1556    }
1557  }
1558
1559  // add (sext i1), X -> sub X, (zext i1)
1560  if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1561      N0.getOperand(0).getValueType() == MVT::i1 &&
1562      !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1563    SDLoc DL(N);
1564    SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1565    return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1566  }
1567
1568  return SDValue();
1569}
1570
1571SDValue DAGCombiner::visitADDC(SDNode *N) {
1572  SDValue N0 = N->getOperand(0);
1573  SDValue N1 = N->getOperand(1);
1574  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1575  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1576  EVT VT = N0.getValueType();
1577
1578  // If the flag result is dead, turn this into an ADD.
1579  if (!N->hasAnyUseOfValue(1))
1580    return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1581                     DAG.getNode(ISD::CARRY_FALSE,
1582                                 SDLoc(N), MVT::Glue));
1583
1584  // canonicalize constant to RHS.
1585  if (N0C && !N1C)
1586    return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1587
1588  // fold (addc x, 0) -> x + no carry out
1589  if (N1C && N1C->isNullValue())
1590    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1591                                        SDLoc(N), MVT::Glue));
1592
1593  // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1594  APInt LHSZero, LHSOne;
1595  APInt RHSZero, RHSOne;
1596  DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1597
1598  if (LHSZero.getBoolValue()) {
1599    DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1600
1601    // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1602    // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1603    if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1604      return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1605                       DAG.getNode(ISD::CARRY_FALSE,
1606                                   SDLoc(N), MVT::Glue));
1607  }
1608
1609  return SDValue();
1610}
1611
1612SDValue DAGCombiner::visitADDE(SDNode *N) {
1613  SDValue N0 = N->getOperand(0);
1614  SDValue N1 = N->getOperand(1);
1615  SDValue CarryIn = N->getOperand(2);
1616  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1617  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1618
1619  // canonicalize constant to RHS
1620  if (N0C && !N1C)
1621    return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1622                       N1, N0, CarryIn);
1623
1624  // fold (adde x, y, false) -> (addc x, y)
1625  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1626    return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1627
1628  return SDValue();
1629}
1630
1631// Since it may not be valid to emit a fold to zero for vector initializers
1632// check if we can before folding.
1633static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1634                             SelectionDAG &DAG,
1635                             bool LegalOperations, bool LegalTypes) {
1636  if (!VT.isVector())
1637    return DAG.getConstant(0, VT);
1638  if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1639    return DAG.getConstant(0, VT);
1640  return SDValue();
1641}
1642
1643SDValue DAGCombiner::visitSUB(SDNode *N) {
1644  SDValue N0 = N->getOperand(0);
1645  SDValue N1 = N->getOperand(1);
1646  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1647  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1648  ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1649    dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1650  EVT VT = N0.getValueType();
1651
1652  // fold vector ops
1653  if (VT.isVector()) {
1654    SDValue FoldedVOp = SimplifyVBinOp(N);
1655    if (FoldedVOp.getNode()) return FoldedVOp;
1656
1657    // fold (sub x, 0) -> x, vector edition
1658    if (ISD::isBuildVectorAllZeros(N1.getNode()))
1659      return N0;
1660  }
1661
1662  // fold (sub x, x) -> 0
1663  // FIXME: Refactor this and xor and other similar operations together.
1664  if (N0 == N1)
1665    return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1666  // fold (sub c1, c2) -> c1-c2
1667  if (N0C && N1C)
1668    return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1669  // fold (sub x, c) -> (add x, -c)
1670  if (N1C)
1671    return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1672                       DAG.getConstant(-N1C->getAPIntValue(), VT));
1673  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1674  if (N0C && N0C->isAllOnesValue())
1675    return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1676  // fold A-(A-B) -> B
1677  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1678    return N1.getOperand(1);
1679  // fold (A+B)-A -> B
1680  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1681    return N0.getOperand(1);
1682  // fold (A+B)-B -> A
1683  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1684    return N0.getOperand(0);
1685  // fold C2-(A+C1) -> (C2-C1)-A
1686  if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1687    SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1688                                   VT);
1689    return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1690                       N1.getOperand(0));
1691  }
1692  // fold ((A+(B+or-C))-B) -> A+or-C
1693  if (N0.getOpcode() == ISD::ADD &&
1694      (N0.getOperand(1).getOpcode() == ISD::SUB ||
1695       N0.getOperand(1).getOpcode() == ISD::ADD) &&
1696      N0.getOperand(1).getOperand(0) == N1)
1697    return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1698                       N0.getOperand(0), N0.getOperand(1).getOperand(1));
1699  // fold ((A+(C+B))-B) -> A+C
1700  if (N0.getOpcode() == ISD::ADD &&
1701      N0.getOperand(1).getOpcode() == ISD::ADD &&
1702      N0.getOperand(1).getOperand(1) == N1)
1703    return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1704                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1705  // fold ((A-(B-C))-C) -> A-B
1706  if (N0.getOpcode() == ISD::SUB &&
1707      N0.getOperand(1).getOpcode() == ISD::SUB &&
1708      N0.getOperand(1).getOperand(1) == N1)
1709    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1710                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1711
1712  // If either operand of a sub is undef, the result is undef
1713  if (N0.getOpcode() == ISD::UNDEF)
1714    return N0;
1715  if (N1.getOpcode() == ISD::UNDEF)
1716    return N1;
1717
1718  // If the relocation model supports it, consider symbol offsets.
1719  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1720    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1721      // fold (sub Sym, c) -> Sym-c
1722      if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1723        return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1724                                    GA->getOffset() -
1725                                      (uint64_t)N1C->getSExtValue());
1726      // fold (sub Sym+c1, Sym+c2) -> c1-c2
1727      if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1728        if (GA->getGlobal() == GB->getGlobal())
1729          return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1730                                 VT);
1731    }
1732
1733  return SDValue();
1734}
1735
1736SDValue DAGCombiner::visitSUBC(SDNode *N) {
1737  SDValue N0 = N->getOperand(0);
1738  SDValue N1 = N->getOperand(1);
1739  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1740  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1741  EVT VT = N0.getValueType();
1742
1743  // If the flag result is dead, turn this into an SUB.
1744  if (!N->hasAnyUseOfValue(1))
1745    return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1746                     DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1747                                 MVT::Glue));
1748
1749  // fold (subc x, x) -> 0 + no borrow
1750  if (N0 == N1)
1751    return CombineTo(N, DAG.getConstant(0, VT),
1752                     DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1753                                 MVT::Glue));
1754
1755  // fold (subc x, 0) -> x + no borrow
1756  if (N1C && N1C->isNullValue())
1757    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1758                                        MVT::Glue));
1759
1760  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1761  if (N0C && N0C->isAllOnesValue())
1762    return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1763                     DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1764                                 MVT::Glue));
1765
1766  return SDValue();
1767}
1768
1769SDValue DAGCombiner::visitSUBE(SDNode *N) {
1770  SDValue N0 = N->getOperand(0);
1771  SDValue N1 = N->getOperand(1);
1772  SDValue CarryIn = N->getOperand(2);
1773
1774  // fold (sube x, y, false) -> (subc x, y)
1775  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1776    return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1777
1778  return SDValue();
1779}
1780
1781/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1782/// elements are all the same constant or undefined.
1783static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1784  BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1785  if (!C)
1786    return false;
1787
1788  APInt SplatUndef;
1789  unsigned SplatBitSize;
1790  bool HasAnyUndefs;
1791  EVT EltVT = N->getValueType(0).getVectorElementType();
1792  return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1793                             HasAnyUndefs) &&
1794          EltVT.getSizeInBits() >= SplatBitSize);
1795}
1796
1797SDValue DAGCombiner::visitMUL(SDNode *N) {
1798  SDValue N0 = N->getOperand(0);
1799  SDValue N1 = N->getOperand(1);
1800  EVT VT = N0.getValueType();
1801
1802  // fold (mul x, undef) -> 0
1803  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1804    return DAG.getConstant(0, VT);
1805
1806  bool N0IsConst = false;
1807  bool N1IsConst = false;
1808  APInt ConstValue0, ConstValue1;
1809  // fold vector ops
1810  if (VT.isVector()) {
1811    SDValue FoldedVOp = SimplifyVBinOp(N);
1812    if (FoldedVOp.getNode()) return FoldedVOp;
1813
1814    N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1815    N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1816  } else {
1817    N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1818    ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1819                            : APInt();
1820    N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1821    ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1822                            : APInt();
1823  }
1824
1825  // fold (mul c1, c2) -> c1*c2
1826  if (N0IsConst && N1IsConst)
1827    return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1828
1829  // canonicalize constant to RHS
1830  if (N0IsConst && !N1IsConst)
1831    return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1832  // fold (mul x, 0) -> 0
1833  if (N1IsConst && ConstValue1 == 0)
1834    return N1;
1835  // We require a splat of the entire scalar bit width for non-contiguous
1836  // bit patterns.
1837  bool IsFullSplat =
1838    ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1839  // fold (mul x, 1) -> x
1840  if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1841    return N0;
1842  // fold (mul x, -1) -> 0-x
1843  if (N1IsConst && ConstValue1.isAllOnesValue())
1844    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1845                       DAG.getConstant(0, VT), N0);
1846  // fold (mul x, (1 << c)) -> x << c
1847  if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1848    return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1849                       DAG.getConstant(ConstValue1.logBase2(),
1850                                       getShiftAmountTy(N0.getValueType())));
1851  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1852  if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1853    unsigned Log2Val = (-ConstValue1).logBase2();
1854    // FIXME: If the input is something that is easily negated (e.g. a
1855    // single-use add), we should put the negate there.
1856    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857                       DAG.getConstant(0, VT),
1858                       DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1859                            DAG.getConstant(Log2Val,
1860                                      getShiftAmountTy(N0.getValueType()))));
1861  }
1862
1863  APInt Val;
1864  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1865  if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1866      (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1867                     isa<ConstantSDNode>(N0.getOperand(1)))) {
1868    SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1869                             N1, N0.getOperand(1));
1870    AddToWorkList(C3.getNode());
1871    return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1872                       N0.getOperand(0), C3);
1873  }
1874
1875  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1876  // use.
1877  {
1878    SDValue Sh(0,0), Y(0,0);
1879    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1880    if (N0.getOpcode() == ISD::SHL &&
1881        (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1882                       isa<ConstantSDNode>(N0.getOperand(1))) &&
1883        N0.getNode()->hasOneUse()) {
1884      Sh = N0; Y = N1;
1885    } else if (N1.getOpcode() == ISD::SHL &&
1886               isa<ConstantSDNode>(N1.getOperand(1)) &&
1887               N1.getNode()->hasOneUse()) {
1888      Sh = N1; Y = N0;
1889    }
1890
1891    if (Sh.getNode()) {
1892      SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1893                                Sh.getOperand(0), Y);
1894      return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1895                         Mul, Sh.getOperand(1));
1896    }
1897  }
1898
1899  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1900  if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1901      (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1902                     isa<ConstantSDNode>(N0.getOperand(1))))
1903    return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1904                       DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1905                                   N0.getOperand(0), N1),
1906                       DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1907                                   N0.getOperand(1), N1));
1908
1909  // reassociate mul
1910  SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1911  if (RMUL.getNode() != 0)
1912    return RMUL;
1913
1914  return SDValue();
1915}
1916
1917SDValue DAGCombiner::visitSDIV(SDNode *N) {
1918  SDValue N0 = N->getOperand(0);
1919  SDValue N1 = N->getOperand(1);
1920  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1921  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1922  EVT VT = N->getValueType(0);
1923
1924  // fold vector ops
1925  if (VT.isVector()) {
1926    SDValue FoldedVOp = SimplifyVBinOp(N);
1927    if (FoldedVOp.getNode()) return FoldedVOp;
1928  }
1929
1930  // fold (sdiv c1, c2) -> c1/c2
1931  if (N0C && N1C && !N1C->isNullValue())
1932    return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1933  // fold (sdiv X, 1) -> X
1934  if (N1C && N1C->getAPIntValue() == 1LL)
1935    return N0;
1936  // fold (sdiv X, -1) -> 0-X
1937  if (N1C && N1C->isAllOnesValue())
1938    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1939                       DAG.getConstant(0, VT), N0);
1940  // If we know the sign bits of both operands are zero, strength reduce to a
1941  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1942  if (!VT.isVector()) {
1943    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1944      return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1945                         N0, N1);
1946  }
1947  // fold (sdiv X, pow2) -> simple ops after legalize
1948  if (N1C && !N1C->isNullValue() &&
1949      (N1C->getAPIntValue().isPowerOf2() ||
1950       (-N1C->getAPIntValue()).isPowerOf2())) {
1951    // If dividing by powers of two is cheap, then don't perform the following
1952    // fold.
1953    if (TLI.isPow2DivCheap())
1954      return SDValue();
1955
1956    unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1957
1958    // Splat the sign bit into the register
1959    SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1960                              DAG.getConstant(VT.getSizeInBits()-1,
1961                                       getShiftAmountTy(N0.getValueType())));
1962    AddToWorkList(SGN.getNode());
1963
1964    // Add (N0 < 0) ? abs2 - 1 : 0;
1965    SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1966                              DAG.getConstant(VT.getSizeInBits() - lg2,
1967                                       getShiftAmountTy(SGN.getValueType())));
1968    SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1969    AddToWorkList(SRL.getNode());
1970    AddToWorkList(ADD.getNode());    // Divide by pow2
1971    SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1972                  DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1973
1974    // If we're dividing by a positive value, we're done.  Otherwise, we must
1975    // negate the result.
1976    if (N1C->getAPIntValue().isNonNegative())
1977      return SRA;
1978
1979    AddToWorkList(SRA.getNode());
1980    return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1981                       DAG.getConstant(0, VT), SRA);
1982  }
1983
1984  // if integer divide is expensive and we satisfy the requirements, emit an
1985  // alternate sequence.
1986  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1987    SDValue Op = BuildSDIV(N);
1988    if (Op.getNode()) return Op;
1989  }
1990
1991  // undef / X -> 0
1992  if (N0.getOpcode() == ISD::UNDEF)
1993    return DAG.getConstant(0, VT);
1994  // X / undef -> undef
1995  if (N1.getOpcode() == ISD::UNDEF)
1996    return N1;
1997
1998  return SDValue();
1999}
2000
2001SDValue DAGCombiner::visitUDIV(SDNode *N) {
2002  SDValue N0 = N->getOperand(0);
2003  SDValue N1 = N->getOperand(1);
2004  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2005  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2006  EVT VT = N->getValueType(0);
2007
2008  // fold vector ops
2009  if (VT.isVector()) {
2010    SDValue FoldedVOp = SimplifyVBinOp(N);
2011    if (FoldedVOp.getNode()) return FoldedVOp;
2012  }
2013
2014  // fold (udiv c1, c2) -> c1/c2
2015  if (N0C && N1C && !N1C->isNullValue())
2016    return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2017  // fold (udiv x, (1 << c)) -> x >>u c
2018  if (N1C && N1C->getAPIntValue().isPowerOf2())
2019    return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2020                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
2021                                       getShiftAmountTy(N0.getValueType())));
2022  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2023  if (N1.getOpcode() == ISD::SHL) {
2024    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2025      if (SHC->getAPIntValue().isPowerOf2()) {
2026        EVT ADDVT = N1.getOperand(1).getValueType();
2027        SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2028                                  N1.getOperand(1),
2029                                  DAG.getConstant(SHC->getAPIntValue()
2030                                                                  .logBase2(),
2031                                                  ADDVT));
2032        AddToWorkList(Add.getNode());
2033        return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2034      }
2035    }
2036  }
2037  // fold (udiv x, c) -> alternate
2038  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2039    SDValue Op = BuildUDIV(N);
2040    if (Op.getNode()) return Op;
2041  }
2042
2043  // undef / X -> 0
2044  if (N0.getOpcode() == ISD::UNDEF)
2045    return DAG.getConstant(0, VT);
2046  // X / undef -> undef
2047  if (N1.getOpcode() == ISD::UNDEF)
2048    return N1;
2049
2050  return SDValue();
2051}
2052
2053SDValue DAGCombiner::visitSREM(SDNode *N) {
2054  SDValue N0 = N->getOperand(0);
2055  SDValue N1 = N->getOperand(1);
2056  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2057  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2058  EVT VT = N->getValueType(0);
2059
2060  // fold (srem c1, c2) -> c1%c2
2061  if (N0C && N1C && !N1C->isNullValue())
2062    return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2063  // If we know the sign bits of both operands are zero, strength reduce to a
2064  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2065  if (!VT.isVector()) {
2066    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2067      return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2068  }
2069
2070  // If X/C can be simplified by the division-by-constant logic, lower
2071  // X%C to the equivalent of X-X/C*C.
2072  if (N1C && !N1C->isNullValue()) {
2073    SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2074    AddToWorkList(Div.getNode());
2075    SDValue OptimizedDiv = combine(Div.getNode());
2076    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2077      SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2078                                OptimizedDiv, N1);
2079      SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2080      AddToWorkList(Mul.getNode());
2081      return Sub;
2082    }
2083  }
2084
2085  // undef % X -> 0
2086  if (N0.getOpcode() == ISD::UNDEF)
2087    return DAG.getConstant(0, VT);
2088  // X % undef -> undef
2089  if (N1.getOpcode() == ISD::UNDEF)
2090    return N1;
2091
2092  return SDValue();
2093}
2094
2095SDValue DAGCombiner::visitUREM(SDNode *N) {
2096  SDValue N0 = N->getOperand(0);
2097  SDValue N1 = N->getOperand(1);
2098  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2099  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2100  EVT VT = N->getValueType(0);
2101
2102  // fold (urem c1, c2) -> c1%c2
2103  if (N0C && N1C && !N1C->isNullValue())
2104    return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2105  // fold (urem x, pow2) -> (and x, pow2-1)
2106  if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2107    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2108                       DAG.getConstant(N1C->getAPIntValue()-1,VT));
2109  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2110  if (N1.getOpcode() == ISD::SHL) {
2111    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2112      if (SHC->getAPIntValue().isPowerOf2()) {
2113        SDValue Add =
2114          DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2115                 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2116                                 VT));
2117        AddToWorkList(Add.getNode());
2118        return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2119      }
2120    }
2121  }
2122
2123  // If X/C can be simplified by the division-by-constant logic, lower
2124  // X%C to the equivalent of X-X/C*C.
2125  if (N1C && !N1C->isNullValue()) {
2126    SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2127    AddToWorkList(Div.getNode());
2128    SDValue OptimizedDiv = combine(Div.getNode());
2129    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2130      SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2131                                OptimizedDiv, N1);
2132      SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2133      AddToWorkList(Mul.getNode());
2134      return Sub;
2135    }
2136  }
2137
2138  // undef % X -> 0
2139  if (N0.getOpcode() == ISD::UNDEF)
2140    return DAG.getConstant(0, VT);
2141  // X % undef -> undef
2142  if (N1.getOpcode() == ISD::UNDEF)
2143    return N1;
2144
2145  return SDValue();
2146}
2147
2148SDValue DAGCombiner::visitMULHS(SDNode *N) {
2149  SDValue N0 = N->getOperand(0);
2150  SDValue N1 = N->getOperand(1);
2151  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2152  EVT VT = N->getValueType(0);
2153  SDLoc DL(N);
2154
2155  // fold (mulhs x, 0) -> 0
2156  if (N1C && N1C->isNullValue())
2157    return N1;
2158  // fold (mulhs x, 1) -> (sra x, size(x)-1)
2159  if (N1C && N1C->getAPIntValue() == 1)
2160    return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2161                       DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2162                                       getShiftAmountTy(N0.getValueType())));
2163  // fold (mulhs x, undef) -> 0
2164  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2165    return DAG.getConstant(0, VT);
2166
2167  // If the type twice as wide is legal, transform the mulhs to a wider multiply
2168  // plus a shift.
2169  if (VT.isSimple() && !VT.isVector()) {
2170    MVT Simple = VT.getSimpleVT();
2171    unsigned SimpleSize = Simple.getSizeInBits();
2172    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2173    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2174      N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2175      N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2176      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2177      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2178            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2179      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2180    }
2181  }
2182
2183  return SDValue();
2184}
2185
2186SDValue DAGCombiner::visitMULHU(SDNode *N) {
2187  SDValue N0 = N->getOperand(0);
2188  SDValue N1 = N->getOperand(1);
2189  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2190  EVT VT = N->getValueType(0);
2191  SDLoc DL(N);
2192
2193  // fold (mulhu x, 0) -> 0
2194  if (N1C && N1C->isNullValue())
2195    return N1;
2196  // fold (mulhu x, 1) -> 0
2197  if (N1C && N1C->getAPIntValue() == 1)
2198    return DAG.getConstant(0, N0.getValueType());
2199  // fold (mulhu x, undef) -> 0
2200  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2201    return DAG.getConstant(0, VT);
2202
2203  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2204  // plus a shift.
2205  if (VT.isSimple() && !VT.isVector()) {
2206    MVT Simple = VT.getSimpleVT();
2207    unsigned SimpleSize = Simple.getSizeInBits();
2208    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2209    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2210      N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2211      N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2212      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2213      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2214            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2215      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2216    }
2217  }
2218
2219  return SDValue();
2220}
2221
2222/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2223/// compute two values. LoOp and HiOp give the opcodes for the two computations
2224/// that are being performed. Return true if a simplification was made.
2225///
2226SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2227                                                unsigned HiOp) {
2228  // If the high half is not needed, just compute the low half.
2229  bool HiExists = N->hasAnyUseOfValue(1);
2230  if (!HiExists &&
2231      (!LegalOperations ||
2232       TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2233    SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2234                              N->op_begin(), N->getNumOperands());
2235    return CombineTo(N, Res, Res);
2236  }
2237
2238  // If the low half is not needed, just compute the high half.
2239  bool LoExists = N->hasAnyUseOfValue(0);
2240  if (!LoExists &&
2241      (!LegalOperations ||
2242       TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2243    SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2244                              N->op_begin(), N->getNumOperands());
2245    return CombineTo(N, Res, Res);
2246  }
2247
2248  // If both halves are used, return as it is.
2249  if (LoExists && HiExists)
2250    return SDValue();
2251
2252  // If the two computed results can be simplified separately, separate them.
2253  if (LoExists) {
2254    SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2255                             N->op_begin(), N->getNumOperands());
2256    AddToWorkList(Lo.getNode());
2257    SDValue LoOpt = combine(Lo.getNode());
2258    if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2259        (!LegalOperations ||
2260         TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2261      return CombineTo(N, LoOpt, LoOpt);
2262  }
2263
2264  if (HiExists) {
2265    SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2266                             N->op_begin(), N->getNumOperands());
2267    AddToWorkList(Hi.getNode());
2268    SDValue HiOpt = combine(Hi.getNode());
2269    if (HiOpt.getNode() && HiOpt != Hi &&
2270        (!LegalOperations ||
2271         TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2272      return CombineTo(N, HiOpt, HiOpt);
2273  }
2274
2275  return SDValue();
2276}
2277
2278SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2279  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2280  if (Res.getNode()) return Res;
2281
2282  EVT VT = N->getValueType(0);
2283  SDLoc DL(N);
2284
2285  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2286  // plus a shift.
2287  if (VT.isSimple() && !VT.isVector()) {
2288    MVT Simple = VT.getSimpleVT();
2289    unsigned SimpleSize = Simple.getSizeInBits();
2290    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2291    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2292      SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2293      SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2294      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2295      // Compute the high part as N1.
2296      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2297            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2298      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2299      // Compute the low part as N0.
2300      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2301      return CombineTo(N, Lo, Hi);
2302    }
2303  }
2304
2305  return SDValue();
2306}
2307
2308SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2309  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2310  if (Res.getNode()) return Res;
2311
2312  EVT VT = N->getValueType(0);
2313  SDLoc DL(N);
2314
2315  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2316  // plus a shift.
2317  if (VT.isSimple() && !VT.isVector()) {
2318    MVT Simple = VT.getSimpleVT();
2319    unsigned SimpleSize = Simple.getSizeInBits();
2320    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322      SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2323      SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2324      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2325      // Compute the high part as N1.
2326      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2327            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2328      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2329      // Compute the low part as N0.
2330      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2331      return CombineTo(N, Lo, Hi);
2332    }
2333  }
2334
2335  return SDValue();
2336}
2337
2338SDValue DAGCombiner::visitSMULO(SDNode *N) {
2339  // (smulo x, 2) -> (saddo x, x)
2340  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2341    if (C2->getAPIntValue() == 2)
2342      return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2343                         N->getOperand(0), N->getOperand(0));
2344
2345  return SDValue();
2346}
2347
2348SDValue DAGCombiner::visitUMULO(SDNode *N) {
2349  // (umulo x, 2) -> (uaddo x, x)
2350  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2351    if (C2->getAPIntValue() == 2)
2352      return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2353                         N->getOperand(0), N->getOperand(0));
2354
2355  return SDValue();
2356}
2357
2358SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2359  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2360  if (Res.getNode()) return Res;
2361
2362  return SDValue();
2363}
2364
2365SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2366  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2367  if (Res.getNode()) return Res;
2368
2369  return SDValue();
2370}
2371
2372/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2373/// two operands of the same opcode, try to simplify it.
2374SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2375  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2376  EVT VT = N0.getValueType();
2377  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2378
2379  // Bail early if none of these transforms apply.
2380  if (N0.getNode()->getNumOperands() == 0) return SDValue();
2381
2382  // For each of OP in AND/OR/XOR:
2383  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2384  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2385  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2386  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2387  //
2388  // do not sink logical op inside of a vector extend, since it may combine
2389  // into a vsetcc.
2390  EVT Op0VT = N0.getOperand(0).getValueType();
2391  if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2392       N0.getOpcode() == ISD::SIGN_EXTEND ||
2393       // Avoid infinite looping with PromoteIntBinOp.
2394       (N0.getOpcode() == ISD::ANY_EXTEND &&
2395        (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2396       (N0.getOpcode() == ISD::TRUNCATE &&
2397        (!TLI.isZExtFree(VT, Op0VT) ||
2398         !TLI.isTruncateFree(Op0VT, VT)) &&
2399        TLI.isTypeLegal(Op0VT))) &&
2400      !VT.isVector() &&
2401      Op0VT == N1.getOperand(0).getValueType() &&
2402      (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2403    SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2404                                 N0.getOperand(0).getValueType(),
2405                                 N0.getOperand(0), N1.getOperand(0));
2406    AddToWorkList(ORNode.getNode());
2407    return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2408  }
2409
2410  // For each of OP in SHL/SRL/SRA/AND...
2411  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2412  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2413  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2414  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2415       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2416      N0.getOperand(1) == N1.getOperand(1)) {
2417    SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2418                                 N0.getOperand(0).getValueType(),
2419                                 N0.getOperand(0), N1.getOperand(0));
2420    AddToWorkList(ORNode.getNode());
2421    return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2422                       ORNode, N0.getOperand(1));
2423  }
2424
2425  // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2426  // Only perform this optimization after type legalization and before
2427  // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2428  // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2429  // we don't want to undo this promotion.
2430  // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2431  // on scalars.
2432  if ((N0.getOpcode() == ISD::BITCAST ||
2433       N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2434      Level == AfterLegalizeTypes) {
2435    SDValue In0 = N0.getOperand(0);
2436    SDValue In1 = N1.getOperand(0);
2437    EVT In0Ty = In0.getValueType();
2438    EVT In1Ty = In1.getValueType();
2439    SDLoc DL(N);
2440    // If both incoming values are integers, and the original types are the
2441    // same.
2442    if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2443      SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2444      SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2445      AddToWorkList(Op.getNode());
2446      return BC;
2447    }
2448  }
2449
2450  // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2451  // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2452  // If both shuffles use the same mask, and both shuffle within a single
2453  // vector, then it is worthwhile to move the swizzle after the operation.
2454  // The type-legalizer generates this pattern when loading illegal
2455  // vector types from memory. In many cases this allows additional shuffle
2456  // optimizations.
2457  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2458      N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2459      N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2460    ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2461    ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2462
2463    assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2464           "Inputs to shuffles are not the same type");
2465
2466    unsigned NumElts = VT.getVectorNumElements();
2467
2468    // Check that both shuffles use the same mask. The masks are known to be of
2469    // the same length because the result vector type is the same.
2470    bool SameMask = true;
2471    for (unsigned i = 0; i != NumElts; ++i) {
2472      int Idx0 = SVN0->getMaskElt(i);
2473      int Idx1 = SVN1->getMaskElt(i);
2474      if (Idx0 != Idx1) {
2475        SameMask = false;
2476        break;
2477      }
2478    }
2479
2480    if (SameMask) {
2481      SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2482                               N0.getOperand(0), N1.getOperand(0));
2483      AddToWorkList(Op.getNode());
2484      return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2485                                  DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2486    }
2487  }
2488
2489  return SDValue();
2490}
2491
2492SDValue DAGCombiner::visitAND(SDNode *N) {
2493  SDValue N0 = N->getOperand(0);
2494  SDValue N1 = N->getOperand(1);
2495  SDValue LL, LR, RL, RR, CC0, CC1;
2496  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2497  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2498  EVT VT = N1.getValueType();
2499  unsigned BitWidth = VT.getScalarType().getSizeInBits();
2500
2501  // fold vector ops
2502  if (VT.isVector()) {
2503    SDValue FoldedVOp = SimplifyVBinOp(N);
2504    if (FoldedVOp.getNode()) return FoldedVOp;
2505
2506    // fold (and x, 0) -> 0, vector edition
2507    if (ISD::isBuildVectorAllZeros(N0.getNode()))
2508      return N0;
2509    if (ISD::isBuildVectorAllZeros(N1.getNode()))
2510      return N1;
2511
2512    // fold (and x, -1) -> x, vector edition
2513    if (ISD::isBuildVectorAllOnes(N0.getNode()))
2514      return N1;
2515    if (ISD::isBuildVectorAllOnes(N1.getNode()))
2516      return N0;
2517  }
2518
2519  // fold (and x, undef) -> 0
2520  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2521    return DAG.getConstant(0, VT);
2522  // fold (and c1, c2) -> c1&c2
2523  if (N0C && N1C)
2524    return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2525  // canonicalize constant to RHS
2526  if (N0C && !N1C)
2527    return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2528  // fold (and x, -1) -> x
2529  if (N1C && N1C->isAllOnesValue())
2530    return N0;
2531  // if (and x, c) is known to be zero, return 0
2532  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2533                                   APInt::getAllOnesValue(BitWidth)))
2534    return DAG.getConstant(0, VT);
2535  // reassociate and
2536  SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2537  if (RAND.getNode() != 0)
2538    return RAND;
2539  // fold (and (or x, C), D) -> D if (C & D) == D
2540  if (N1C && N0.getOpcode() == ISD::OR)
2541    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2542      if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2543        return N1;
2544  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2545  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2546    SDValue N0Op0 = N0.getOperand(0);
2547    APInt Mask = ~N1C->getAPIntValue();
2548    Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2549    if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2550      SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2551                                 N0.getValueType(), N0Op0);
2552
2553      // Replace uses of the AND with uses of the Zero extend node.
2554      CombineTo(N, Zext);
2555
2556      // We actually want to replace all uses of the any_extend with the
2557      // zero_extend, to avoid duplicating things.  This will later cause this
2558      // AND to be folded.
2559      CombineTo(N0.getNode(), Zext);
2560      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2561    }
2562  }
2563  // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2564  // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2565  // already be zero by virtue of the width of the base type of the load.
2566  //
2567  // the 'X' node here can either be nothing or an extract_vector_elt to catch
2568  // more cases.
2569  if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2570       N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2571      N0.getOpcode() == ISD::LOAD) {
2572    LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2573                                         N0 : N0.getOperand(0) );
2574
2575    // Get the constant (if applicable) the zero'th operand is being ANDed with.
2576    // This can be a pure constant or a vector splat, in which case we treat the
2577    // vector as a scalar and use the splat value.
2578    APInt Constant = APInt::getNullValue(1);
2579    if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2580      Constant = C->getAPIntValue();
2581    } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2582      APInt SplatValue, SplatUndef;
2583      unsigned SplatBitSize;
2584      bool HasAnyUndefs;
2585      bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2586                                             SplatBitSize, HasAnyUndefs);
2587      if (IsSplat) {
2588        // Undef bits can contribute to a possible optimisation if set, so
2589        // set them.
2590        SplatValue |= SplatUndef;
2591
2592        // The splat value may be something like "0x00FFFFFF", which means 0 for
2593        // the first vector value and FF for the rest, repeating. We need a mask
2594        // that will apply equally to all members of the vector, so AND all the
2595        // lanes of the constant together.
2596        EVT VT = Vector->getValueType(0);
2597        unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2598
2599        // If the splat value has been compressed to a bitlength lower
2600        // than the size of the vector lane, we need to re-expand it to
2601        // the lane size.
2602        if (BitWidth > SplatBitSize)
2603          for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2604               SplatBitSize < BitWidth;
2605               SplatBitSize = SplatBitSize * 2)
2606            SplatValue |= SplatValue.shl(SplatBitSize);
2607
2608        Constant = APInt::getAllOnesValue(BitWidth);
2609        for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2610          Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2611      }
2612    }
2613
2614    // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2615    // actually legal and isn't going to get expanded, else this is a false
2616    // optimisation.
2617    bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2618                                                    Load->getMemoryVT());
2619
2620    // Resize the constant to the same size as the original memory access before
2621    // extension. If it is still the AllOnesValue then this AND is completely
2622    // unneeded.
2623    Constant =
2624      Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2625
2626    bool B;
2627    switch (Load->getExtensionType()) {
2628    default: B = false; break;
2629    case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2630    case ISD::ZEXTLOAD:
2631    case ISD::NON_EXTLOAD: B = true; break;
2632    }
2633
2634    if (B && Constant.isAllOnesValue()) {
2635      // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2636      // preserve semantics once we get rid of the AND.
2637      SDValue NewLoad(Load, 0);
2638      if (Load->getExtensionType() == ISD::EXTLOAD) {
2639        NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2640                              Load->getValueType(0), SDLoc(Load),
2641                              Load->getChain(), Load->getBasePtr(),
2642                              Load->getOffset(), Load->getMemoryVT(),
2643                              Load->getMemOperand());
2644        // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2645        if (Load->getNumValues() == 3) {
2646          // PRE/POST_INC loads have 3 values.
2647          SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2648                           NewLoad.getValue(2) };
2649          CombineTo(Load, To, 3, true);
2650        } else {
2651          CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2652        }
2653      }
2654
2655      // Fold the AND away, taking care not to fold to the old load node if we
2656      // replaced it.
2657      CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2658
2659      return SDValue(N, 0); // Return N so it doesn't get rechecked!
2660    }
2661  }
2662  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2663  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2664    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2665    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2666
2667    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2668        LL.getValueType().isInteger()) {
2669      // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2670      if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2671        SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2672                                     LR.getValueType(), LL, RL);
2673        AddToWorkList(ORNode.getNode());
2674        return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2675      }
2676      // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2677      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2678        SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2679                                      LR.getValueType(), LL, RL);
2680        AddToWorkList(ANDNode.getNode());
2681        return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2682      }
2683      // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2684      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2685        SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2686                                     LR.getValueType(), LL, RL);
2687        AddToWorkList(ORNode.getNode());
2688        return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2689      }
2690    }
2691    // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2692    if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2693        Op0 == Op1 && LL.getValueType().isInteger() &&
2694      Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2695                                 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2696                                (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2697                                 cast<ConstantSDNode>(RR)->isNullValue()))) {
2698      SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2699                                    LL, DAG.getConstant(1, LL.getValueType()));
2700      AddToWorkList(ADDNode.getNode());
2701      return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2702                          DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2703    }
2704    // canonicalize equivalent to ll == rl
2705    if (LL == RR && LR == RL) {
2706      Op1 = ISD::getSetCCSwappedOperands(Op1);
2707      std::swap(RL, RR);
2708    }
2709    if (LL == RL && LR == RR) {
2710      bool isInteger = LL.getValueType().isInteger();
2711      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2712      if (Result != ISD::SETCC_INVALID &&
2713          (!LegalOperations ||
2714           (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2715            TLI.isOperationLegal(ISD::SETCC,
2716                            getSetCCResultType(N0.getSimpleValueType())))))
2717        return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2718                            LL, LR, Result);
2719    }
2720  }
2721
2722  // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2723  if (N0.getOpcode() == N1.getOpcode()) {
2724    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2725    if (Tmp.getNode()) return Tmp;
2726  }
2727
2728  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2729  // fold (and (sra)) -> (and (srl)) when possible.
2730  if (!VT.isVector() &&
2731      SimplifyDemandedBits(SDValue(N, 0)))
2732    return SDValue(N, 0);
2733
2734  // fold (zext_inreg (extload x)) -> (zextload x)
2735  if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2736    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2737    EVT MemVT = LN0->getMemoryVT();
2738    // If we zero all the possible extended bits, then we can turn this into
2739    // a zextload if we are running before legalize or the operation is legal.
2740    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2741    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2742                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2743        ((!LegalOperations && !LN0->isVolatile()) ||
2744         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2745      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2746                                       LN0->getChain(), LN0->getBasePtr(),
2747                                       MemVT, LN0->getMemOperand());
2748      AddToWorkList(N);
2749      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2750      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2751    }
2752  }
2753  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2754  if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2755      N0.hasOneUse()) {
2756    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2757    EVT MemVT = LN0->getMemoryVT();
2758    // If we zero all the possible extended bits, then we can turn this into
2759    // a zextload if we are running before legalize or the operation is legal.
2760    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2761    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2762                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2763        ((!LegalOperations && !LN0->isVolatile()) ||
2764         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2765      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2766                                       LN0->getChain(), LN0->getBasePtr(),
2767                                       MemVT, LN0->getMemOperand());
2768      AddToWorkList(N);
2769      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2770      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2771    }
2772  }
2773
2774  // fold (and (load x), 255) -> (zextload x, i8)
2775  // fold (and (extload x, i16), 255) -> (zextload x, i8)
2776  // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2777  if (N1C && (N0.getOpcode() == ISD::LOAD ||
2778              (N0.getOpcode() == ISD::ANY_EXTEND &&
2779               N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2780    bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2781    LoadSDNode *LN0 = HasAnyExt
2782      ? cast<LoadSDNode>(N0.getOperand(0))
2783      : cast<LoadSDNode>(N0);
2784    if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2785        LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2786      uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2787      if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2788        EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2789        EVT LoadedVT = LN0->getMemoryVT();
2790
2791        if (ExtVT == LoadedVT &&
2792            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2793          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2794
2795          SDValue NewLoad =
2796            DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2797                           LN0->getChain(), LN0->getBasePtr(), ExtVT,
2798                           LN0->getMemOperand());
2799          AddToWorkList(N);
2800          CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2801          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2802        }
2803
2804        // Do not change the width of a volatile load.
2805        // Do not generate loads of non-round integer types since these can
2806        // be expensive (and would be wrong if the type is not byte sized).
2807        if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2808            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2809          EVT PtrType = LN0->getOperand(1).getValueType();
2810
2811          unsigned Alignment = LN0->getAlignment();
2812          SDValue NewPtr = LN0->getBasePtr();
2813
2814          // For big endian targets, we need to add an offset to the pointer
2815          // to load the correct bytes.  For little endian systems, we merely
2816          // need to read fewer bytes from the same pointer.
2817          if (TLI.isBigEndian()) {
2818            unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2819            unsigned EVTStoreBytes = ExtVT.getStoreSize();
2820            unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2821            NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2822                                 NewPtr, DAG.getConstant(PtrOff, PtrType));
2823            Alignment = MinAlign(Alignment, PtrOff);
2824          }
2825
2826          AddToWorkList(NewPtr.getNode());
2827
2828          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2829          SDValue Load =
2830            DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2831                           LN0->getChain(), NewPtr,
2832                           LN0->getPointerInfo(),
2833                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2834                           Alignment, LN0->getTBAAInfo());
2835          AddToWorkList(N);
2836          CombineTo(LN0, Load, Load.getValue(1));
2837          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2838        }
2839      }
2840    }
2841  }
2842
2843  if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2844      VT.getSizeInBits() <= 64) {
2845    if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2846      APInt ADDC = ADDI->getAPIntValue();
2847      if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2848        // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2849        // immediate for an add, but it is legal if its top c2 bits are set,
2850        // transform the ADD so the immediate doesn't need to be materialized
2851        // in a register.
2852        if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2853          APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2854                                             SRLI->getZExtValue());
2855          if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2856            ADDC |= Mask;
2857            if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2858              SDValue NewAdd =
2859                DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2860                            N0.getOperand(0), DAG.getConstant(ADDC, VT));
2861              CombineTo(N0.getNode(), NewAdd);
2862              return SDValue(N, 0); // Return N so it doesn't get rechecked!
2863            }
2864          }
2865        }
2866      }
2867    }
2868  }
2869
2870  // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2871  if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2872    SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2873                                       N0.getOperand(1), false);
2874    if (BSwap.getNode())
2875      return BSwap;
2876  }
2877
2878  return SDValue();
2879}
2880
2881/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2882///
2883SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2884                                        bool DemandHighBits) {
2885  if (!LegalOperations)
2886    return SDValue();
2887
2888  EVT VT = N->getValueType(0);
2889  if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2890    return SDValue();
2891  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2892    return SDValue();
2893
2894  // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2895  bool LookPassAnd0 = false;
2896  bool LookPassAnd1 = false;
2897  if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2898      std::swap(N0, N1);
2899  if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2900      std::swap(N0, N1);
2901  if (N0.getOpcode() == ISD::AND) {
2902    if (!N0.getNode()->hasOneUse())
2903      return SDValue();
2904    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2905    if (!N01C || N01C->getZExtValue() != 0xFF00)
2906      return SDValue();
2907    N0 = N0.getOperand(0);
2908    LookPassAnd0 = true;
2909  }
2910
2911  if (N1.getOpcode() == ISD::AND) {
2912    if (!N1.getNode()->hasOneUse())
2913      return SDValue();
2914    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2915    if (!N11C || N11C->getZExtValue() != 0xFF)
2916      return SDValue();
2917    N1 = N1.getOperand(0);
2918    LookPassAnd1 = true;
2919  }
2920
2921  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2922    std::swap(N0, N1);
2923  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2924    return SDValue();
2925  if (!N0.getNode()->hasOneUse() ||
2926      !N1.getNode()->hasOneUse())
2927    return SDValue();
2928
2929  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2930  ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2931  if (!N01C || !N11C)
2932    return SDValue();
2933  if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2934    return SDValue();
2935
2936  // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2937  SDValue N00 = N0->getOperand(0);
2938  if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2939    if (!N00.getNode()->hasOneUse())
2940      return SDValue();
2941    ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2942    if (!N001C || N001C->getZExtValue() != 0xFF)
2943      return SDValue();
2944    N00 = N00.getOperand(0);
2945    LookPassAnd0 = true;
2946  }
2947
2948  SDValue N10 = N1->getOperand(0);
2949  if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2950    if (!N10.getNode()->hasOneUse())
2951      return SDValue();
2952    ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2953    if (!N101C || N101C->getZExtValue() != 0xFF00)
2954      return SDValue();
2955    N10 = N10.getOperand(0);
2956    LookPassAnd1 = true;
2957  }
2958
2959  if (N00 != N10)
2960    return SDValue();
2961
2962  // Make sure everything beyond the low halfword gets set to zero since the SRL
2963  // 16 will clear the top bits.
2964  unsigned OpSizeInBits = VT.getSizeInBits();
2965  if (DemandHighBits && OpSizeInBits > 16) {
2966    // If the left-shift isn't masked out then the only way this is a bswap is
2967    // if all bits beyond the low 8 are 0. In that case the entire pattern
2968    // reduces to a left shift anyway: leave it for other parts of the combiner.
2969    if (!LookPassAnd0)
2970      return SDValue();
2971
2972    // However, if the right shift isn't masked out then it might be because
2973    // it's not needed. See if we can spot that too.
2974    if (!LookPassAnd1 &&
2975        !DAG.MaskedValueIsZero(
2976            N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2977      return SDValue();
2978  }
2979
2980  SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2981  if (OpSizeInBits > 16)
2982    Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2983                      DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2984  return Res;
2985}
2986
2987/// isBSwapHWordElement - Return true if the specified node is an element
2988/// that makes up a 32-bit packed halfword byteswap. i.e.
2989/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2990static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2991  if (!N.getNode()->hasOneUse())
2992    return false;
2993
2994  unsigned Opc = N.getOpcode();
2995  if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2996    return false;
2997
2998  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2999  if (!N1C)
3000    return false;
3001
3002  unsigned Num;
3003  switch (N1C->getZExtValue()) {
3004  default:
3005    return false;
3006  case 0xFF:       Num = 0; break;
3007  case 0xFF00:     Num = 1; break;
3008  case 0xFF0000:   Num = 2; break;
3009  case 0xFF000000: Num = 3; break;
3010  }
3011
3012  // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3013  SDValue N0 = N.getOperand(0);
3014  if (Opc == ISD::AND) {
3015    if (Num == 0 || Num == 2) {
3016      // (x >> 8) & 0xff
3017      // (x >> 8) & 0xff0000
3018      if (N0.getOpcode() != ISD::SRL)
3019        return false;
3020      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3021      if (!C || C->getZExtValue() != 8)
3022        return false;
3023    } else {
3024      // (x << 8) & 0xff00
3025      // (x << 8) & 0xff000000
3026      if (N0.getOpcode() != ISD::SHL)
3027        return false;
3028      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3029      if (!C || C->getZExtValue() != 8)
3030        return false;
3031    }
3032  } else if (Opc == ISD::SHL) {
3033    // (x & 0xff) << 8
3034    // (x & 0xff0000) << 8
3035    if (Num != 0 && Num != 2)
3036      return false;
3037    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3038    if (!C || C->getZExtValue() != 8)
3039      return false;
3040  } else { // Opc == ISD::SRL
3041    // (x & 0xff00) >> 8
3042    // (x & 0xff000000) >> 8
3043    if (Num != 1 && Num != 3)
3044      return false;
3045    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3046    if (!C || C->getZExtValue() != 8)
3047      return false;
3048  }
3049
3050  if (Parts[Num])
3051    return false;
3052
3053  Parts[Num] = N0.getOperand(0).getNode();
3054  return true;
3055}
3056
3057/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3058/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3059/// => (rotl (bswap x), 16)
3060SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3061  if (!LegalOperations)
3062    return SDValue();
3063
3064  EVT VT = N->getValueType(0);
3065  if (VT != MVT::i32)
3066    return SDValue();
3067  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3068    return SDValue();
3069
3070  SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3071  // Look for either
3072  // (or (or (and), (and)), (or (and), (and)))
3073  // (or (or (or (and), (and)), (and)), (and))
3074  if (N0.getOpcode() != ISD::OR)
3075    return SDValue();
3076  SDValue N00 = N0.getOperand(0);
3077  SDValue N01 = N0.getOperand(1);
3078
3079  if (N1.getOpcode() == ISD::OR &&
3080      N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3081    // (or (or (and), (and)), (or (and), (and)))
3082    SDValue N000 = N00.getOperand(0);
3083    if (!isBSwapHWordElement(N000, Parts))
3084      return SDValue();
3085
3086    SDValue N001 = N00.getOperand(1);
3087    if (!isBSwapHWordElement(N001, Parts))
3088      return SDValue();
3089    SDValue N010 = N01.getOperand(0);
3090    if (!isBSwapHWordElement(N010, Parts))
3091      return SDValue();
3092    SDValue N011 = N01.getOperand(1);
3093    if (!isBSwapHWordElement(N011, Parts))
3094      return SDValue();
3095  } else {
3096    // (or (or (or (and), (and)), (and)), (and))
3097    if (!isBSwapHWordElement(N1, Parts))
3098      return SDValue();
3099    if (!isBSwapHWordElement(N01, Parts))
3100      return SDValue();
3101    if (N00.getOpcode() != ISD::OR)
3102      return SDValue();
3103    SDValue N000 = N00.getOperand(0);
3104    if (!isBSwapHWordElement(N000, Parts))
3105      return SDValue();
3106    SDValue N001 = N00.getOperand(1);
3107    if (!isBSwapHWordElement(N001, Parts))
3108      return SDValue();
3109  }
3110
3111  // Make sure the parts are all coming from the same node.
3112  if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3113    return SDValue();
3114
3115  SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3116                              SDValue(Parts[0],0));
3117
3118  // Result of the bswap should be rotated by 16. If it's not legal, then
3119  // do  (x << 16) | (x >> 16).
3120  SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3121  if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3122    return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3123  if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3124    return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3125  return DAG.getNode(ISD::OR, SDLoc(N), VT,
3126                     DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3127                     DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3128}
3129
3130SDValue DAGCombiner::visitOR(SDNode *N) {
3131  SDValue N0 = N->getOperand(0);
3132  SDValue N1 = N->getOperand(1);
3133  SDValue LL, LR, RL, RR, CC0, CC1;
3134  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3135  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3136  EVT VT = N1.getValueType();
3137
3138  // fold vector ops
3139  if (VT.isVector()) {
3140    SDValue FoldedVOp = SimplifyVBinOp(N);
3141    if (FoldedVOp.getNode()) return FoldedVOp;
3142
3143    // fold (or x, 0) -> x, vector edition
3144    if (ISD::isBuildVectorAllZeros(N0.getNode()))
3145      return N1;
3146    if (ISD::isBuildVectorAllZeros(N1.getNode()))
3147      return N0;
3148
3149    // fold (or x, -1) -> -1, vector edition
3150    if (ISD::isBuildVectorAllOnes(N0.getNode()))
3151      return N0;
3152    if (ISD::isBuildVectorAllOnes(N1.getNode()))
3153      return N1;
3154  }
3155
3156  // fold (or x, undef) -> -1
3157  if (!LegalOperations &&
3158      (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3159    EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3160    return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3161  }
3162  // fold (or c1, c2) -> c1|c2
3163  if (N0C && N1C)
3164    return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3165  // canonicalize constant to RHS
3166  if (N0C && !N1C)
3167    return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3168  // fold (or x, 0) -> x
3169  if (N1C && N1C->isNullValue())
3170    return N0;
3171  // fold (or x, -1) -> -1
3172  if (N1C && N1C->isAllOnesValue())
3173    return N1;
3174  // fold (or x, c) -> c iff (x & ~c) == 0
3175  if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3176    return N1;
3177
3178  // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3179  SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3180  if (BSwap.getNode() != 0)
3181    return BSwap;
3182  BSwap = MatchBSwapHWordLow(N, N0, N1);
3183  if (BSwap.getNode() != 0)
3184    return BSwap;
3185
3186  // reassociate or
3187  SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3188  if (ROR.getNode() != 0)
3189    return ROR;
3190  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3191  // iff (c1 & c2) == 0.
3192  if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3193             isa<ConstantSDNode>(N0.getOperand(1))) {
3194    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3195    if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3196      return DAG.getNode(ISD::AND, SDLoc(N), VT,
3197                         DAG.getNode(ISD::OR, SDLoc(N0), VT,
3198                                     N0.getOperand(0), N1),
3199                         DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3200  }
3201  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3202  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3203    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3204    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3205
3206    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3207        LL.getValueType().isInteger()) {
3208      // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3209      // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3210      if (cast<ConstantSDNode>(LR)->isNullValue() &&
3211          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3212        SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3213                                     LR.getValueType(), LL, RL);
3214        AddToWorkList(ORNode.getNode());
3215        return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3216      }
3217      // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3218      // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3219      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3220          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3221        SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3222                                      LR.getValueType(), LL, RL);
3223        AddToWorkList(ANDNode.getNode());
3224        return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3225      }
3226    }
3227    // canonicalize equivalent to ll == rl
3228    if (LL == RR && LR == RL) {
3229      Op1 = ISD::getSetCCSwappedOperands(Op1);
3230      std::swap(RL, RR);
3231    }
3232    if (LL == RL && LR == RR) {
3233      bool isInteger = LL.getValueType().isInteger();
3234      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3235      if (Result != ISD::SETCC_INVALID &&
3236          (!LegalOperations ||
3237           (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3238            TLI.isOperationLegal(ISD::SETCC,
3239              getSetCCResultType(N0.getValueType())))))
3240        return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3241                            LL, LR, Result);
3242    }
3243  }
3244
3245  // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3246  if (N0.getOpcode() == N1.getOpcode()) {
3247    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3248    if (Tmp.getNode()) return Tmp;
3249  }
3250
3251  // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3252  if (N0.getOpcode() == ISD::AND &&
3253      N1.getOpcode() == ISD::AND &&
3254      N0.getOperand(1).getOpcode() == ISD::Constant &&
3255      N1.getOperand(1).getOpcode() == ISD::Constant &&
3256      // Don't increase # computations.
3257      (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3258    // We can only do this xform if we know that bits from X that are set in C2
3259    // but not in C1 are already zero.  Likewise for Y.
3260    const APInt &LHSMask =
3261      cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3262    const APInt &RHSMask =
3263      cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3264
3265    if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3266        DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3267      SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3268                              N0.getOperand(0), N1.getOperand(0));
3269      return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3270                         DAG.getConstant(LHSMask | RHSMask, VT));
3271    }
3272  }
3273
3274  // See if this is some rotate idiom.
3275  if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3276    return SDValue(Rot, 0);
3277
3278  // Simplify the operands using demanded-bits information.
3279  if (!VT.isVector() &&
3280      SimplifyDemandedBits(SDValue(N, 0)))
3281    return SDValue(N, 0);
3282
3283  return SDValue();
3284}
3285
3286/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3287static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3288  if (Op.getOpcode() == ISD::AND) {
3289    if (isa<ConstantSDNode>(Op.getOperand(1))) {
3290      Mask = Op.getOperand(1);
3291      Op = Op.getOperand(0);
3292    } else {
3293      return false;
3294    }
3295  }
3296
3297  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3298    Shift = Op;
3299    return true;
3300  }
3301
3302  return false;
3303}
3304
3305// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3306// idioms for rotate, and if the target supports rotation instructions, generate
3307// a rot[lr].
3308SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3309  // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3310  EVT VT = LHS.getValueType();
3311  if (!TLI.isTypeLegal(VT)) return 0;
3312
3313  // The target must have at least one rotate flavor.
3314  bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3315  bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3316  if (!HasROTL && !HasROTR) return 0;
3317
3318  // Match "(X shl/srl V1) & V2" where V2 may not be present.
3319  SDValue LHSShift;   // The shift.
3320  SDValue LHSMask;    // AND value if any.
3321  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3322    return 0; // Not part of a rotate.
3323
3324  SDValue RHSShift;   // The shift.
3325  SDValue RHSMask;    // AND value if any.
3326  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3327    return 0; // Not part of a rotate.
3328
3329  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3330    return 0;   // Not shifting the same value.
3331
3332  if (LHSShift.getOpcode() == RHSShift.getOpcode())
3333    return 0;   // Shifts must disagree.
3334
3335  // Canonicalize shl to left side in a shl/srl pair.
3336  if (RHSShift.getOpcode() == ISD::SHL) {
3337    std::swap(LHS, RHS);
3338    std::swap(LHSShift, RHSShift);
3339    std::swap(LHSMask , RHSMask );
3340  }
3341
3342  unsigned OpSizeInBits = VT.getSizeInBits();
3343  SDValue LHSShiftArg = LHSShift.getOperand(0);
3344  SDValue LHSShiftAmt = LHSShift.getOperand(1);
3345  SDValue RHSShiftAmt = RHSShift.getOperand(1);
3346
3347  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3348  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3349  if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3350      RHSShiftAmt.getOpcode() == ISD::Constant) {
3351    uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3352    uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3353    if ((LShVal + RShVal) != OpSizeInBits)
3354      return 0;
3355
3356    SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3357                              LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3358
3359    // If there is an AND of either shifted operand, apply it to the result.
3360    if (LHSMask.getNode() || RHSMask.getNode()) {
3361      APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3362
3363      if (LHSMask.getNode()) {
3364        APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3365        Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3366      }
3367      if (RHSMask.getNode()) {
3368        APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3369        Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3370      }
3371
3372      Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3373    }
3374
3375    return Rot.getNode();
3376  }
3377
3378  // If there is a mask here, and we have a variable shift, we can't be sure
3379  // that we're masking out the right stuff.
3380  if (LHSMask.getNode() || RHSMask.getNode())
3381    return 0;
3382
3383  // If the shift amount is sign/zext/any-extended just peel it off.
3384  SDValue LExtOp0 = LHSShiftAmt;
3385  SDValue RExtOp0 = RHSShiftAmt;
3386  if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3387       LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3388       LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3389       LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3390      (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3391       RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3392       RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3393       RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3394    LExtOp0 = LHSShiftAmt.getOperand(0);
3395    RExtOp0 = RHSShiftAmt.getOperand(0);
3396  }
3397
3398  if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3399    // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3400    //   (rotl x, y)
3401    // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3402    //   (rotr x, (sub 32, y))
3403    if (ConstantSDNode *SUBC =
3404            dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0)))
3405      if (SUBC->getAPIntValue() == OpSizeInBits)
3406        return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3407                           HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3408  } else if (LExtOp0.getOpcode() == ISD::SUB &&
3409             RExtOp0 == LExtOp0.getOperand(1)) {
3410    // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3411    //   (rotr x, y)
3412    // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3413    //   (rotl x, (sub 32, y))
3414    if (ConstantSDNode *SUBC =
3415            dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0)))
3416      if (SUBC->getAPIntValue() == OpSizeInBits)
3417        return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3418                           HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3419  }
3420
3421  return 0;
3422}
3423
3424SDValue DAGCombiner::visitXOR(SDNode *N) {
3425  SDValue N0 = N->getOperand(0);
3426  SDValue N1 = N->getOperand(1);
3427  SDValue LHS, RHS, CC;
3428  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3429  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3430  EVT VT = N0.getValueType();
3431
3432  // fold vector ops
3433  if (VT.isVector()) {
3434    SDValue FoldedVOp = SimplifyVBinOp(N);
3435    if (FoldedVOp.getNode()) return FoldedVOp;
3436
3437    // fold (xor x, 0) -> x, vector edition
3438    if (ISD::isBuildVectorAllZeros(N0.getNode()))
3439      return N1;
3440    if (ISD::isBuildVectorAllZeros(N1.getNode()))
3441      return N0;
3442  }
3443
3444  // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3445  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3446    return DAG.getConstant(0, VT);
3447  // fold (xor x, undef) -> undef
3448  if (N0.getOpcode() == ISD::UNDEF)
3449    return N0;
3450  if (N1.getOpcode() == ISD::UNDEF)
3451    return N1;
3452  // fold (xor c1, c2) -> c1^c2
3453  if (N0C && N1C)
3454    return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3455  // canonicalize constant to RHS
3456  if (N0C && !N1C)
3457    return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3458  // fold (xor x, 0) -> x
3459  if (N1C && N1C->isNullValue())
3460    return N0;
3461  // reassociate xor
3462  SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3463  if (RXOR.getNode() != 0)
3464    return RXOR;
3465
3466  // fold !(x cc y) -> (x !cc y)
3467  if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3468    bool isInt = LHS.getValueType().isInteger();
3469    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3470                                               isInt);
3471
3472    if (!LegalOperations ||
3473        TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3474      switch (N0.getOpcode()) {
3475      default:
3476        llvm_unreachable("Unhandled SetCC Equivalent!");
3477      case ISD::SETCC:
3478        return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3479      case ISD::SELECT_CC:
3480        return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3481                               N0.getOperand(3), NotCC);
3482      }
3483    }
3484  }
3485
3486  // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3487  if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3488      N0.getNode()->hasOneUse() &&
3489      isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3490    SDValue V = N0.getOperand(0);
3491    V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3492                    DAG.getConstant(1, V.getValueType()));
3493    AddToWorkList(V.getNode());
3494    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3495  }
3496
3497  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3498  if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3499      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3500    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3501    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3502      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3503      LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3504      RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3505      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3506      return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3507    }
3508  }
3509  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3510  if (N1C && N1C->isAllOnesValue() &&
3511      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3512    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3513    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3514      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3515      LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3516      RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3517      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3518      return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3519    }
3520  }
3521  // fold (xor (and x, y), y) -> (and (not x), y)
3522  if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3523      N0->getOperand(1) == N1) {
3524    SDValue X = N0->getOperand(0);
3525    SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3526    AddToWorkList(NotX.getNode());
3527    return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3528  }
3529  // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3530  if (N1C && N0.getOpcode() == ISD::XOR) {
3531    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3532    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3533    if (N00C)
3534      return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3535                         DAG.getConstant(N1C->getAPIntValue() ^
3536                                         N00C->getAPIntValue(), VT));
3537    if (N01C)
3538      return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3539                         DAG.getConstant(N1C->getAPIntValue() ^
3540                                         N01C->getAPIntValue(), VT));
3541  }
3542  // fold (xor x, x) -> 0
3543  if (N0 == N1)
3544    return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3545
3546  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3547  if (N0.getOpcode() == N1.getOpcode()) {
3548    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3549    if (Tmp.getNode()) return Tmp;
3550  }
3551
3552  // Simplify the expression using non-local knowledge.
3553  if (!VT.isVector() &&
3554      SimplifyDemandedBits(SDValue(N, 0)))
3555    return SDValue(N, 0);
3556
3557  return SDValue();
3558}
3559
3560/// visitShiftByConstant - Handle transforms common to the three shifts, when
3561/// the shift amount is a constant.
3562SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3563  SDNode *LHS = N->getOperand(0).getNode();
3564  if (!LHS->hasOneUse()) return SDValue();
3565
3566  // We want to pull some binops through shifts, so that we have (and (shift))
3567  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3568  // thing happens with address calculations, so it's important to canonicalize
3569  // it.
3570  bool HighBitSet = false;  // Can we transform this if the high bit is set?
3571
3572  switch (LHS->getOpcode()) {
3573  default: return SDValue();
3574  case ISD::OR:
3575  case ISD::XOR:
3576    HighBitSet = false; // We can only transform sra if the high bit is clear.
3577    break;
3578  case ISD::AND:
3579    HighBitSet = true;  // We can only transform sra if the high bit is set.
3580    break;
3581  case ISD::ADD:
3582    if (N->getOpcode() != ISD::SHL)
3583      return SDValue(); // only shl(add) not sr[al](add).
3584    HighBitSet = false; // We can only transform sra if the high bit is clear.
3585    break;
3586  }
3587
3588  // We require the RHS of the binop to be a constant as well.
3589  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3590  if (!BinOpCst) return SDValue();
3591
3592  // FIXME: disable this unless the input to the binop is a shift by a constant.
3593  // If it is not a shift, it pessimizes some common cases like:
3594  //
3595  //    void foo(int *X, int i) { X[i & 1235] = 1; }
3596  //    int bar(int *X, int i) { return X[i & 255]; }
3597  SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3598  if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3599       BinOpLHSVal->getOpcode() != ISD::SRA &&
3600       BinOpLHSVal->getOpcode() != ISD::SRL) ||
3601      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3602    return SDValue();
3603
3604  EVT VT = N->getValueType(0);
3605
3606  // If this is a signed shift right, and the high bit is modified by the
3607  // logical operation, do not perform the transformation. The highBitSet
3608  // boolean indicates the value of the high bit of the constant which would
3609  // cause it to be modified for this operation.
3610  if (N->getOpcode() == ISD::SRA) {
3611    bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3612    if (BinOpRHSSignSet != HighBitSet)
3613      return SDValue();
3614  }
3615
3616  // Fold the constants, shifting the binop RHS by the shift amount.
3617  SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3618                               N->getValueType(0),
3619                               LHS->getOperand(1), N->getOperand(1));
3620
3621  // Create the new shift.
3622  SDValue NewShift = DAG.getNode(N->getOpcode(),
3623                                 SDLoc(LHS->getOperand(0)),
3624                                 VT, LHS->getOperand(0), N->getOperand(1));
3625
3626  // Create the new binop.
3627  return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3628}
3629
3630SDValue DAGCombiner::visitSHL(SDNode *N) {
3631  SDValue N0 = N->getOperand(0);
3632  SDValue N1 = N->getOperand(1);
3633  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3634  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3635  EVT VT = N0.getValueType();
3636  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3637
3638  // fold vector ops
3639  if (VT.isVector()) {
3640    SDValue FoldedVOp = SimplifyVBinOp(N);
3641    if (FoldedVOp.getNode()) return FoldedVOp;
3642  }
3643
3644  // fold (shl c1, c2) -> c1<<c2
3645  if (N0C && N1C)
3646    return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3647  // fold (shl 0, x) -> 0
3648  if (N0C && N0C->isNullValue())
3649    return N0;
3650  // fold (shl x, c >= size(x)) -> undef
3651  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3652    return DAG.getUNDEF(VT);
3653  // fold (shl x, 0) -> x
3654  if (N1C && N1C->isNullValue())
3655    return N0;
3656  // fold (shl undef, x) -> 0
3657  if (N0.getOpcode() == ISD::UNDEF)
3658    return DAG.getConstant(0, VT);
3659  // if (shl x, c) is known to be zero, return 0
3660  if (DAG.MaskedValueIsZero(SDValue(N, 0),
3661                            APInt::getAllOnesValue(OpSizeInBits)))
3662    return DAG.getConstant(0, VT);
3663  // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3664  if (N1.getOpcode() == ISD::TRUNCATE &&
3665      N1.getOperand(0).getOpcode() == ISD::AND &&
3666      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3667    SDValue N101 = N1.getOperand(0).getOperand(1);
3668    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3669      EVT TruncVT = N1.getValueType();
3670      SDValue N100 = N1.getOperand(0).getOperand(0);
3671      APInt TruncC = N101C->getAPIntValue();
3672      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3673      return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3674                         DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3675                                     DAG.getNode(ISD::TRUNCATE,
3676                                                 SDLoc(N),
3677                                                 TruncVT, N100),
3678                                     DAG.getConstant(TruncC, TruncVT)));
3679    }
3680  }
3681
3682  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3683    return SDValue(N, 0);
3684
3685  // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3686  if (N1C && N0.getOpcode() == ISD::SHL &&
3687      N0.getOperand(1).getOpcode() == ISD::Constant) {
3688    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3689    uint64_t c2 = N1C->getZExtValue();
3690    if (c1 + c2 >= OpSizeInBits)
3691      return DAG.getConstant(0, VT);
3692    return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3693                       DAG.getConstant(c1 + c2, N1.getValueType()));
3694  }
3695
3696  // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3697  // For this to be valid, the second form must not preserve any of the bits
3698  // that are shifted out by the inner shift in the first form.  This means
3699  // the outer shift size must be >= the number of bits added by the ext.
3700  // As a corollary, we don't care what kind of ext it is.
3701  if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3702              N0.getOpcode() == ISD::ANY_EXTEND ||
3703              N0.getOpcode() == ISD::SIGN_EXTEND) &&
3704      N0.getOperand(0).getOpcode() == ISD::SHL &&
3705      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3706    uint64_t c1 =
3707      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3708    uint64_t c2 = N1C->getZExtValue();
3709    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3710    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3711    if (c2 >= OpSizeInBits - InnerShiftSize) {
3712      if (c1 + c2 >= OpSizeInBits)
3713        return DAG.getConstant(0, VT);
3714      return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3715                         DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3716                                     N0.getOperand(0)->getOperand(0)),
3717                         DAG.getConstant(c1 + c2, N1.getValueType()));
3718    }
3719  }
3720
3721  // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3722  // Only fold this if the inner zext has no other uses to avoid increasing
3723  // the total number of instructions.
3724  if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3725      N0.getOperand(0).getOpcode() == ISD::SRL &&
3726      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3727    uint64_t c1 =
3728      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3729    if (c1 < VT.getSizeInBits()) {
3730      uint64_t c2 = N1C->getZExtValue();
3731      if (c1 == c2) {
3732        SDValue NewOp0 = N0.getOperand(0);
3733        EVT CountVT = NewOp0.getOperand(1).getValueType();
3734        SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3735                                     NewOp0, DAG.getConstant(c2, CountVT));
3736        AddToWorkList(NewSHL.getNode());
3737        return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3738      }
3739    }
3740  }
3741
3742  // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3743  //                               (and (srl x, (sub c1, c2), MASK)
3744  // Only fold this if the inner shift has no other uses -- if it does, folding
3745  // this will increase the total number of instructions.
3746  if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3747      N0.getOperand(1).getOpcode() == ISD::Constant) {
3748    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3749    if (c1 < VT.getSizeInBits()) {
3750      uint64_t c2 = N1C->getZExtValue();
3751      APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3752                                         VT.getSizeInBits() - c1);
3753      SDValue Shift;
3754      if (c2 > c1) {
3755        Mask = Mask.shl(c2-c1);
3756        Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3757                            DAG.getConstant(c2-c1, N1.getValueType()));
3758      } else {
3759        Mask = Mask.lshr(c1-c2);
3760        Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3761                            DAG.getConstant(c1-c2, N1.getValueType()));
3762      }
3763      return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3764                         DAG.getConstant(Mask, VT));
3765    }
3766  }
3767  // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3768  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3769    SDValue HiBitsMask =
3770      DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3771                                            VT.getSizeInBits() -
3772                                              N1C->getZExtValue()),
3773                      VT);
3774    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3775                       HiBitsMask);
3776  }
3777
3778  if (N1C) {
3779    SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3780    if (NewSHL.getNode())
3781      return NewSHL;
3782  }
3783
3784  return SDValue();
3785}
3786
3787SDValue DAGCombiner::visitSRA(SDNode *N) {
3788  SDValue N0 = N->getOperand(0);
3789  SDValue N1 = N->getOperand(1);
3790  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3791  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3792  EVT VT = N0.getValueType();
3793  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3794
3795  // fold vector ops
3796  if (VT.isVector()) {
3797    SDValue FoldedVOp = SimplifyVBinOp(N);
3798    if (FoldedVOp.getNode()) return FoldedVOp;
3799  }
3800
3801  // fold (sra c1, c2) -> (sra c1, c2)
3802  if (N0C && N1C)
3803    return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3804  // fold (sra 0, x) -> 0
3805  if (N0C && N0C->isNullValue())
3806    return N0;
3807  // fold (sra -1, x) -> -1
3808  if (N0C && N0C->isAllOnesValue())
3809    return N0;
3810  // fold (sra x, (setge c, size(x))) -> undef
3811  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3812    return DAG.getUNDEF(VT);
3813  // fold (sra x, 0) -> x
3814  if (N1C && N1C->isNullValue())
3815    return N0;
3816  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3817  // sext_inreg.
3818  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3819    unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3820    EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3821    if (VT.isVector())
3822      ExtVT = EVT::getVectorVT(*DAG.getContext(),
3823                               ExtVT, VT.getVectorNumElements());
3824    if ((!LegalOperations ||
3825         TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3826      return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3827                         N0.getOperand(0), DAG.getValueType(ExtVT));
3828  }
3829
3830  // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3831  if (N1C && N0.getOpcode() == ISD::SRA) {
3832    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3833      unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3834      if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3835      return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3836                         DAG.getConstant(Sum, N1C->getValueType(0)));
3837    }
3838  }
3839
3840  // fold (sra (shl X, m), (sub result_size, n))
3841  // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3842  // result_size - n != m.
3843  // If truncate is free for the target sext(shl) is likely to result in better
3844  // code.
3845  if (N0.getOpcode() == ISD::SHL) {
3846    // Get the two constanst of the shifts, CN0 = m, CN = n.
3847    const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3848    if (N01C && N1C) {
3849      // Determine what the truncate's result bitsize and type would be.
3850      EVT TruncVT =
3851        EVT::getIntegerVT(*DAG.getContext(),
3852                          OpSizeInBits - N1C->getZExtValue());
3853      // Determine the residual right-shift amount.
3854      signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3855
3856      // If the shift is not a no-op (in which case this should be just a sign
3857      // extend already), the truncated to type is legal, sign_extend is legal
3858      // on that type, and the truncate to that type is both legal and free,
3859      // perform the transform.
3860      if ((ShiftAmt > 0) &&
3861          TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3862          TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3863          TLI.isTruncateFree(VT, TruncVT)) {
3864
3865          SDValue Amt = DAG.getConstant(ShiftAmt,
3866              getShiftAmountTy(N0.getOperand(0).getValueType()));
3867          SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3868                                      N0.getOperand(0), Amt);
3869          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3870                                      Shift);
3871          return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3872                             N->getValueType(0), Trunc);
3873      }
3874    }
3875  }
3876
3877  // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3878  if (N1.getOpcode() == ISD::TRUNCATE &&
3879      N1.getOperand(0).getOpcode() == ISD::AND &&
3880      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3881    SDValue N101 = N1.getOperand(0).getOperand(1);
3882    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3883      EVT TruncVT = N1.getValueType();
3884      SDValue N100 = N1.getOperand(0).getOperand(0);
3885      APInt TruncC = N101C->getAPIntValue();
3886      TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3887      return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3888                         DAG.getNode(ISD::AND, SDLoc(N),
3889                                     TruncVT,
3890                                     DAG.getNode(ISD::TRUNCATE,
3891                                                 SDLoc(N),
3892                                                 TruncVT, N100),
3893                                     DAG.getConstant(TruncC, TruncVT)));
3894    }
3895  }
3896
3897  // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3898  //      if c1 is equal to the number of bits the trunc removes
3899  if (N0.getOpcode() == ISD::TRUNCATE &&
3900      (N0.getOperand(0).getOpcode() == ISD::SRL ||
3901       N0.getOperand(0).getOpcode() == ISD::SRA) &&
3902      N0.getOperand(0).hasOneUse() &&
3903      N0.getOperand(0).getOperand(1).hasOneUse() &&
3904      N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3905    EVT LargeVT = N0.getOperand(0).getValueType();
3906    ConstantSDNode *LargeShiftAmt =
3907      cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3908
3909    if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3910        LargeShiftAmt->getZExtValue()) {
3911      SDValue Amt =
3912        DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3913              getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3914      SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3915                                N0.getOperand(0).getOperand(0), Amt);
3916      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3917    }
3918  }
3919
3920  // Simplify, based on bits shifted out of the LHS.
3921  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3922    return SDValue(N, 0);
3923
3924
3925  // If the sign bit is known to be zero, switch this to a SRL.
3926  if (DAG.SignBitIsZero(N0))
3927    return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3928
3929  if (N1C) {
3930    SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3931    if (NewSRA.getNode())
3932      return NewSRA;
3933  }
3934
3935  return SDValue();
3936}
3937
3938SDValue DAGCombiner::visitSRL(SDNode *N) {
3939  SDValue N0 = N->getOperand(0);
3940  SDValue N1 = N->getOperand(1);
3941  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3942  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3943  EVT VT = N0.getValueType();
3944  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3945
3946  // fold vector ops
3947  if (VT.isVector()) {
3948    SDValue FoldedVOp = SimplifyVBinOp(N);
3949    if (FoldedVOp.getNode()) return FoldedVOp;
3950  }
3951
3952  // fold (srl c1, c2) -> c1 >>u c2
3953  if (N0C && N1C)
3954    return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3955  // fold (srl 0, x) -> 0
3956  if (N0C && N0C->isNullValue())
3957    return N0;
3958  // fold (srl x, c >= size(x)) -> undef
3959  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3960    return DAG.getUNDEF(VT);
3961  // fold (srl x, 0) -> x
3962  if (N1C && N1C->isNullValue())
3963    return N0;
3964  // if (srl x, c) is known to be zero, return 0
3965  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3966                                   APInt::getAllOnesValue(OpSizeInBits)))
3967    return DAG.getConstant(0, VT);
3968
3969  // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3970  if (N1C && N0.getOpcode() == ISD::SRL &&
3971      N0.getOperand(1).getOpcode() == ISD::Constant) {
3972    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3973    uint64_t c2 = N1C->getZExtValue();
3974    if (c1 + c2 >= OpSizeInBits)
3975      return DAG.getConstant(0, VT);
3976    return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3977                       DAG.getConstant(c1 + c2, N1.getValueType()));
3978  }
3979
3980  // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3981  if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3982      N0.getOperand(0).getOpcode() == ISD::SRL &&
3983      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3984    uint64_t c1 =
3985      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3986    uint64_t c2 = N1C->getZExtValue();
3987    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3988    EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3989    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3990    // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3991    if (c1 + OpSizeInBits == InnerShiftSize) {
3992      if (c1 + c2 >= InnerShiftSize)
3993        return DAG.getConstant(0, VT);
3994      return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3995                         DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3996                                     N0.getOperand(0)->getOperand(0),
3997                                     DAG.getConstant(c1 + c2, ShiftCountVT)));
3998    }
3999  }
4000
4001  // fold (srl (shl x, c), c) -> (and x, cst2)
4002  if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4003      N0.getValueSizeInBits() <= 64) {
4004    uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4005    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4006                       DAG.getConstant(~0ULL >> ShAmt, VT));
4007  }
4008
4009  // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4010  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4011    // Shifting in all undef bits?
4012    EVT SmallVT = N0.getOperand(0).getValueType();
4013    if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4014      return DAG.getUNDEF(VT);
4015
4016    if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4017      uint64_t ShiftAmt = N1C->getZExtValue();
4018      SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4019                                       N0.getOperand(0),
4020                          DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4021      AddToWorkList(SmallShift.getNode());
4022      APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4023      return DAG.getNode(ISD::AND, SDLoc(N), VT,
4024                         DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4025                         DAG.getConstant(Mask, VT));
4026    }
4027  }
4028
4029  // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4030  // bit, which is unmodified by sra.
4031  if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4032    if (N0.getOpcode() == ISD::SRA)
4033      return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4034  }
4035
4036  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4037  if (N1C && N0.getOpcode() == ISD::CTLZ &&
4038      N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4039    APInt KnownZero, KnownOne;
4040    DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4041
4042    // If any of the input bits are KnownOne, then the input couldn't be all
4043    // zeros, thus the result of the srl will always be zero.
4044    if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4045
4046    // If all of the bits input the to ctlz node are known to be zero, then
4047    // the result of the ctlz is "32" and the result of the shift is one.
4048    APInt UnknownBits = ~KnownZero;
4049    if (UnknownBits == 0) return DAG.getConstant(1, VT);
4050
4051    // Otherwise, check to see if there is exactly one bit input to the ctlz.
4052    if ((UnknownBits & (UnknownBits - 1)) == 0) {
4053      // Okay, we know that only that the single bit specified by UnknownBits
4054      // could be set on input to the CTLZ node. If this bit is set, the SRL
4055      // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4056      // to an SRL/XOR pair, which is likely to simplify more.
4057      unsigned ShAmt = UnknownBits.countTrailingZeros();
4058      SDValue Op = N0.getOperand(0);
4059
4060      if (ShAmt) {
4061        Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4062                  DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4063        AddToWorkList(Op.getNode());
4064      }
4065
4066      return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4067                         Op, DAG.getConstant(1, VT));
4068    }
4069  }
4070
4071  // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4072  if (N1.getOpcode() == ISD::TRUNCATE &&
4073      N1.getOperand(0).getOpcode() == ISD::AND &&
4074      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4075    SDValue N101 = N1.getOperand(0).getOperand(1);
4076    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4077      EVT TruncVT = N1.getValueType();
4078      SDValue N100 = N1.getOperand(0).getOperand(0);
4079      APInt TruncC = N101C->getAPIntValue();
4080      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4081      return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4082                         DAG.getNode(ISD::AND, SDLoc(N),
4083                                     TruncVT,
4084                                     DAG.getNode(ISD::TRUNCATE,
4085                                                 SDLoc(N),
4086                                                 TruncVT, N100),
4087                                     DAG.getConstant(TruncC, TruncVT)));
4088    }
4089  }
4090
4091  // fold operands of srl based on knowledge that the low bits are not
4092  // demanded.
4093  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4094    return SDValue(N, 0);
4095
4096  if (N1C) {
4097    SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4098    if (NewSRL.getNode())
4099      return NewSRL;
4100  }
4101
4102  // Attempt to convert a srl of a load into a narrower zero-extending load.
4103  SDValue NarrowLoad = ReduceLoadWidth(N);
4104  if (NarrowLoad.getNode())
4105    return NarrowLoad;
4106
4107  // Here is a common situation. We want to optimize:
4108  //
4109  //   %a = ...
4110  //   %b = and i32 %a, 2
4111  //   %c = srl i32 %b, 1
4112  //   brcond i32 %c ...
4113  //
4114  // into
4115  //
4116  //   %a = ...
4117  //   %b = and %a, 2
4118  //   %c = setcc eq %b, 0
4119  //   brcond %c ...
4120  //
4121  // However when after the source operand of SRL is optimized into AND, the SRL
4122  // itself may not be optimized further. Look for it and add the BRCOND into
4123  // the worklist.
4124  if (N->hasOneUse()) {
4125    SDNode *Use = *N->use_begin();
4126    if (Use->getOpcode() == ISD::BRCOND)
4127      AddToWorkList(Use);
4128    else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4129      // Also look pass the truncate.
4130      Use = *Use->use_begin();
4131      if (Use->getOpcode() == ISD::BRCOND)
4132        AddToWorkList(Use);
4133    }
4134  }
4135
4136  return SDValue();
4137}
4138
4139SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4140  SDValue N0 = N->getOperand(0);
4141  EVT VT = N->getValueType(0);
4142
4143  // fold (ctlz c1) -> c2
4144  if (isa<ConstantSDNode>(N0))
4145    return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4146  return SDValue();
4147}
4148
4149SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4150  SDValue N0 = N->getOperand(0);
4151  EVT VT = N->getValueType(0);
4152
4153  // fold (ctlz_zero_undef c1) -> c2
4154  if (isa<ConstantSDNode>(N0))
4155    return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4156  return SDValue();
4157}
4158
4159SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4160  SDValue N0 = N->getOperand(0);
4161  EVT VT = N->getValueType(0);
4162
4163  // fold (cttz c1) -> c2
4164  if (isa<ConstantSDNode>(N0))
4165    return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4166  return SDValue();
4167}
4168
4169SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4170  SDValue N0 = N->getOperand(0);
4171  EVT VT = N->getValueType(0);
4172
4173  // fold (cttz_zero_undef c1) -> c2
4174  if (isa<ConstantSDNode>(N0))
4175    return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4176  return SDValue();
4177}
4178
4179SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4180  SDValue N0 = N->getOperand(0);
4181  EVT VT = N->getValueType(0);
4182
4183  // fold (ctpop c1) -> c2
4184  if (isa<ConstantSDNode>(N0))
4185    return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4186  return SDValue();
4187}
4188
4189SDValue DAGCombiner::visitSELECT(SDNode *N) {
4190  SDValue N0 = N->getOperand(0);
4191  SDValue N1 = N->getOperand(1);
4192  SDValue N2 = N->getOperand(2);
4193  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4194  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4195  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4196  EVT VT = N->getValueType(0);
4197  EVT VT0 = N0.getValueType();
4198
4199  // fold (select C, X, X) -> X
4200  if (N1 == N2)
4201    return N1;
4202  // fold (select true, X, Y) -> X
4203  if (N0C && !N0C->isNullValue())
4204    return N1;
4205  // fold (select false, X, Y) -> Y
4206  if (N0C && N0C->isNullValue())
4207    return N2;
4208  // fold (select C, 1, X) -> (or C, X)
4209  if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4210    return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4211  // fold (select C, 0, 1) -> (xor C, 1)
4212  if (VT.isInteger() &&
4213      (VT0 == MVT::i1 ||
4214       (VT0.isInteger() &&
4215        TLI.getBooleanContents(false) ==
4216        TargetLowering::ZeroOrOneBooleanContent)) &&
4217      N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4218    SDValue XORNode;
4219    if (VT == VT0)
4220      return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4221                         N0, DAG.getConstant(1, VT0));
4222    XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4223                          N0, DAG.getConstant(1, VT0));
4224    AddToWorkList(XORNode.getNode());
4225    if (VT.bitsGT(VT0))
4226      return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4227    return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4228  }
4229  // fold (select C, 0, X) -> (and (not C), X)
4230  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4231    SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4232    AddToWorkList(NOTNode.getNode());
4233    return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4234  }
4235  // fold (select C, X, 1) -> (or (not C), X)
4236  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4237    SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4238    AddToWorkList(NOTNode.getNode());
4239    return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4240  }
4241  // fold (select C, X, 0) -> (and C, X)
4242  if (VT == MVT::i1 && N2C && N2C->isNullValue())
4243    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4244  // fold (select X, X, Y) -> (or X, Y)
4245  // fold (select X, 1, Y) -> (or X, Y)
4246  if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4247    return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4248  // fold (select X, Y, X) -> (and X, Y)
4249  // fold (select X, Y, 0) -> (and X, Y)
4250  if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4251    return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4252
4253  // If we can fold this based on the true/false value, do so.
4254  if (SimplifySelectOps(N, N1, N2))
4255    return SDValue(N, 0);  // Don't revisit N.
4256
4257  // fold selects based on a setcc into other things, such as min/max/abs
4258  if (N0.getOpcode() == ISD::SETCC) {
4259    // FIXME:
4260    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4261    // having to say they don't support SELECT_CC on every type the DAG knows
4262    // about, since there is no way to mark an opcode illegal at all value types
4263    if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4264        TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4265      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4266                         N0.getOperand(0), N0.getOperand(1),
4267                         N1, N2, N0.getOperand(2));
4268    return SimplifySelect(SDLoc(N), N0, N1, N2);
4269  }
4270
4271  return SDValue();
4272}
4273
4274static
4275std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4276  SDLoc DL(N);
4277  EVT LoVT, HiVT;
4278  llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4279
4280  // Split the inputs.
4281  SDValue Lo, Hi, LL, LH, RL, RH;
4282  llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4283  llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4284
4285  Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4286  Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4287
4288  return std::make_pair(Lo, Hi);
4289}
4290
4291SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4292  SDValue N0 = N->getOperand(0);
4293  SDValue N1 = N->getOperand(1);
4294  SDValue N2 = N->getOperand(2);
4295  SDLoc DL(N);
4296
4297  // Canonicalize integer abs.
4298  // vselect (setg[te] X,  0),  X, -X ->
4299  // vselect (setgt    X, -1),  X, -X ->
4300  // vselect (setl[te] X,  0), -X,  X ->
4301  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4302  if (N0.getOpcode() == ISD::SETCC) {
4303    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4304    ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4305    bool isAbs = false;
4306    bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4307
4308    if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4309         (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4310        N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4311      isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4312    else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4313             N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4314      isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4315
4316    if (isAbs) {
4317      EVT VT = LHS.getValueType();
4318      SDValue Shift = DAG.getNode(
4319          ISD::SRA, DL, VT, LHS,
4320          DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4321      SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4322      AddToWorkList(Shift.getNode());
4323      AddToWorkList(Add.getNode());
4324      return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4325    }
4326  }
4327
4328  // If the VSELECT result requires splitting and the mask is provided by a
4329  // SETCC, then split both nodes and its operands before legalization. This
4330  // prevents the type legalizer from unrolling SETCC into scalar comparisons
4331  // and enables future optimizations (e.g. min/max pattern matching on X86).
4332  if (N0.getOpcode() == ISD::SETCC) {
4333    EVT VT = N->getValueType(0);
4334
4335    // Check if any splitting is required.
4336    if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4337        TargetLowering::TypeSplitVector)
4338      return SDValue();
4339
4340    SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4341    llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4342    llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4343    llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4344
4345    Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4346    Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4347
4348    // Add the new VSELECT nodes to the work list in case they need to be split
4349    // again.
4350    AddToWorkList(Lo.getNode());
4351    AddToWorkList(Hi.getNode());
4352
4353    return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4354  }
4355
4356  return SDValue();
4357}
4358
4359SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4360  SDValue N0 = N->getOperand(0);
4361  SDValue N1 = N->getOperand(1);
4362  SDValue N2 = N->getOperand(2);
4363  SDValue N3 = N->getOperand(3);
4364  SDValue N4 = N->getOperand(4);
4365  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4366
4367  // fold select_cc lhs, rhs, x, x, cc -> x
4368  if (N2 == N3)
4369    return N2;
4370
4371  // Determine if the condition we're dealing with is constant
4372  SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4373                              N0, N1, CC, SDLoc(N), false);
4374  if (SCC.getNode()) {
4375    AddToWorkList(SCC.getNode());
4376
4377    if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4378      if (!SCCC->isNullValue())
4379        return N2;    // cond always true -> true val
4380      else
4381        return N3;    // cond always false -> false val
4382    }
4383
4384    // Fold to a simpler select_cc
4385    if (SCC.getOpcode() == ISD::SETCC)
4386      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4387                         SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4388                         SCC.getOperand(2));
4389  }
4390
4391  // If we can fold this based on the true/false value, do so.
4392  if (SimplifySelectOps(N, N2, N3))
4393    return SDValue(N, 0);  // Don't revisit N.
4394
4395  // fold select_cc into other things, such as min/max/abs
4396  return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4397}
4398
4399SDValue DAGCombiner::visitSETCC(SDNode *N) {
4400  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4401                       cast<CondCodeSDNode>(N->getOperand(2))->get(),
4402                       SDLoc(N));
4403}
4404
4405// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4406// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4407// transformation. Returns true if extension are possible and the above
4408// mentioned transformation is profitable.
4409static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4410                                    unsigned ExtOpc,
4411                                    SmallVectorImpl<SDNode *> &ExtendNodes,
4412                                    const TargetLowering &TLI) {
4413  bool HasCopyToRegUses = false;
4414  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4415  for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4416                            UE = N0.getNode()->use_end();
4417       UI != UE; ++UI) {
4418    SDNode *User = *UI;
4419    if (User == N)
4420      continue;
4421    if (UI.getUse().getResNo() != N0.getResNo())
4422      continue;
4423    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4424    if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4425      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4426      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4427        // Sign bits will be lost after a zext.
4428        return false;
4429      bool Add = false;
4430      for (unsigned i = 0; i != 2; ++i) {
4431        SDValue UseOp = User->getOperand(i);
4432        if (UseOp == N0)
4433          continue;
4434        if (!isa<ConstantSDNode>(UseOp))
4435          return false;
4436        Add = true;
4437      }
4438      if (Add)
4439        ExtendNodes.push_back(User);
4440      continue;
4441    }
4442    // If truncates aren't free and there are users we can't
4443    // extend, it isn't worthwhile.
4444    if (!isTruncFree)
4445      return false;
4446    // Remember if this value is live-out.
4447    if (User->getOpcode() == ISD::CopyToReg)
4448      HasCopyToRegUses = true;
4449  }
4450
4451  if (HasCopyToRegUses) {
4452    bool BothLiveOut = false;
4453    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4454         UI != UE; ++UI) {
4455      SDUse &Use = UI.getUse();
4456      if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4457        BothLiveOut = true;
4458        break;
4459      }
4460    }
4461    if (BothLiveOut)
4462      // Both unextended and extended values are live out. There had better be
4463      // a good reason for the transformation.
4464      return ExtendNodes.size();
4465  }
4466  return true;
4467}
4468
4469void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4470                                  SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4471                                  ISD::NodeType ExtType) {
4472  // Extend SetCC uses if necessary.
4473  for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4474    SDNode *SetCC = SetCCs[i];
4475    SmallVector<SDValue, 4> Ops;
4476
4477    for (unsigned j = 0; j != 2; ++j) {
4478      SDValue SOp = SetCC->getOperand(j);
4479      if (SOp == Trunc)
4480        Ops.push_back(ExtLoad);
4481      else
4482        Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4483    }
4484
4485    Ops.push_back(SetCC->getOperand(2));
4486    CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4487                                 &Ops[0], Ops.size()));
4488  }
4489}
4490
4491SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4492  SDValue N0 = N->getOperand(0);
4493  EVT VT = N->getValueType(0);
4494
4495  // fold (sext c1) -> c1
4496  if (isa<ConstantSDNode>(N0))
4497    return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4498
4499  // fold (sext (sext x)) -> (sext x)
4500  // fold (sext (aext x)) -> (sext x)
4501  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4502    return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4503                       N0.getOperand(0));
4504
4505  if (N0.getOpcode() == ISD::TRUNCATE) {
4506    // fold (sext (truncate (load x))) -> (sext (smaller load x))
4507    // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4508    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4509    if (NarrowLoad.getNode()) {
4510      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4511      if (NarrowLoad.getNode() != N0.getNode()) {
4512        CombineTo(N0.getNode(), NarrowLoad);
4513        // CombineTo deleted the truncate, if needed, but not what's under it.
4514        AddToWorkList(oye);
4515      }
4516      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4517    }
4518
4519    // See if the value being truncated is already sign extended.  If so, just
4520    // eliminate the trunc/sext pair.
4521    SDValue Op = N0.getOperand(0);
4522    unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4523    unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4524    unsigned DestBits = VT.getScalarType().getSizeInBits();
4525    unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4526
4527    if (OpBits == DestBits) {
4528      // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4529      // bits, it is already ready.
4530      if (NumSignBits > DestBits-MidBits)
4531        return Op;
4532    } else if (OpBits < DestBits) {
4533      // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4534      // bits, just sext from i32.
4535      if (NumSignBits > OpBits-MidBits)
4536        return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4537    } else {
4538      // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4539      // bits, just truncate to i32.
4540      if (NumSignBits > OpBits-MidBits)
4541        return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4542    }
4543
4544    // fold (sext (truncate x)) -> (sextinreg x).
4545    if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4546                                                 N0.getValueType())) {
4547      if (OpBits < DestBits)
4548        Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4549      else if (OpBits > DestBits)
4550        Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4551      return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4552                         DAG.getValueType(N0.getValueType()));
4553    }
4554  }
4555
4556  // fold (sext (load x)) -> (sext (truncate (sextload x)))
4557  // None of the supported targets knows how to perform load and sign extend
4558  // on vectors in one instruction.  We only perform this transformation on
4559  // scalars.
4560  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4561      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4562       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4563    bool DoXform = true;
4564    SmallVector<SDNode*, 4> SetCCs;
4565    if (!N0.hasOneUse())
4566      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4567    if (DoXform) {
4568      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4569      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4570                                       LN0->getChain(),
4571                                       LN0->getBasePtr(), N0.getValueType(),
4572                                       LN0->getMemOperand());
4573      CombineTo(N, ExtLoad);
4574      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4575                                  N0.getValueType(), ExtLoad);
4576      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4577      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4578                      ISD::SIGN_EXTEND);
4579      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4580    }
4581  }
4582
4583  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4584  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4585  if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4586      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4587    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4588    EVT MemVT = LN0->getMemoryVT();
4589    if ((!LegalOperations && !LN0->isVolatile()) ||
4590        TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4591      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4592                                       LN0->getChain(),
4593                                       LN0->getBasePtr(), MemVT,
4594                                       LN0->getMemOperand());
4595      CombineTo(N, ExtLoad);
4596      CombineTo(N0.getNode(),
4597                DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4598                            N0.getValueType(), ExtLoad),
4599                ExtLoad.getValue(1));
4600      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4601    }
4602  }
4603
4604  // fold (sext (and/or/xor (load x), cst)) ->
4605  //      (and/or/xor (sextload x), (sext cst))
4606  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4607       N0.getOpcode() == ISD::XOR) &&
4608      isa<LoadSDNode>(N0.getOperand(0)) &&
4609      N0.getOperand(1).getOpcode() == ISD::Constant &&
4610      TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4611      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4612    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4613    if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4614      bool DoXform = true;
4615      SmallVector<SDNode*, 4> SetCCs;
4616      if (!N0.hasOneUse())
4617        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4618                                          SetCCs, TLI);
4619      if (DoXform) {
4620        SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4621                                         LN0->getChain(), LN0->getBasePtr(),
4622                                         LN0->getMemoryVT(),
4623                                         LN0->getMemOperand());
4624        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4625        Mask = Mask.sext(VT.getSizeInBits());
4626        SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4627                                  ExtLoad, DAG.getConstant(Mask, VT));
4628        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4629                                    SDLoc(N0.getOperand(0)),
4630                                    N0.getOperand(0).getValueType(), ExtLoad);
4631        CombineTo(N, And);
4632        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4633        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4634                        ISD::SIGN_EXTEND);
4635        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4636      }
4637    }
4638  }
4639
4640  if (N0.getOpcode() == ISD::SETCC) {
4641    // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4642    // Only do this before legalize for now.
4643    if (VT.isVector() && !LegalOperations &&
4644        TLI.getBooleanContents(true) ==
4645          TargetLowering::ZeroOrNegativeOneBooleanContent) {
4646      EVT N0VT = N0.getOperand(0).getValueType();
4647      // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4648      // of the same size as the compared operands. Only optimize sext(setcc())
4649      // if this is the case.
4650      EVT SVT = getSetCCResultType(N0VT);
4651
4652      // We know that the # elements of the results is the same as the
4653      // # elements of the compare (and the # elements of the compare result
4654      // for that matter).  Check to see that they are the same size.  If so,
4655      // we know that the element size of the sext'd result matches the
4656      // element size of the compare operands.
4657      if (VT.getSizeInBits() == SVT.getSizeInBits())
4658        return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4659                             N0.getOperand(1),
4660                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
4661
4662      // If the desired elements are smaller or larger than the source
4663      // elements we can use a matching integer vector type and then
4664      // truncate/sign extend
4665      EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4666      if (SVT == MatchingVectorType) {
4667        SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4668                               N0.getOperand(0), N0.getOperand(1),
4669                               cast<CondCodeSDNode>(N0.getOperand(2))->get());
4670        return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4671      }
4672    }
4673
4674    // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4675    unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4676    SDValue NegOne =
4677      DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4678    SDValue SCC =
4679      SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4680                       NegOne, DAG.getConstant(0, VT),
4681                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4682    if (SCC.getNode()) return SCC;
4683    if (!VT.isVector() &&
4684        (!LegalOperations ||
4685         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4686      return DAG.getSelect(SDLoc(N), VT,
4687                           DAG.getSetCC(SDLoc(N),
4688                           getSetCCResultType(VT),
4689                           N0.getOperand(0), N0.getOperand(1),
4690                           cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4691                           NegOne, DAG.getConstant(0, VT));
4692    }
4693  }
4694
4695  // fold (sext x) -> (zext x) if the sign bit is known zero.
4696  if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4697      DAG.SignBitIsZero(N0))
4698    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4699
4700  return SDValue();
4701}
4702
4703// isTruncateOf - If N is a truncate of some other value, return true, record
4704// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4705// This function computes KnownZero to avoid a duplicated call to
4706// ComputeMaskedBits in the caller.
4707static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4708                         APInt &KnownZero) {
4709  APInt KnownOne;
4710  if (N->getOpcode() == ISD::TRUNCATE) {
4711    Op = N->getOperand(0);
4712    DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4713    return true;
4714  }
4715
4716  if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4717      cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4718    return false;
4719
4720  SDValue Op0 = N->getOperand(0);
4721  SDValue Op1 = N->getOperand(1);
4722  assert(Op0.getValueType() == Op1.getValueType());
4723
4724  ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4725  ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4726  if (COp0 && COp0->isNullValue())
4727    Op = Op1;
4728  else if (COp1 && COp1->isNullValue())
4729    Op = Op0;
4730  else
4731    return false;
4732
4733  DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4734
4735  if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4736    return false;
4737
4738  return true;
4739}
4740
4741SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4742  SDValue N0 = N->getOperand(0);
4743  EVT VT = N->getValueType(0);
4744
4745  // fold (zext c1) -> c1
4746  if (isa<ConstantSDNode>(N0))
4747    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4748  // fold (zext (zext x)) -> (zext x)
4749  // fold (zext (aext x)) -> (zext x)
4750  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4751    return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4752                       N0.getOperand(0));
4753
4754  // fold (zext (truncate x)) -> (zext x) or
4755  //      (zext (truncate x)) -> (truncate x)
4756  // This is valid when the truncated bits of x are already zero.
4757  // FIXME: We should extend this to work for vectors too.
4758  SDValue Op;
4759  APInt KnownZero;
4760  if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4761    APInt TruncatedBits =
4762      (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4763      APInt(Op.getValueSizeInBits(), 0) :
4764      APInt::getBitsSet(Op.getValueSizeInBits(),
4765                        N0.getValueSizeInBits(),
4766                        std::min(Op.getValueSizeInBits(),
4767                                 VT.getSizeInBits()));
4768    if (TruncatedBits == (KnownZero & TruncatedBits)) {
4769      if (VT.bitsGT(Op.getValueType()))
4770        return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4771      if (VT.bitsLT(Op.getValueType()))
4772        return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4773
4774      return Op;
4775    }
4776  }
4777
4778  // fold (zext (truncate (load x))) -> (zext (smaller load x))
4779  // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4780  if (N0.getOpcode() == ISD::TRUNCATE) {
4781    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4782    if (NarrowLoad.getNode()) {
4783      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4784      if (NarrowLoad.getNode() != N0.getNode()) {
4785        CombineTo(N0.getNode(), NarrowLoad);
4786        // CombineTo deleted the truncate, if needed, but not what's under it.
4787        AddToWorkList(oye);
4788      }
4789      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4790    }
4791  }
4792
4793  // fold (zext (truncate x)) -> (and x, mask)
4794  if (N0.getOpcode() == ISD::TRUNCATE &&
4795      (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4796
4797    // fold (zext (truncate (load x))) -> (zext (smaller load x))
4798    // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4799    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4800    if (NarrowLoad.getNode()) {
4801      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4802      if (NarrowLoad.getNode() != N0.getNode()) {
4803        CombineTo(N0.getNode(), NarrowLoad);
4804        // CombineTo deleted the truncate, if needed, but not what's under it.
4805        AddToWorkList(oye);
4806      }
4807      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4808    }
4809
4810    SDValue Op = N0.getOperand(0);
4811    if (Op.getValueType().bitsLT(VT)) {
4812      Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4813      AddToWorkList(Op.getNode());
4814    } else if (Op.getValueType().bitsGT(VT)) {
4815      Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4816      AddToWorkList(Op.getNode());
4817    }
4818    return DAG.getZeroExtendInReg(Op, SDLoc(N),
4819                                  N0.getValueType().getScalarType());
4820  }
4821
4822  // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4823  // if either of the casts is not free.
4824  if (N0.getOpcode() == ISD::AND &&
4825      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4826      N0.getOperand(1).getOpcode() == ISD::Constant &&
4827      (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4828                           N0.getValueType()) ||
4829       !TLI.isZExtFree(N0.getValueType(), VT))) {
4830    SDValue X = N0.getOperand(0).getOperand(0);
4831    if (X.getValueType().bitsLT(VT)) {
4832      X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4833    } else if (X.getValueType().bitsGT(VT)) {
4834      X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4835    }
4836    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4837    Mask = Mask.zext(VT.getSizeInBits());
4838    return DAG.getNode(ISD::AND, SDLoc(N), VT,
4839                       X, DAG.getConstant(Mask, VT));
4840  }
4841
4842  // fold (zext (load x)) -> (zext (truncate (zextload x)))
4843  // None of the supported targets knows how to perform load and vector_zext
4844  // on vectors in one instruction.  We only perform this transformation on
4845  // scalars.
4846  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4847      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4848       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4849    bool DoXform = true;
4850    SmallVector<SDNode*, 4> SetCCs;
4851    if (!N0.hasOneUse())
4852      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4853    if (DoXform) {
4854      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4855      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4856                                       LN0->getChain(),
4857                                       LN0->getBasePtr(), N0.getValueType(),
4858                                       LN0->getMemOperand());
4859      CombineTo(N, ExtLoad);
4860      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4861                                  N0.getValueType(), ExtLoad);
4862      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4863
4864      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4865                      ISD::ZERO_EXTEND);
4866      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4867    }
4868  }
4869
4870  // fold (zext (and/or/xor (load x), cst)) ->
4871  //      (and/or/xor (zextload x), (zext cst))
4872  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4873       N0.getOpcode() == ISD::XOR) &&
4874      isa<LoadSDNode>(N0.getOperand(0)) &&
4875      N0.getOperand(1).getOpcode() == ISD::Constant &&
4876      TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4877      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4878    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4879    if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4880      bool DoXform = true;
4881      SmallVector<SDNode*, 4> SetCCs;
4882      if (!N0.hasOneUse())
4883        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4884                                          SetCCs, TLI);
4885      if (DoXform) {
4886        SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4887                                         LN0->getChain(), LN0->getBasePtr(),
4888                                         LN0->getMemoryVT(),
4889                                         LN0->getMemOperand());
4890        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4891        Mask = Mask.zext(VT.getSizeInBits());
4892        SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4893                                  ExtLoad, DAG.getConstant(Mask, VT));
4894        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4895                                    SDLoc(N0.getOperand(0)),
4896                                    N0.getOperand(0).getValueType(), ExtLoad);
4897        CombineTo(N, And);
4898        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4899        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4900                        ISD::ZERO_EXTEND);
4901        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4902      }
4903    }
4904  }
4905
4906  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4907  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4908  if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4909      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4910    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4911    EVT MemVT = LN0->getMemoryVT();
4912    if ((!LegalOperations && !LN0->isVolatile()) ||
4913        TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4914      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4915                                       LN0->getChain(),
4916                                       LN0->getBasePtr(), MemVT,
4917                                       LN0->getMemOperand());
4918      CombineTo(N, ExtLoad);
4919      CombineTo(N0.getNode(),
4920                DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4921                            ExtLoad),
4922                ExtLoad.getValue(1));
4923      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4924    }
4925  }
4926
4927  if (N0.getOpcode() == ISD::SETCC) {
4928    if (!LegalOperations && VT.isVector()) {
4929      // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4930      // Only do this before legalize for now.
4931      EVT N0VT = N0.getOperand(0).getValueType();
4932      EVT EltVT = VT.getVectorElementType();
4933      SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4934                                    DAG.getConstant(1, EltVT));
4935      if (VT.getSizeInBits() == N0VT.getSizeInBits())
4936        // We know that the # elements of the results is the same as the
4937        // # elements of the compare (and the # elements of the compare result
4938        // for that matter).  Check to see that they are the same size.  If so,
4939        // we know that the element size of the sext'd result matches the
4940        // element size of the compare operands.
4941        return DAG.getNode(ISD::AND, SDLoc(N), VT,
4942                           DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4943                                         N0.getOperand(1),
4944                                 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4945                           DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4946                                       &OneOps[0], OneOps.size()));
4947
4948      // If the desired elements are smaller or larger than the source
4949      // elements we can use a matching integer vector type and then
4950      // truncate/sign extend
4951      EVT MatchingElementType =
4952        EVT::getIntegerVT(*DAG.getContext(),
4953                          N0VT.getScalarType().getSizeInBits());
4954      EVT MatchingVectorType =
4955        EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4956                         N0VT.getVectorNumElements());
4957      SDValue VsetCC =
4958        DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4959                      N0.getOperand(1),
4960                      cast<CondCodeSDNode>(N0.getOperand(2))->get());
4961      return DAG.getNode(ISD::AND, SDLoc(N), VT,
4962                         DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4963                         DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4964                                     &OneOps[0], OneOps.size()));
4965    }
4966
4967    // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4968    SDValue SCC =
4969      SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4970                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4971                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4972    if (SCC.getNode()) return SCC;
4973  }
4974
4975  // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4976  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4977      isa<ConstantSDNode>(N0.getOperand(1)) &&
4978      N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4979      N0.hasOneUse()) {
4980    SDValue ShAmt = N0.getOperand(1);
4981    unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4982    if (N0.getOpcode() == ISD::SHL) {
4983      SDValue InnerZExt = N0.getOperand(0);
4984      // If the original shl may be shifting out bits, do not perform this
4985      // transformation.
4986      unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4987        InnerZExt.getOperand(0).getValueType().getSizeInBits();
4988      if (ShAmtVal > KnownZeroBits)
4989        return SDValue();
4990    }
4991
4992    SDLoc DL(N);
4993
4994    // Ensure that the shift amount is wide enough for the shifted value.
4995    if (VT.getSizeInBits() >= 256)
4996      ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4997
4998    return DAG.getNode(N0.getOpcode(), DL, VT,
4999                       DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5000                       ShAmt);
5001  }
5002
5003  return SDValue();
5004}
5005
5006SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5007  SDValue N0 = N->getOperand(0);
5008  EVT VT = N->getValueType(0);
5009
5010  // fold (aext c1) -> c1
5011  if (isa<ConstantSDNode>(N0))
5012    return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5013  // fold (aext (aext x)) -> (aext x)
5014  // fold (aext (zext x)) -> (zext x)
5015  // fold (aext (sext x)) -> (sext x)
5016  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5017      N0.getOpcode() == ISD::ZERO_EXTEND ||
5018      N0.getOpcode() == ISD::SIGN_EXTEND)
5019    return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5020
5021  // fold (aext (truncate (load x))) -> (aext (smaller load x))
5022  // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5023  if (N0.getOpcode() == ISD::TRUNCATE) {
5024    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5025    if (NarrowLoad.getNode()) {
5026      SDNode* oye = N0.getNode()->getOperand(0).getNode();
5027      if (NarrowLoad.getNode() != N0.getNode()) {
5028        CombineTo(N0.getNode(), NarrowLoad);
5029        // CombineTo deleted the truncate, if needed, but not what's under it.
5030        AddToWorkList(oye);
5031      }
5032      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5033    }
5034  }
5035
5036  // fold (aext (truncate x))
5037  if (N0.getOpcode() == ISD::TRUNCATE) {
5038    SDValue TruncOp = N0.getOperand(0);
5039    if (TruncOp.getValueType() == VT)
5040      return TruncOp; // x iff x size == zext size.
5041    if (TruncOp.getValueType().bitsGT(VT))
5042      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5043    return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5044  }
5045
5046  // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5047  // if the trunc is not free.
5048  if (N0.getOpcode() == ISD::AND &&
5049      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5050      N0.getOperand(1).getOpcode() == ISD::Constant &&
5051      !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5052                          N0.getValueType())) {
5053    SDValue X = N0.getOperand(0).getOperand(0);
5054    if (X.getValueType().bitsLT(VT)) {
5055      X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5056    } else if (X.getValueType().bitsGT(VT)) {
5057      X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5058    }
5059    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5060    Mask = Mask.zext(VT.getSizeInBits());
5061    return DAG.getNode(ISD::AND, SDLoc(N), VT,
5062                       X, DAG.getConstant(Mask, VT));
5063  }
5064
5065  // fold (aext (load x)) -> (aext (truncate (extload x)))
5066  // None of the supported targets knows how to perform load and any_ext
5067  // on vectors in one instruction.  We only perform this transformation on
5068  // scalars.
5069  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5070      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5071       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5072    bool DoXform = true;
5073    SmallVector<SDNode*, 4> SetCCs;
5074    if (!N0.hasOneUse())
5075      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5076    if (DoXform) {
5077      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5078      SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5079                                       LN0->getChain(),
5080                                       LN0->getBasePtr(), N0.getValueType(),
5081                                       LN0->getMemOperand());
5082      CombineTo(N, ExtLoad);
5083      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5084                                  N0.getValueType(), ExtLoad);
5085      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5086      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5087                      ISD::ANY_EXTEND);
5088      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5089    }
5090  }
5091
5092  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5093  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5094  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5095  if (N0.getOpcode() == ISD::LOAD &&
5096      !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5097      N0.hasOneUse()) {
5098    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5099    EVT MemVT = LN0->getMemoryVT();
5100    SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5101                                     VT, LN0->getChain(), LN0->getBasePtr(),
5102                                     MemVT, LN0->getMemOperand());
5103    CombineTo(N, ExtLoad);
5104    CombineTo(N0.getNode(),
5105              DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5106                          N0.getValueType(), ExtLoad),
5107              ExtLoad.getValue(1));
5108    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5109  }
5110
5111  if (N0.getOpcode() == ISD::SETCC) {
5112    // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5113    // Only do this before legalize for now.
5114    if (VT.isVector() && !LegalOperations) {
5115      EVT N0VT = N0.getOperand(0).getValueType();
5116        // We know that the # elements of the results is the same as the
5117        // # elements of the compare (and the # elements of the compare result
5118        // for that matter).  Check to see that they are the same size.  If so,
5119        // we know that the element size of the sext'd result matches the
5120        // element size of the compare operands.
5121      if (VT.getSizeInBits() == N0VT.getSizeInBits())
5122        return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5123                             N0.getOperand(1),
5124                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
5125      // If the desired elements are smaller or larger than the source
5126      // elements we can use a matching integer vector type and then
5127      // truncate/sign extend
5128      else {
5129        EVT MatchingElementType =
5130          EVT::getIntegerVT(*DAG.getContext(),
5131                            N0VT.getScalarType().getSizeInBits());
5132        EVT MatchingVectorType =
5133          EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5134                           N0VT.getVectorNumElements());
5135        SDValue VsetCC =
5136          DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5137                        N0.getOperand(1),
5138                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
5139        return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5140      }
5141    }
5142
5143    // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5144    SDValue SCC =
5145      SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5146                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5147                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5148    if (SCC.getNode())
5149      return SCC;
5150  }
5151
5152  return SDValue();
5153}
5154
5155/// GetDemandedBits - See if the specified operand can be simplified with the
5156/// knowledge that only the bits specified by Mask are used.  If so, return the
5157/// simpler operand, otherwise return a null SDValue.
5158SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5159  switch (V.getOpcode()) {
5160  default: break;
5161  case ISD::Constant: {
5162    const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5163    assert(CV != 0 && "Const value should be ConstSDNode.");
5164    const APInt &CVal = CV->getAPIntValue();
5165    APInt NewVal = CVal & Mask;
5166    if (NewVal != CVal)
5167      return DAG.getConstant(NewVal, V.getValueType());
5168    break;
5169  }
5170  case ISD::OR:
5171  case ISD::XOR:
5172    // If the LHS or RHS don't contribute bits to the or, drop them.
5173    if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5174      return V.getOperand(1);
5175    if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5176      return V.getOperand(0);
5177    break;
5178  case ISD::SRL:
5179    // Only look at single-use SRLs.
5180    if (!V.getNode()->hasOneUse())
5181      break;
5182    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5183      // See if we can recursively simplify the LHS.
5184      unsigned Amt = RHSC->getZExtValue();
5185
5186      // Watch out for shift count overflow though.
5187      if (Amt >= Mask.getBitWidth()) break;
5188      APInt NewMask = Mask << Amt;
5189      SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5190      if (SimplifyLHS.getNode())
5191        return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5192                           SimplifyLHS, V.getOperand(1));
5193    }
5194  }
5195  return SDValue();
5196}
5197
5198/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5199/// bits and then truncated to a narrower type and where N is a multiple
5200/// of number of bits of the narrower type, transform it to a narrower load
5201/// from address + N / num of bits of new type. If the result is to be
5202/// extended, also fold the extension to form a extending load.
5203SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5204  unsigned Opc = N->getOpcode();
5205
5206  ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5207  SDValue N0 = N->getOperand(0);
5208  EVT VT = N->getValueType(0);
5209  EVT ExtVT = VT;
5210
5211  // This transformation isn't valid for vector loads.
5212  if (VT.isVector())
5213    return SDValue();
5214
5215  // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5216  // extended to VT.
5217  if (Opc == ISD::SIGN_EXTEND_INREG) {
5218    ExtType = ISD::SEXTLOAD;
5219    ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5220  } else if (Opc == ISD::SRL) {
5221    // Another special-case: SRL is basically zero-extending a narrower value.
5222    ExtType = ISD::ZEXTLOAD;
5223    N0 = SDValue(N, 0);
5224    ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5225    if (!N01) return SDValue();
5226    ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5227                              VT.getSizeInBits() - N01->getZExtValue());
5228  }
5229  if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5230    return SDValue();
5231
5232  unsigned EVTBits = ExtVT.getSizeInBits();
5233
5234  // Do not generate loads of non-round integer types since these can
5235  // be expensive (and would be wrong if the type is not byte sized).
5236  if (!ExtVT.isRound())
5237    return SDValue();
5238
5239  unsigned ShAmt = 0;
5240  if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5241    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5242      ShAmt = N01->getZExtValue();
5243      // Is the shift amount a multiple of size of VT?
5244      if ((ShAmt & (EVTBits-1)) == 0) {
5245        N0 = N0.getOperand(0);
5246        // Is the load width a multiple of size of VT?
5247        if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5248          return SDValue();
5249      }
5250
5251      // At this point, we must have a load or else we can't do the transform.
5252      if (!isa<LoadSDNode>(N0)) return SDValue();
5253
5254      // Because a SRL must be assumed to *need* to zero-extend the high bits
5255      // (as opposed to anyext the high bits), we can't combine the zextload
5256      // lowering of SRL and an sextload.
5257      if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5258        return SDValue();
5259
5260      // If the shift amount is larger than the input type then we're not
5261      // accessing any of the loaded bytes.  If the load was a zextload/extload
5262      // then the result of the shift+trunc is zero/undef (handled elsewhere).
5263      if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5264        return SDValue();
5265    }
5266  }
5267
5268  // If the load is shifted left (and the result isn't shifted back right),
5269  // we can fold the truncate through the shift.
5270  unsigned ShLeftAmt = 0;
5271  if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5272      ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5273    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5274      ShLeftAmt = N01->getZExtValue();
5275      N0 = N0.getOperand(0);
5276    }
5277  }
5278
5279  // If we haven't found a load, we can't narrow it.  Don't transform one with
5280  // multiple uses, this would require adding a new load.
5281  if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5282    return SDValue();
5283
5284  // Don't change the width of a volatile load.
5285  LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5286  if (LN0->isVolatile())
5287    return SDValue();
5288
5289  // Verify that we are actually reducing a load width here.
5290  if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5291    return SDValue();
5292
5293  // For the transform to be legal, the load must produce only two values
5294  // (the value loaded and the chain).  Don't transform a pre-increment
5295  // load, for example, which produces an extra value.  Otherwise the
5296  // transformation is not equivalent, and the downstream logic to replace
5297  // uses gets things wrong.
5298  if (LN0->getNumValues() > 2)
5299    return SDValue();
5300
5301  // If the load that we're shrinking is an extload and we're not just
5302  // discarding the extension we can't simply shrink the load. Bail.
5303  // TODO: It would be possible to merge the extensions in some cases.
5304  if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5305      LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5306    return SDValue();
5307
5308  EVT PtrType = N0.getOperand(1).getValueType();
5309
5310  if (PtrType == MVT::Untyped || PtrType.isExtended())
5311    // It's not possible to generate a constant of extended or untyped type.
5312    return SDValue();
5313
5314  // For big endian targets, we need to adjust the offset to the pointer to
5315  // load the correct bytes.
5316  if (TLI.isBigEndian()) {
5317    unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5318    unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5319    ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5320  }
5321
5322  uint64_t PtrOff = ShAmt / 8;
5323  unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5324  SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5325                               PtrType, LN0->getBasePtr(),
5326                               DAG.getConstant(PtrOff, PtrType));
5327  AddToWorkList(NewPtr.getNode());
5328
5329  SDValue Load;
5330  if (ExtType == ISD::NON_EXTLOAD)
5331    Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5332                        LN0->getPointerInfo().getWithOffset(PtrOff),
5333                        LN0->isVolatile(), LN0->isNonTemporal(),
5334                        LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5335  else
5336    Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5337                          LN0->getPointerInfo().getWithOffset(PtrOff),
5338                          ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5339                          NewAlign, LN0->getTBAAInfo());
5340
5341  // Replace the old load's chain with the new load's chain.
5342  WorkListRemover DeadNodes(*this);
5343  DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5344
5345  // Shift the result left, if we've swallowed a left shift.
5346  SDValue Result = Load;
5347  if (ShLeftAmt != 0) {
5348    EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5349    if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5350      ShImmTy = VT;
5351    // If the shift amount is as large as the result size (but, presumably,
5352    // no larger than the source) then the useful bits of the result are
5353    // zero; we can't simply return the shortened shift, because the result
5354    // of that operation is undefined.
5355    if (ShLeftAmt >= VT.getSizeInBits())
5356      Result = DAG.getConstant(0, VT);
5357    else
5358      Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5359                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5360  }
5361
5362  // Return the new loaded value.
5363  return Result;
5364}
5365
5366SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5367  SDValue N0 = N->getOperand(0);
5368  SDValue N1 = N->getOperand(1);
5369  EVT VT = N->getValueType(0);
5370  EVT EVT = cast<VTSDNode>(N1)->getVT();
5371  unsigned VTBits = VT.getScalarType().getSizeInBits();
5372  unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5373
5374  // fold (sext_in_reg c1) -> c1
5375  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5376    return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5377
5378  // If the input is already sign extended, just drop the extension.
5379  if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5380    return N0;
5381
5382  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5383  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5384      EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5385    return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5386                       N0.getOperand(0), N1);
5387
5388  // fold (sext_in_reg (sext x)) -> (sext x)
5389  // fold (sext_in_reg (aext x)) -> (sext x)
5390  // if x is small enough.
5391  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5392    SDValue N00 = N0.getOperand(0);
5393    if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5394        (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5395      return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5396  }
5397
5398  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5399  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5400    return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5401
5402  // fold operands of sext_in_reg based on knowledge that the top bits are not
5403  // demanded.
5404  if (SimplifyDemandedBits(SDValue(N, 0)))
5405    return SDValue(N, 0);
5406
5407  // fold (sext_in_reg (load x)) -> (smaller sextload x)
5408  // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5409  SDValue NarrowLoad = ReduceLoadWidth(N);
5410  if (NarrowLoad.getNode())
5411    return NarrowLoad;
5412
5413  // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5414  // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5415  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5416  if (N0.getOpcode() == ISD::SRL) {
5417    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5418      if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5419        // We can turn this into an SRA iff the input to the SRL is already sign
5420        // extended enough.
5421        unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5422        if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5423          return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5424                             N0.getOperand(0), N0.getOperand(1));
5425      }
5426  }
5427
5428  // fold (sext_inreg (extload x)) -> (sextload x)
5429  if (ISD::isEXTLoad(N0.getNode()) &&
5430      ISD::isUNINDEXEDLoad(N0.getNode()) &&
5431      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5432      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5433       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5434    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5435    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5436                                     LN0->getChain(),
5437                                     LN0->getBasePtr(), EVT,
5438                                     LN0->getMemOperand());
5439    CombineTo(N, ExtLoad);
5440    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5441    AddToWorkList(ExtLoad.getNode());
5442    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5443  }
5444  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5445  if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5446      N0.hasOneUse() &&
5447      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5448      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5449       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5450    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5451    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5452                                     LN0->getChain(),
5453                                     LN0->getBasePtr(), EVT,
5454                                     LN0->getMemOperand());
5455    CombineTo(N, ExtLoad);
5456    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5457    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5458  }
5459
5460  // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5461  if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5462    SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5463                                       N0.getOperand(1), false);
5464    if (BSwap.getNode() != 0)
5465      return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5466                         BSwap, N1);
5467  }
5468
5469  return SDValue();
5470}
5471
5472SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5473  SDValue N0 = N->getOperand(0);
5474  EVT VT = N->getValueType(0);
5475  bool isLE = TLI.isLittleEndian();
5476
5477  // noop truncate
5478  if (N0.getValueType() == N->getValueType(0))
5479    return N0;
5480  // fold (truncate c1) -> c1
5481  if (isa<ConstantSDNode>(N0))
5482    return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5483  // fold (truncate (truncate x)) -> (truncate x)
5484  if (N0.getOpcode() == ISD::TRUNCATE)
5485    return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5486  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5487  if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5488      N0.getOpcode() == ISD::SIGN_EXTEND ||
5489      N0.getOpcode() == ISD::ANY_EXTEND) {
5490    if (N0.getOperand(0).getValueType().bitsLT(VT))
5491      // if the source is smaller than the dest, we still need an extend
5492      return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5493                         N0.getOperand(0));
5494    if (N0.getOperand(0).getValueType().bitsGT(VT))
5495      // if the source is larger than the dest, than we just need the truncate
5496      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5497    // if the source and dest are the same type, we can drop both the extend
5498    // and the truncate.
5499    return N0.getOperand(0);
5500  }
5501
5502  // Fold extract-and-trunc into a narrow extract. For example:
5503  //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5504  //   i32 y = TRUNCATE(i64 x)
5505  //        -- becomes --
5506  //   v16i8 b = BITCAST (v2i64 val)
5507  //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5508  //
5509  // Note: We only run this optimization after type legalization (which often
5510  // creates this pattern) and before operation legalization after which
5511  // we need to be more careful about the vector instructions that we generate.
5512  if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5513      LegalTypes && !LegalOperations && N0->hasOneUse()) {
5514
5515    EVT VecTy = N0.getOperand(0).getValueType();
5516    EVT ExTy = N0.getValueType();
5517    EVT TrTy = N->getValueType(0);
5518
5519    unsigned NumElem = VecTy.getVectorNumElements();
5520    unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5521
5522    EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5523    assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5524
5525    SDValue EltNo = N0->getOperand(1);
5526    if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5527      int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5528      EVT IndexTy = TLI.getVectorIdxTy();
5529      int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5530
5531      SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5532                              NVT, N0.getOperand(0));
5533
5534      return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5535                         SDLoc(N), TrTy, V,
5536                         DAG.getConstant(Index, IndexTy));
5537    }
5538  }
5539
5540  // Fold a series of buildvector, bitcast, and truncate if possible.
5541  // For example fold
5542  //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5543  //   (2xi32 (buildvector x, y)).
5544  if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5545      N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5546      N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5547      N0.getOperand(0).hasOneUse()) {
5548
5549    SDValue BuildVect = N0.getOperand(0);
5550    EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5551    EVT TruncVecEltTy = VT.getVectorElementType();
5552
5553    // Check that the element types match.
5554    if (BuildVectEltTy == TruncVecEltTy) {
5555      // Now we only need to compute the offset of the truncated elements.
5556      unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5557      unsigned TruncVecNumElts = VT.getVectorNumElements();
5558      unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5559
5560      assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5561             "Invalid number of elements");
5562
5563      SmallVector<SDValue, 8> Opnds;
5564      for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5565        Opnds.push_back(BuildVect.getOperand(i));
5566
5567      return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5568                         Opnds.size());
5569    }
5570  }
5571
5572  // See if we can simplify the input to this truncate through knowledge that
5573  // only the low bits are being used.
5574  // For example "trunc (or (shl x, 8), y)" // -> trunc y
5575  // Currently we only perform this optimization on scalars because vectors
5576  // may have different active low bits.
5577  if (!VT.isVector()) {
5578    SDValue Shorter =
5579      GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5580                                               VT.getSizeInBits()));
5581    if (Shorter.getNode())
5582      return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5583  }
5584  // fold (truncate (load x)) -> (smaller load x)
5585  // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5586  if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5587    SDValue Reduced = ReduceLoadWidth(N);
5588    if (Reduced.getNode())
5589      return Reduced;
5590  }
5591  // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5592  // where ... are all 'undef'.
5593  if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5594    SmallVector<EVT, 8> VTs;
5595    SDValue V;
5596    unsigned Idx = 0;
5597    unsigned NumDefs = 0;
5598
5599    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5600      SDValue X = N0.getOperand(i);
5601      if (X.getOpcode() != ISD::UNDEF) {
5602        V = X;
5603        Idx = i;
5604        NumDefs++;
5605      }
5606      // Stop if more than one members are non-undef.
5607      if (NumDefs > 1)
5608        break;
5609      VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5610                                     VT.getVectorElementType(),
5611                                     X.getValueType().getVectorNumElements()));
5612    }
5613
5614    if (NumDefs == 0)
5615      return DAG.getUNDEF(VT);
5616
5617    if (NumDefs == 1) {
5618      assert(V.getNode() && "The single defined operand is empty!");
5619      SmallVector<SDValue, 8> Opnds;
5620      for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5621        if (i != Idx) {
5622          Opnds.push_back(DAG.getUNDEF(VTs[i]));
5623          continue;
5624        }
5625        SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5626        AddToWorkList(NV.getNode());
5627        Opnds.push_back(NV);
5628      }
5629      return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5630                         &Opnds[0], Opnds.size());
5631    }
5632  }
5633
5634  // Simplify the operands using demanded-bits information.
5635  if (!VT.isVector() &&
5636      SimplifyDemandedBits(SDValue(N, 0)))
5637    return SDValue(N, 0);
5638
5639  return SDValue();
5640}
5641
5642static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5643  SDValue Elt = N->getOperand(i);
5644  if (Elt.getOpcode() != ISD::MERGE_VALUES)
5645    return Elt.getNode();
5646  return Elt.getOperand(Elt.getResNo()).getNode();
5647}
5648
5649/// CombineConsecutiveLoads - build_pair (load, load) -> load
5650/// if load locations are consecutive.
5651SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5652  assert(N->getOpcode() == ISD::BUILD_PAIR);
5653
5654  LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5655  LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5656  if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5657      LD1->getPointerInfo().getAddrSpace() !=
5658         LD2->getPointerInfo().getAddrSpace())
5659    return SDValue();
5660  EVT LD1VT = LD1->getValueType(0);
5661
5662  if (ISD::isNON_EXTLoad(LD2) &&
5663      LD2->hasOneUse() &&
5664      // If both are volatile this would reduce the number of volatile loads.
5665      // If one is volatile it might be ok, but play conservative and bail out.
5666      !LD1->isVolatile() &&
5667      !LD2->isVolatile() &&
5668      DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5669    unsigned Align = LD1->getAlignment();
5670    unsigned NewAlign = TLI.getDataLayout()->
5671      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5672
5673    if (NewAlign <= Align &&
5674        (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5675      return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5676                         LD1->getBasePtr(), LD1->getPointerInfo(),
5677                         false, false, false, Align);
5678  }
5679
5680  return SDValue();
5681}
5682
5683SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5684  SDValue N0 = N->getOperand(0);
5685  EVT VT = N->getValueType(0);
5686
5687  // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5688  // Only do this before legalize, since afterward the target may be depending
5689  // on the bitconvert.
5690  // First check to see if this is all constant.
5691  if (!LegalTypes &&
5692      N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5693      VT.isVector()) {
5694    bool isSimple = true;
5695    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5696      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5697          N0.getOperand(i).getOpcode() != ISD::Constant &&
5698          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5699        isSimple = false;
5700        break;
5701      }
5702
5703    EVT DestEltVT = N->getValueType(0).getVectorElementType();
5704    assert(!DestEltVT.isVector() &&
5705           "Element type of vector ValueType must not be vector!");
5706    if (isSimple)
5707      return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5708  }
5709
5710  // If the input is a constant, let getNode fold it.
5711  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5712    SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5713    if (Res.getNode() != N) {
5714      if (!LegalOperations ||
5715          TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5716        return Res;
5717
5718      // Folding it resulted in an illegal node, and it's too late to
5719      // do that. Clean up the old node and forego the transformation.
5720      // Ideally this won't happen very often, because instcombine
5721      // and the earlier dagcombine runs (where illegal nodes are
5722      // permitted) should have folded most of them already.
5723      DAG.DeleteNode(Res.getNode());
5724    }
5725  }
5726
5727  // (conv (conv x, t1), t2) -> (conv x, t2)
5728  if (N0.getOpcode() == ISD::BITCAST)
5729    return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5730                       N0.getOperand(0));
5731
5732  // fold (conv (load x)) -> (load (conv*)x)
5733  // If the resultant load doesn't need a higher alignment than the original!
5734  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5735      // Do not change the width of a volatile load.
5736      !cast<LoadSDNode>(N0)->isVolatile() &&
5737      (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5738      TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5739    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5740    unsigned Align = TLI.getDataLayout()->
5741      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5742    unsigned OrigAlign = LN0->getAlignment();
5743
5744    if (Align <= OrigAlign) {
5745      SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5746                                 LN0->getBasePtr(), LN0->getPointerInfo(),
5747                                 LN0->isVolatile(), LN0->isNonTemporal(),
5748                                 LN0->isInvariant(), OrigAlign,
5749                                 LN0->getTBAAInfo());
5750      AddToWorkList(N);
5751      CombineTo(N0.getNode(),
5752                DAG.getNode(ISD::BITCAST, SDLoc(N0),
5753                            N0.getValueType(), Load),
5754                Load.getValue(1));
5755      return Load;
5756    }
5757  }
5758
5759  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5760  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5761  // This often reduces constant pool loads.
5762  if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5763       (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5764      N0.getNode()->hasOneUse() && VT.isInteger() &&
5765      !VT.isVector() && !N0.getValueType().isVector()) {
5766    SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5767                                  N0.getOperand(0));
5768    AddToWorkList(NewConv.getNode());
5769
5770    APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5771    if (N0.getOpcode() == ISD::FNEG)
5772      return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5773                         NewConv, DAG.getConstant(SignBit, VT));
5774    assert(N0.getOpcode() == ISD::FABS);
5775    return DAG.getNode(ISD::AND, SDLoc(N), VT,
5776                       NewConv, DAG.getConstant(~SignBit, VT));
5777  }
5778
5779  // fold (bitconvert (fcopysign cst, x)) ->
5780  //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5781  // Note that we don't handle (copysign x, cst) because this can always be
5782  // folded to an fneg or fabs.
5783  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5784      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5785      VT.isInteger() && !VT.isVector()) {
5786    unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5787    EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5788    if (isTypeLegal(IntXVT)) {
5789      SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5790                              IntXVT, N0.getOperand(1));
5791      AddToWorkList(X.getNode());
5792
5793      // If X has a different width than the result/lhs, sext it or truncate it.
5794      unsigned VTWidth = VT.getSizeInBits();
5795      if (OrigXWidth < VTWidth) {
5796        X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5797        AddToWorkList(X.getNode());
5798      } else if (OrigXWidth > VTWidth) {
5799        // To get the sign bit in the right place, we have to shift it right
5800        // before truncating.
5801        X = DAG.getNode(ISD::SRL, SDLoc(X),
5802                        X.getValueType(), X,
5803                        DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5804        AddToWorkList(X.getNode());
5805        X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5806        AddToWorkList(X.getNode());
5807      }
5808
5809      APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5810      X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5811                      X, DAG.getConstant(SignBit, VT));
5812      AddToWorkList(X.getNode());
5813
5814      SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5815                                VT, N0.getOperand(0));
5816      Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5817                        Cst, DAG.getConstant(~SignBit, VT));
5818      AddToWorkList(Cst.getNode());
5819
5820      return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5821    }
5822  }
5823
5824  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5825  if (N0.getOpcode() == ISD::BUILD_PAIR) {
5826    SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5827    if (CombineLD.getNode())
5828      return CombineLD;
5829  }
5830
5831  return SDValue();
5832}
5833
5834SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5835  EVT VT = N->getValueType(0);
5836  return CombineConsecutiveLoads(N, VT);
5837}
5838
5839/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5840/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5841/// destination element value type.
5842SDValue DAGCombiner::
5843ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5844  EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5845
5846  // If this is already the right type, we're done.
5847  if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5848
5849  unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5850  unsigned DstBitSize = DstEltVT.getSizeInBits();
5851
5852  // If this is a conversion of N elements of one type to N elements of another
5853  // type, convert each element.  This handles FP<->INT cases.
5854  if (SrcBitSize == DstBitSize) {
5855    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5856                              BV->getValueType(0).getVectorNumElements());
5857
5858    // Due to the FP element handling below calling this routine recursively,
5859    // we can end up with a scalar-to-vector node here.
5860    if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5861      return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5862                         DAG.getNode(ISD::BITCAST, SDLoc(BV),
5863                                     DstEltVT, BV->getOperand(0)));
5864
5865    SmallVector<SDValue, 8> Ops;
5866    for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5867      SDValue Op = BV->getOperand(i);
5868      // If the vector element type is not legal, the BUILD_VECTOR operands
5869      // are promoted and implicitly truncated.  Make that explicit here.
5870      if (Op.getValueType() != SrcEltVT)
5871        Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5872      Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5873                                DstEltVT, Op));
5874      AddToWorkList(Ops.back().getNode());
5875    }
5876    return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5877                       &Ops[0], Ops.size());
5878  }
5879
5880  // Otherwise, we're growing or shrinking the elements.  To avoid having to
5881  // handle annoying details of growing/shrinking FP values, we convert them to
5882  // int first.
5883  if (SrcEltVT.isFloatingPoint()) {
5884    // Convert the input float vector to a int vector where the elements are the
5885    // same sizes.
5886    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5887    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5888    BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5889    SrcEltVT = IntVT;
5890  }
5891
5892  // Now we know the input is an integer vector.  If the output is a FP type,
5893  // convert to integer first, then to FP of the right size.
5894  if (DstEltVT.isFloatingPoint()) {
5895    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5896    EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5897    SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5898
5899    // Next, convert to FP elements of the same size.
5900    return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5901  }
5902
5903  // Okay, we know the src/dst types are both integers of differing types.
5904  // Handling growing first.
5905  assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5906  if (SrcBitSize < DstBitSize) {
5907    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5908
5909    SmallVector<SDValue, 8> Ops;
5910    for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5911         i += NumInputsPerOutput) {
5912      bool isLE = TLI.isLittleEndian();
5913      APInt NewBits = APInt(DstBitSize, 0);
5914      bool EltIsUndef = true;
5915      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5916        // Shift the previously computed bits over.
5917        NewBits <<= SrcBitSize;
5918        SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5919        if (Op.getOpcode() == ISD::UNDEF) continue;
5920        EltIsUndef = false;
5921
5922        NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5923                   zextOrTrunc(SrcBitSize).zext(DstBitSize);
5924      }
5925
5926      if (EltIsUndef)
5927        Ops.push_back(DAG.getUNDEF(DstEltVT));
5928      else
5929        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5930    }
5931
5932    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5933    return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5934                       &Ops[0], Ops.size());
5935  }
5936
5937  // Finally, this must be the case where we are shrinking elements: each input
5938  // turns into multiple outputs.
5939  bool isS2V = ISD::isScalarToVector(BV);
5940  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5941  EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5942                            NumOutputsPerInput*BV->getNumOperands());
5943  SmallVector<SDValue, 8> Ops;
5944
5945  for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5946    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5947      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5948        Ops.push_back(DAG.getUNDEF(DstEltVT));
5949      continue;
5950    }
5951
5952    APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5953                  getAPIntValue().zextOrTrunc(SrcBitSize);
5954
5955    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5956      APInt ThisVal = OpVal.trunc(DstBitSize);
5957      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5958      if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5959        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5960        return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5961                           Ops[0]);
5962      OpVal = OpVal.lshr(DstBitSize);
5963    }
5964
5965    // For big endian targets, swap the order of the pieces of each element.
5966    if (TLI.isBigEndian())
5967      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5968  }
5969
5970  return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5971                     &Ops[0], Ops.size());
5972}
5973
5974SDValue DAGCombiner::visitFADD(SDNode *N) {
5975  SDValue N0 = N->getOperand(0);
5976  SDValue N1 = N->getOperand(1);
5977  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5978  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5979  EVT VT = N->getValueType(0);
5980
5981  // fold vector ops
5982  if (VT.isVector()) {
5983    SDValue FoldedVOp = SimplifyVBinOp(N);
5984    if (FoldedVOp.getNode()) return FoldedVOp;
5985  }
5986
5987  // fold (fadd c1, c2) -> c1 + c2
5988  if (N0CFP && N1CFP)
5989    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5990  // canonicalize constant to RHS
5991  if (N0CFP && !N1CFP)
5992    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5993  // fold (fadd A, 0) -> A
5994  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5995      N1CFP->getValueAPF().isZero())
5996    return N0;
5997  // fold (fadd A, (fneg B)) -> (fsub A, B)
5998  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5999    isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6000    return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6001                       GetNegatedExpression(N1, DAG, LegalOperations));
6002  // fold (fadd (fneg A), B) -> (fsub B, A)
6003  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6004    isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6005    return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6006                       GetNegatedExpression(N0, DAG, LegalOperations));
6007
6008  // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6009  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6010      N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6011      isa<ConstantFPSDNode>(N0.getOperand(1)))
6012    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6013                       DAG.getNode(ISD::FADD, SDLoc(N), VT,
6014                                   N0.getOperand(1), N1));
6015
6016  // No FP constant should be created after legalization as Instruction
6017  // Selection pass has hard time in dealing with FP constant.
6018  //
6019  // We don't need test this condition for transformation like following, as
6020  // the DAG being transformed implies it is legal to take FP constant as
6021  // operand.
6022  //
6023  //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6024  //
6025  bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6026
6027  // If allow, fold (fadd (fneg x), x) -> 0.0
6028  if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6029      N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6030    return DAG.getConstantFP(0.0, VT);
6031
6032    // If allow, fold (fadd x, (fneg x)) -> 0.0
6033  if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6034      N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6035    return DAG.getConstantFP(0.0, VT);
6036
6037  // In unsafe math mode, we can fold chains of FADD's of the same value
6038  // into multiplications.  This transform is not safe in general because
6039  // we are reducing the number of rounding steps.
6040  if (DAG.getTarget().Options.UnsafeFPMath &&
6041      TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6042      !N0CFP && !N1CFP) {
6043    if (N0.getOpcode() == ISD::FMUL) {
6044      ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6045      ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6046
6047      // (fadd (fmul c, x), x) -> (fmul x, c+1)
6048      if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6049        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6050                                     SDValue(CFP00, 0),
6051                                     DAG.getConstantFP(1.0, VT));
6052        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6053                           N1, NewCFP);
6054      }
6055
6056      // (fadd (fmul x, c), x) -> (fmul x, c+1)
6057      if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6058        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6059                                     SDValue(CFP01, 0),
6060                                     DAG.getConstantFP(1.0, VT));
6061        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6062                           N1, NewCFP);
6063      }
6064
6065      // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6066      if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6067          N1.getOperand(0) == N1.getOperand(1) &&
6068          N0.getOperand(1) == N1.getOperand(0)) {
6069        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6070                                     SDValue(CFP00, 0),
6071                                     DAG.getConstantFP(2.0, VT));
6072        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6073                           N0.getOperand(1), NewCFP);
6074      }
6075
6076      // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6077      if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6078          N1.getOperand(0) == N1.getOperand(1) &&
6079          N0.getOperand(0) == N1.getOperand(0)) {
6080        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6081                                     SDValue(CFP01, 0),
6082                                     DAG.getConstantFP(2.0, VT));
6083        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6084                           N0.getOperand(0), NewCFP);
6085      }
6086    }
6087
6088    if (N1.getOpcode() == ISD::FMUL) {
6089      ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6090      ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6091
6092      // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6093      if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6094        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6095                                     SDValue(CFP10, 0),
6096                                     DAG.getConstantFP(1.0, VT));
6097        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6098                           N0, NewCFP);
6099      }
6100
6101      // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6102      if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6103        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6104                                     SDValue(CFP11, 0),
6105                                     DAG.getConstantFP(1.0, VT));
6106        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6107                           N0, NewCFP);
6108      }
6109
6110
6111      // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6112      if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6113          N0.getOperand(0) == N0.getOperand(1) &&
6114          N1.getOperand(1) == N0.getOperand(0)) {
6115        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6116                                     SDValue(CFP10, 0),
6117                                     DAG.getConstantFP(2.0, VT));
6118        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6119                           N1.getOperand(1), NewCFP);
6120      }
6121
6122      // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6123      if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6124          N0.getOperand(0) == N0.getOperand(1) &&
6125          N1.getOperand(0) == N0.getOperand(0)) {
6126        SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6127                                     SDValue(CFP11, 0),
6128                                     DAG.getConstantFP(2.0, VT));
6129        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6130                           N1.getOperand(0), NewCFP);
6131      }
6132    }
6133
6134    if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6135      ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6136      // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6137      if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6138          (N0.getOperand(0) == N1))
6139        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6140                           N1, DAG.getConstantFP(3.0, VT));
6141    }
6142
6143    if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6144      ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6145      // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6146      if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6147          N1.getOperand(0) == N0)
6148        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6149                           N0, DAG.getConstantFP(3.0, VT));
6150    }
6151
6152    // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6153    if (AllowNewFpConst &&
6154        N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6155        N0.getOperand(0) == N0.getOperand(1) &&
6156        N1.getOperand(0) == N1.getOperand(1) &&
6157        N0.getOperand(0) == N1.getOperand(0))
6158      return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6159                         N0.getOperand(0),
6160                         DAG.getConstantFP(4.0, VT));
6161  }
6162
6163  // FADD -> FMA combines:
6164  if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6165       DAG.getTarget().Options.UnsafeFPMath) &&
6166      DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6167      (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6168
6169    // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6170    if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6171      return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6172                         N0.getOperand(0), N0.getOperand(1), N1);
6173
6174    // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6175    // Note: Commutes FADD operands.
6176    if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6177      return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6178                         N1.getOperand(0), N1.getOperand(1), N0);
6179  }
6180
6181  return SDValue();
6182}
6183
6184SDValue DAGCombiner::visitFSUB(SDNode *N) {
6185  SDValue N0 = N->getOperand(0);
6186  SDValue N1 = N->getOperand(1);
6187  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6188  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6189  EVT VT = N->getValueType(0);
6190  SDLoc dl(N);
6191
6192  // fold vector ops
6193  if (VT.isVector()) {
6194    SDValue FoldedVOp = SimplifyVBinOp(N);
6195    if (FoldedVOp.getNode()) return FoldedVOp;
6196  }
6197
6198  // fold (fsub c1, c2) -> c1-c2
6199  if (N0CFP && N1CFP)
6200    return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6201  // fold (fsub A, 0) -> A
6202  if (DAG.getTarget().Options.UnsafeFPMath &&
6203      N1CFP && N1CFP->getValueAPF().isZero())
6204    return N0;
6205  // fold (fsub 0, B) -> -B
6206  if (DAG.getTarget().Options.UnsafeFPMath &&
6207      N0CFP && N0CFP->getValueAPF().isZero()) {
6208    if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6209      return GetNegatedExpression(N1, DAG, LegalOperations);
6210    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6211      return DAG.getNode(ISD::FNEG, dl, VT, N1);
6212  }
6213  // fold (fsub A, (fneg B)) -> (fadd A, B)
6214  if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6215    return DAG.getNode(ISD::FADD, dl, VT, N0,
6216                       GetNegatedExpression(N1, DAG, LegalOperations));
6217
6218  // If 'unsafe math' is enabled, fold
6219  //    (fsub x, x) -> 0.0 &
6220  //    (fsub x, (fadd x, y)) -> (fneg y) &
6221  //    (fsub x, (fadd y, x)) -> (fneg y)
6222  if (DAG.getTarget().Options.UnsafeFPMath) {
6223    if (N0 == N1)
6224      return DAG.getConstantFP(0.0f, VT);
6225
6226    if (N1.getOpcode() == ISD::FADD) {
6227      SDValue N10 = N1->getOperand(0);
6228      SDValue N11 = N1->getOperand(1);
6229
6230      if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6231                                          &DAG.getTarget().Options))
6232        return GetNegatedExpression(N11, DAG, LegalOperations);
6233
6234      if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6235                                          &DAG.getTarget().Options))
6236        return GetNegatedExpression(N10, DAG, LegalOperations);
6237    }
6238  }
6239
6240  // FSUB -> FMA combines:
6241  if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6242       DAG.getTarget().Options.UnsafeFPMath) &&
6243      DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6244      (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6245
6246    // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6247    if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6248      return DAG.getNode(ISD::FMA, dl, VT,
6249                         N0.getOperand(0), N0.getOperand(1),
6250                         DAG.getNode(ISD::FNEG, dl, VT, N1));
6251
6252    // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6253    // Note: Commutes FSUB operands.
6254    if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6255      return DAG.getNode(ISD::FMA, dl, VT,
6256                         DAG.getNode(ISD::FNEG, dl, VT,
6257                         N1.getOperand(0)),
6258                         N1.getOperand(1), N0);
6259
6260    // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6261    if (N0.getOpcode() == ISD::FNEG &&
6262        N0.getOperand(0).getOpcode() == ISD::FMUL &&
6263        N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6264      SDValue N00 = N0.getOperand(0).getOperand(0);
6265      SDValue N01 = N0.getOperand(0).getOperand(1);
6266      return DAG.getNode(ISD::FMA, dl, VT,
6267                         DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6268                         DAG.getNode(ISD::FNEG, dl, VT, N1));
6269    }
6270  }
6271
6272  return SDValue();
6273}
6274
6275SDValue DAGCombiner::visitFMUL(SDNode *N) {
6276  SDValue N0 = N->getOperand(0);
6277  SDValue N1 = N->getOperand(1);
6278  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6279  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6280  EVT VT = N->getValueType(0);
6281  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6282
6283  // fold vector ops
6284  if (VT.isVector()) {
6285    SDValue FoldedVOp = SimplifyVBinOp(N);
6286    if (FoldedVOp.getNode()) return FoldedVOp;
6287  }
6288
6289  // fold (fmul c1, c2) -> c1*c2
6290  if (N0CFP && N1CFP)
6291    return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6292  // canonicalize constant to RHS
6293  if (N0CFP && !N1CFP)
6294    return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6295  // fold (fmul A, 0) -> 0
6296  if (DAG.getTarget().Options.UnsafeFPMath &&
6297      N1CFP && N1CFP->getValueAPF().isZero())
6298    return N1;
6299  // fold (fmul A, 0) -> 0, vector edition.
6300  if (DAG.getTarget().Options.UnsafeFPMath &&
6301      ISD::isBuildVectorAllZeros(N1.getNode()))
6302    return N1;
6303  // fold (fmul A, 1.0) -> A
6304  if (N1CFP && N1CFP->isExactlyValue(1.0))
6305    return N0;
6306  // fold (fmul X, 2.0) -> (fadd X, X)
6307  if (N1CFP && N1CFP->isExactlyValue(+2.0))
6308    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6309  // fold (fmul X, -1.0) -> (fneg X)
6310  if (N1CFP && N1CFP->isExactlyValue(-1.0))
6311    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6312      return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6313
6314  // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6315  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6316                                       &DAG.getTarget().Options)) {
6317    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6318                                         &DAG.getTarget().Options)) {
6319      // Both can be negated for free, check to see if at least one is cheaper
6320      // negated.
6321      if (LHSNeg == 2 || RHSNeg == 2)
6322        return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6323                           GetNegatedExpression(N0, DAG, LegalOperations),
6324                           GetNegatedExpression(N1, DAG, LegalOperations));
6325    }
6326  }
6327
6328  // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6329  if (DAG.getTarget().Options.UnsafeFPMath &&
6330      N1CFP && N0.getOpcode() == ISD::FMUL &&
6331      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6332    return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6333                       DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6334                                   N0.getOperand(1), N1));
6335
6336  return SDValue();
6337}
6338
6339SDValue DAGCombiner::visitFMA(SDNode *N) {
6340  SDValue N0 = N->getOperand(0);
6341  SDValue N1 = N->getOperand(1);
6342  SDValue N2 = N->getOperand(2);
6343  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6344  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6345  EVT VT = N->getValueType(0);
6346  SDLoc dl(N);
6347
6348  if (DAG.getTarget().Options.UnsafeFPMath) {
6349    if (N0CFP && N0CFP->isZero())
6350      return N2;
6351    if (N1CFP && N1CFP->isZero())
6352      return N2;
6353  }
6354  if (N0CFP && N0CFP->isExactlyValue(1.0))
6355    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6356  if (N1CFP && N1CFP->isExactlyValue(1.0))
6357    return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6358
6359  // Canonicalize (fma c, x, y) -> (fma x, c, y)
6360  if (N0CFP && !N1CFP)
6361    return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6362
6363  // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6364  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6365      N2.getOpcode() == ISD::FMUL &&
6366      N0 == N2.getOperand(0) &&
6367      N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6368    return DAG.getNode(ISD::FMUL, dl, VT, N0,
6369                       DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6370  }
6371
6372
6373  // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6374  if (DAG.getTarget().Options.UnsafeFPMath &&
6375      N0.getOpcode() == ISD::FMUL && N1CFP &&
6376      N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6377    return DAG.getNode(ISD::FMA, dl, VT,
6378                       N0.getOperand(0),
6379                       DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6380                       N2);
6381  }
6382
6383  // (fma x, 1, y) -> (fadd x, y)
6384  // (fma x, -1, y) -> (fadd (fneg x), y)
6385  if (N1CFP) {
6386    if (N1CFP->isExactlyValue(1.0))
6387      return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6388
6389    if (N1CFP->isExactlyValue(-1.0) &&
6390        (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6391      SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6392      AddToWorkList(RHSNeg.getNode());
6393      return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6394    }
6395  }
6396
6397  // (fma x, c, x) -> (fmul x, (c+1))
6398  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6399    return DAG.getNode(ISD::FMUL, dl, VT, N0,
6400                       DAG.getNode(ISD::FADD, dl, VT,
6401                                   N1, DAG.getConstantFP(1.0, VT)));
6402
6403  // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6404  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6405      N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6406    return DAG.getNode(ISD::FMUL, dl, VT, N0,
6407                       DAG.getNode(ISD::FADD, dl, VT,
6408                                   N1, DAG.getConstantFP(-1.0, VT)));
6409
6410
6411  return SDValue();
6412}
6413
6414SDValue DAGCombiner::visitFDIV(SDNode *N) {
6415  SDValue N0 = N->getOperand(0);
6416  SDValue N1 = N->getOperand(1);
6417  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6418  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6419  EVT VT = N->getValueType(0);
6420  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6421
6422  // fold vector ops
6423  if (VT.isVector()) {
6424    SDValue FoldedVOp = SimplifyVBinOp(N);
6425    if (FoldedVOp.getNode()) return FoldedVOp;
6426  }
6427
6428  // fold (fdiv c1, c2) -> c1/c2
6429  if (N0CFP && N1CFP)
6430    return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6431
6432  // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6433  if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6434    // Compute the reciprocal 1.0 / c2.
6435    APFloat N1APF = N1CFP->getValueAPF();
6436    APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6437    APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6438    // Only do the transform if the reciprocal is a legal fp immediate that
6439    // isn't too nasty (eg NaN, denormal, ...).
6440    if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6441        (!LegalOperations ||
6442         // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6443         // backend)... we should handle this gracefully after Legalize.
6444         // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6445         TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6446         TLI.isFPImmLegal(Recip, VT)))
6447      return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6448                         DAG.getConstantFP(Recip, VT));
6449  }
6450
6451  // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6452  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6453                                       &DAG.getTarget().Options)) {
6454    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6455                                         &DAG.getTarget().Options)) {
6456      // Both can be negated for free, check to see if at least one is cheaper
6457      // negated.
6458      if (LHSNeg == 2 || RHSNeg == 2)
6459        return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6460                           GetNegatedExpression(N0, DAG, LegalOperations),
6461                           GetNegatedExpression(N1, DAG, LegalOperations));
6462    }
6463  }
6464
6465  return SDValue();
6466}
6467
6468SDValue DAGCombiner::visitFREM(SDNode *N) {
6469  SDValue N0 = N->getOperand(0);
6470  SDValue N1 = N->getOperand(1);
6471  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6472  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6473  EVT VT = N->getValueType(0);
6474
6475  // fold (frem c1, c2) -> fmod(c1,c2)
6476  if (N0CFP && N1CFP)
6477    return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6478
6479  return SDValue();
6480}
6481
6482SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6483  SDValue N0 = N->getOperand(0);
6484  SDValue N1 = N->getOperand(1);
6485  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6486  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6487  EVT VT = N->getValueType(0);
6488
6489  if (N0CFP && N1CFP)  // Constant fold
6490    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6491
6492  if (N1CFP) {
6493    const APFloat& V = N1CFP->getValueAPF();
6494    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6495    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6496    if (!V.isNegative()) {
6497      if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6498        return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6499    } else {
6500      if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6501        return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6502                           DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6503    }
6504  }
6505
6506  // copysign(fabs(x), y) -> copysign(x, y)
6507  // copysign(fneg(x), y) -> copysign(x, y)
6508  // copysign(copysign(x,z), y) -> copysign(x, y)
6509  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6510      N0.getOpcode() == ISD::FCOPYSIGN)
6511    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6512                       N0.getOperand(0), N1);
6513
6514  // copysign(x, abs(y)) -> abs(x)
6515  if (N1.getOpcode() == ISD::FABS)
6516    return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6517
6518  // copysign(x, copysign(y,z)) -> copysign(x, z)
6519  if (N1.getOpcode() == ISD::FCOPYSIGN)
6520    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6521                       N0, N1.getOperand(1));
6522
6523  // copysign(x, fp_extend(y)) -> copysign(x, y)
6524  // copysign(x, fp_round(y)) -> copysign(x, y)
6525  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6526    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6527                       N0, N1.getOperand(0));
6528
6529  return SDValue();
6530}
6531
6532SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6533  SDValue N0 = N->getOperand(0);
6534  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6535  EVT VT = N->getValueType(0);
6536  EVT OpVT = N0.getValueType();
6537
6538  // fold (sint_to_fp c1) -> c1fp
6539  if (N0C &&
6540      // ...but only if the target supports immediate floating-point values
6541      (!LegalOperations ||
6542       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6543    return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6544
6545  // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6546  // but UINT_TO_FP is legal on this target, try to convert.
6547  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6548      TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6549    // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6550    if (DAG.SignBitIsZero(N0))
6551      return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6552  }
6553
6554  // The next optimizations are desireable only if SELECT_CC can be lowered.
6555  // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6556  // having to say they don't support SELECT_CC on every type the DAG knows
6557  // about, since there is no way to mark an opcode illegal at all value types
6558  // (See also visitSELECT)
6559  if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6560    // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6561    if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6562        !VT.isVector() &&
6563        (!LegalOperations ||
6564         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6565      SDValue Ops[] =
6566        { N0.getOperand(0), N0.getOperand(1),
6567          DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6568          N0.getOperand(2) };
6569      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6570    }
6571
6572    // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6573    //      (select_cc x, y, 1.0, 0.0,, cc)
6574    if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6575        N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6576        (!LegalOperations ||
6577         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6578      SDValue Ops[] =
6579        { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6580          DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6581          N0.getOperand(0).getOperand(2) };
6582      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6583    }
6584  }
6585
6586  return SDValue();
6587}
6588
6589SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6590  SDValue N0 = N->getOperand(0);
6591  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6592  EVT VT = N->getValueType(0);
6593  EVT OpVT = N0.getValueType();
6594
6595  // fold (uint_to_fp c1) -> c1fp
6596  if (N0C &&
6597      // ...but only if the target supports immediate floating-point values
6598      (!LegalOperations ||
6599       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6600    return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6601
6602  // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6603  // but SINT_TO_FP is legal on this target, try to convert.
6604  if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6605      TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6606    // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6607    if (DAG.SignBitIsZero(N0))
6608      return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6609  }
6610
6611  // The next optimizations are desireable only if SELECT_CC can be lowered.
6612  // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6613  // having to say they don't support SELECT_CC on every type the DAG knows
6614  // about, since there is no way to mark an opcode illegal at all value types
6615  // (See also visitSELECT)
6616  if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6617    // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6618
6619    if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6620        (!LegalOperations ||
6621         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6622      SDValue Ops[] =
6623        { N0.getOperand(0), N0.getOperand(1),
6624          DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6625          N0.getOperand(2) };
6626      return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6627    }
6628  }
6629
6630  return SDValue();
6631}
6632
6633SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6634  SDValue N0 = N->getOperand(0);
6635  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6636  EVT VT = N->getValueType(0);
6637
6638  // fold (fp_to_sint c1fp) -> c1
6639  if (N0CFP)
6640    return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6641
6642  return SDValue();
6643}
6644
6645SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6646  SDValue N0 = N->getOperand(0);
6647  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6648  EVT VT = N->getValueType(0);
6649
6650  // fold (fp_to_uint c1fp) -> c1
6651  if (N0CFP)
6652    return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6653
6654  return SDValue();
6655}
6656
6657SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6658  SDValue N0 = N->getOperand(0);
6659  SDValue N1 = N->getOperand(1);
6660  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6661  EVT VT = N->getValueType(0);
6662
6663  // fold (fp_round c1fp) -> c1fp
6664  if (N0CFP)
6665    return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6666
6667  // fold (fp_round (fp_extend x)) -> x
6668  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6669    return N0.getOperand(0);
6670
6671  // fold (fp_round (fp_round x)) -> (fp_round x)
6672  if (N0.getOpcode() == ISD::FP_ROUND) {
6673    // This is a value preserving truncation if both round's are.
6674    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6675                   N0.getNode()->getConstantOperandVal(1) == 1;
6676    return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6677                       DAG.getIntPtrConstant(IsTrunc));
6678  }
6679
6680  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6681  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6682    SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6683                              N0.getOperand(0), N1);
6684    AddToWorkList(Tmp.getNode());
6685    return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6686                       Tmp, N0.getOperand(1));
6687  }
6688
6689  return SDValue();
6690}
6691
6692SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6693  SDValue N0 = N->getOperand(0);
6694  EVT VT = N->getValueType(0);
6695  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6696  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6697
6698  // fold (fp_round_inreg c1fp) -> c1fp
6699  if (N0CFP && isTypeLegal(EVT)) {
6700    SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6701    return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6702  }
6703
6704  return SDValue();
6705}
6706
6707SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6708  SDValue N0 = N->getOperand(0);
6709  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6710  EVT VT = N->getValueType(0);
6711
6712  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6713  if (N->hasOneUse() &&
6714      N->use_begin()->getOpcode() == ISD::FP_ROUND)
6715    return SDValue();
6716
6717  // fold (fp_extend c1fp) -> c1fp
6718  if (N0CFP)
6719    return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6720
6721  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6722  // value of X.
6723  if (N0.getOpcode() == ISD::FP_ROUND
6724      && N0.getNode()->getConstantOperandVal(1) == 1) {
6725    SDValue In = N0.getOperand(0);
6726    if (In.getValueType() == VT) return In;
6727    if (VT.bitsLT(In.getValueType()))
6728      return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6729                         In, N0.getOperand(1));
6730    return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6731  }
6732
6733  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6734  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6735      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6736       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6737    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6738    SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6739                                     LN0->getChain(),
6740                                     LN0->getBasePtr(), N0.getValueType(),
6741                                     LN0->getMemOperand());
6742    CombineTo(N, ExtLoad);
6743    CombineTo(N0.getNode(),
6744              DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6745                          N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6746              ExtLoad.getValue(1));
6747    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6748  }
6749
6750  return SDValue();
6751}
6752
6753SDValue DAGCombiner::visitFNEG(SDNode *N) {
6754  SDValue N0 = N->getOperand(0);
6755  EVT VT = N->getValueType(0);
6756
6757  if (VT.isVector()) {
6758    SDValue FoldedVOp = SimplifyVUnaryOp(N);
6759    if (FoldedVOp.getNode()) return FoldedVOp;
6760  }
6761
6762  if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6763                         &DAG.getTarget().Options))
6764    return GetNegatedExpression(N0, DAG, LegalOperations);
6765
6766  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6767  // constant pool values.
6768  if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6769      !VT.isVector() &&
6770      N0.getNode()->hasOneUse() &&
6771      N0.getOperand(0).getValueType().isInteger()) {
6772    SDValue Int = N0.getOperand(0);
6773    EVT IntVT = Int.getValueType();
6774    if (IntVT.isInteger() && !IntVT.isVector()) {
6775      Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6776              DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6777      AddToWorkList(Int.getNode());
6778      return DAG.getNode(ISD::BITCAST, SDLoc(N),
6779                         VT, Int);
6780    }
6781  }
6782
6783  // (fneg (fmul c, x)) -> (fmul -c, x)
6784  if (N0.getOpcode() == ISD::FMUL) {
6785    ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6786    if (CFP1)
6787      return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6788                         N0.getOperand(0),
6789                         DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6790                                     N0.getOperand(1)));
6791  }
6792
6793  return SDValue();
6794}
6795
6796SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6797  SDValue N0 = N->getOperand(0);
6798  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6799  EVT VT = N->getValueType(0);
6800
6801  // fold (fceil c1) -> fceil(c1)
6802  if (N0CFP)
6803    return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6804
6805  return SDValue();
6806}
6807
6808SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6809  SDValue N0 = N->getOperand(0);
6810  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6811  EVT VT = N->getValueType(0);
6812
6813  // fold (ftrunc c1) -> ftrunc(c1)
6814  if (N0CFP)
6815    return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6816
6817  return SDValue();
6818}
6819
6820SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6821  SDValue N0 = N->getOperand(0);
6822  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6823  EVT VT = N->getValueType(0);
6824
6825  // fold (ffloor c1) -> ffloor(c1)
6826  if (N0CFP)
6827    return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6828
6829  return SDValue();
6830}
6831
6832SDValue DAGCombiner::visitFABS(SDNode *N) {
6833  SDValue N0 = N->getOperand(0);
6834  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6835  EVT VT = N->getValueType(0);
6836
6837  if (VT.isVector()) {
6838    SDValue FoldedVOp = SimplifyVUnaryOp(N);
6839    if (FoldedVOp.getNode()) return FoldedVOp;
6840  }
6841
6842  // fold (fabs c1) -> fabs(c1)
6843  if (N0CFP)
6844    return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6845  // fold (fabs (fabs x)) -> (fabs x)
6846  if (N0.getOpcode() == ISD::FABS)
6847    return N->getOperand(0);
6848  // fold (fabs (fneg x)) -> (fabs x)
6849  // fold (fabs (fcopysign x, y)) -> (fabs x)
6850  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6851    return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6852
6853  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6854  // constant pool values.
6855  if (!TLI.isFAbsFree(VT) &&
6856      N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6857      N0.getOperand(0).getValueType().isInteger() &&
6858      !N0.getOperand(0).getValueType().isVector()) {
6859    SDValue Int = N0.getOperand(0);
6860    EVT IntVT = Int.getValueType();
6861    if (IntVT.isInteger() && !IntVT.isVector()) {
6862      Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6863             DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6864      AddToWorkList(Int.getNode());
6865      return DAG.getNode(ISD::BITCAST, SDLoc(N),
6866                         N->getValueType(0), Int);
6867    }
6868  }
6869
6870  return SDValue();
6871}
6872
6873SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6874  SDValue Chain = N->getOperand(0);
6875  SDValue N1 = N->getOperand(1);
6876  SDValue N2 = N->getOperand(2);
6877
6878  // If N is a constant we could fold this into a fallthrough or unconditional
6879  // branch. However that doesn't happen very often in normal code, because
6880  // Instcombine/SimplifyCFG should have handled the available opportunities.
6881  // If we did this folding here, it would be necessary to update the
6882  // MachineBasicBlock CFG, which is awkward.
6883
6884  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6885  // on the target.
6886  if (N1.getOpcode() == ISD::SETCC &&
6887      TLI.isOperationLegalOrCustom(ISD::BR_CC,
6888                                   N1.getOperand(0).getValueType())) {
6889    return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6890                       Chain, N1.getOperand(2),
6891                       N1.getOperand(0), N1.getOperand(1), N2);
6892  }
6893
6894  if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6895      ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6896       (N1.getOperand(0).hasOneUse() &&
6897        N1.getOperand(0).getOpcode() == ISD::SRL))) {
6898    SDNode *Trunc = 0;
6899    if (N1.getOpcode() == ISD::TRUNCATE) {
6900      // Look pass the truncate.
6901      Trunc = N1.getNode();
6902      N1 = N1.getOperand(0);
6903    }
6904
6905    // Match this pattern so that we can generate simpler code:
6906    //
6907    //   %a = ...
6908    //   %b = and i32 %a, 2
6909    //   %c = srl i32 %b, 1
6910    //   brcond i32 %c ...
6911    //
6912    // into
6913    //
6914    //   %a = ...
6915    //   %b = and i32 %a, 2
6916    //   %c = setcc eq %b, 0
6917    //   brcond %c ...
6918    //
6919    // This applies only when the AND constant value has one bit set and the
6920    // SRL constant is equal to the log2 of the AND constant. The back-end is
6921    // smart enough to convert the result into a TEST/JMP sequence.
6922    SDValue Op0 = N1.getOperand(0);
6923    SDValue Op1 = N1.getOperand(1);
6924
6925    if (Op0.getOpcode() == ISD::AND &&
6926        Op1.getOpcode() == ISD::Constant) {
6927      SDValue AndOp1 = Op0.getOperand(1);
6928
6929      if (AndOp1.getOpcode() == ISD::Constant) {
6930        const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6931
6932        if (AndConst.isPowerOf2() &&
6933            cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6934          SDValue SetCC =
6935            DAG.getSetCC(SDLoc(N),
6936                         getSetCCResultType(Op0.getValueType()),
6937                         Op0, DAG.getConstant(0, Op0.getValueType()),
6938                         ISD::SETNE);
6939
6940          SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6941                                          MVT::Other, Chain, SetCC, N2);
6942          // Don't add the new BRCond into the worklist or else SimplifySelectCC
6943          // will convert it back to (X & C1) >> C2.
6944          CombineTo(N, NewBRCond, false);
6945          // Truncate is dead.
6946          if (Trunc) {
6947            removeFromWorkList(Trunc);
6948            DAG.DeleteNode(Trunc);
6949          }
6950          // Replace the uses of SRL with SETCC
6951          WorkListRemover DeadNodes(*this);
6952          DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6953          removeFromWorkList(N1.getNode());
6954          DAG.DeleteNode(N1.getNode());
6955          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6956        }
6957      }
6958    }
6959
6960    if (Trunc)
6961      // Restore N1 if the above transformation doesn't match.
6962      N1 = N->getOperand(1);
6963  }
6964
6965  // Transform br(xor(x, y)) -> br(x != y)
6966  // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6967  if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6968    SDNode *TheXor = N1.getNode();
6969    SDValue Op0 = TheXor->getOperand(0);
6970    SDValue Op1 = TheXor->getOperand(1);
6971    if (Op0.getOpcode() == Op1.getOpcode()) {
6972      // Avoid missing important xor optimizations.
6973      SDValue Tmp = visitXOR(TheXor);
6974      if (Tmp.getNode()) {
6975        if (Tmp.getNode() != TheXor) {
6976          DEBUG(dbgs() << "\nReplacing.8 ";
6977                TheXor->dump(&DAG);
6978                dbgs() << "\nWith: ";
6979                Tmp.getNode()->dump(&DAG);
6980                dbgs() << '\n');
6981          WorkListRemover DeadNodes(*this);
6982          DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6983          removeFromWorkList(TheXor);
6984          DAG.DeleteNode(TheXor);
6985          return DAG.getNode(ISD::BRCOND, SDLoc(N),
6986                             MVT::Other, Chain, Tmp, N2);
6987        }
6988
6989        // visitXOR has changed XOR's operands or replaced the XOR completely,
6990        // bail out.
6991        return SDValue(N, 0);
6992      }
6993    }
6994
6995    if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6996      bool Equal = false;
6997      if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6998        if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6999            Op0.getOpcode() == ISD::XOR) {
7000          TheXor = Op0.getNode();
7001          Equal = true;
7002        }
7003
7004      EVT SetCCVT = N1.getValueType();
7005      if (LegalTypes)
7006        SetCCVT = getSetCCResultType(SetCCVT);
7007      SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7008                                   SetCCVT,
7009                                   Op0, Op1,
7010                                   Equal ? ISD::SETEQ : ISD::SETNE);
7011      // Replace the uses of XOR with SETCC
7012      WorkListRemover DeadNodes(*this);
7013      DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7014      removeFromWorkList(N1.getNode());
7015      DAG.DeleteNode(N1.getNode());
7016      return DAG.getNode(ISD::BRCOND, SDLoc(N),
7017                         MVT::Other, Chain, SetCC, N2);
7018    }
7019  }
7020
7021  return SDValue();
7022}
7023
7024// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7025//
7026SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7027  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7028  SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7029
7030  // If N is a constant we could fold this into a fallthrough or unconditional
7031  // branch. However that doesn't happen very often in normal code, because
7032  // Instcombine/SimplifyCFG should have handled the available opportunities.
7033  // If we did this folding here, it would be necessary to update the
7034  // MachineBasicBlock CFG, which is awkward.
7035
7036  // Use SimplifySetCC to simplify SETCC's.
7037  SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7038                               CondLHS, CondRHS, CC->get(), SDLoc(N),
7039                               false);
7040  if (Simp.getNode()) AddToWorkList(Simp.getNode());
7041
7042  // fold to a simpler setcc
7043  if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7044    return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7045                       N->getOperand(0), Simp.getOperand(2),
7046                       Simp.getOperand(0), Simp.getOperand(1),
7047                       N->getOperand(4));
7048
7049  return SDValue();
7050}
7051
7052/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7053/// uses N as its base pointer and that N may be folded in the load / store
7054/// addressing mode.
7055static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7056                                    SelectionDAG &DAG,
7057                                    const TargetLowering &TLI) {
7058  EVT VT;
7059  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7060    if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7061      return false;
7062    VT = Use->getValueType(0);
7063  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7064    if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7065      return false;
7066    VT = ST->getValue().getValueType();
7067  } else
7068    return false;
7069
7070  TargetLowering::AddrMode AM;
7071  if (N->getOpcode() == ISD::ADD) {
7072    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7073    if (Offset)
7074      // [reg +/- imm]
7075      AM.BaseOffs = Offset->getSExtValue();
7076    else
7077      // [reg +/- reg]
7078      AM.Scale = 1;
7079  } else if (N->getOpcode() == ISD::SUB) {
7080    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7081    if (Offset)
7082      // [reg +/- imm]
7083      AM.BaseOffs = -Offset->getSExtValue();
7084    else
7085      // [reg +/- reg]
7086      AM.Scale = 1;
7087  } else
7088    return false;
7089
7090  return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7091}
7092
7093/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7094/// pre-indexed load / store when the base pointer is an add or subtract
7095/// and it has other uses besides the load / store. After the
7096/// transformation, the new indexed load / store has effectively folded
7097/// the add / subtract in and all of its other uses are redirected to the
7098/// new load / store.
7099bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7100  if (Level < AfterLegalizeDAG)
7101    return false;
7102
7103  bool isLoad = true;
7104  SDValue Ptr;
7105  EVT VT;
7106  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7107    if (LD->isIndexed())
7108      return false;
7109    VT = LD->getMemoryVT();
7110    if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7111        !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7112      return false;
7113    Ptr = LD->getBasePtr();
7114  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7115    if (ST->isIndexed())
7116      return false;
7117    VT = ST->getMemoryVT();
7118    if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7119        !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7120      return false;
7121    Ptr = ST->getBasePtr();
7122    isLoad = false;
7123  } else {
7124    return false;
7125  }
7126
7127  // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7128  // out.  There is no reason to make this a preinc/predec.
7129  if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7130      Ptr.getNode()->hasOneUse())
7131    return false;
7132
7133  // Ask the target to do addressing mode selection.
7134  SDValue BasePtr;
7135  SDValue Offset;
7136  ISD::MemIndexedMode AM = ISD::UNINDEXED;
7137  if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7138    return false;
7139
7140  // Backends without true r+i pre-indexed forms may need to pass a
7141  // constant base with a variable offset so that constant coercion
7142  // will work with the patterns in canonical form.
7143  bool Swapped = false;
7144  if (isa<ConstantSDNode>(BasePtr)) {
7145    std::swap(BasePtr, Offset);
7146    Swapped = true;
7147  }
7148
7149  // Don't create a indexed load / store with zero offset.
7150  if (isa<ConstantSDNode>(Offset) &&
7151      cast<ConstantSDNode>(Offset)->isNullValue())
7152    return false;
7153
7154  // Try turning it into a pre-indexed load / store except when:
7155  // 1) The new base ptr is a frame index.
7156  // 2) If N is a store and the new base ptr is either the same as or is a
7157  //    predecessor of the value being stored.
7158  // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7159  //    that would create a cycle.
7160  // 4) All uses are load / store ops that use it as old base ptr.
7161
7162  // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7163  // (plus the implicit offset) to a register to preinc anyway.
7164  if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7165    return false;
7166
7167  // Check #2.
7168  if (!isLoad) {
7169    SDValue Val = cast<StoreSDNode>(N)->getValue();
7170    if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7171      return false;
7172  }
7173
7174  // If the offset is a constant, there may be other adds of constants that
7175  // can be folded with this one. We should do this to avoid having to keep
7176  // a copy of the original base pointer.
7177  SmallVector<SDNode *, 16> OtherUses;
7178  if (isa<ConstantSDNode>(Offset))
7179    for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7180         E = BasePtr.getNode()->use_end(); I != E; ++I) {
7181      SDNode *Use = *I;
7182      if (Use == Ptr.getNode())
7183        continue;
7184
7185      if (Use->isPredecessorOf(N))
7186        continue;
7187
7188      if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7189        OtherUses.clear();
7190        break;
7191      }
7192
7193      SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7194      if (Op1.getNode() == BasePtr.getNode())
7195        std::swap(Op0, Op1);
7196      assert(Op0.getNode() == BasePtr.getNode() &&
7197             "Use of ADD/SUB but not an operand");
7198
7199      if (!isa<ConstantSDNode>(Op1)) {
7200        OtherUses.clear();
7201        break;
7202      }
7203
7204      // FIXME: In some cases, we can be smarter about this.
7205      if (Op1.getValueType() != Offset.getValueType()) {
7206        OtherUses.clear();
7207        break;
7208      }
7209
7210      OtherUses.push_back(Use);
7211    }
7212
7213  if (Swapped)
7214    std::swap(BasePtr, Offset);
7215
7216  // Now check for #3 and #4.
7217  bool RealUse = false;
7218
7219  // Caches for hasPredecessorHelper
7220  SmallPtrSet<const SDNode *, 32> Visited;
7221  SmallVector<const SDNode *, 16> Worklist;
7222
7223  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7224         E = Ptr.getNode()->use_end(); I != E; ++I) {
7225    SDNode *Use = *I;
7226    if (Use == N)
7227      continue;
7228    if (N->hasPredecessorHelper(Use, Visited, Worklist))
7229      return false;
7230
7231    // If Ptr may be folded in addressing mode of other use, then it's
7232    // not profitable to do this transformation.
7233    if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7234      RealUse = true;
7235  }
7236
7237  if (!RealUse)
7238    return false;
7239
7240  SDValue Result;
7241  if (isLoad)
7242    Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7243                                BasePtr, Offset, AM);
7244  else
7245    Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7246                                 BasePtr, Offset, AM);
7247  ++PreIndexedNodes;
7248  ++NodesCombined;
7249  DEBUG(dbgs() << "\nReplacing.4 ";
7250        N->dump(&DAG);
7251        dbgs() << "\nWith: ";
7252        Result.getNode()->dump(&DAG);
7253        dbgs() << '\n');
7254  WorkListRemover DeadNodes(*this);
7255  if (isLoad) {
7256    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7257    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7258  } else {
7259    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7260  }
7261
7262  // Finally, since the node is now dead, remove it from the graph.
7263  DAG.DeleteNode(N);
7264
7265  if (Swapped)
7266    std::swap(BasePtr, Offset);
7267
7268  // Replace other uses of BasePtr that can be updated to use Ptr
7269  for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7270    unsigned OffsetIdx = 1;
7271    if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7272      OffsetIdx = 0;
7273    assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7274           BasePtr.getNode() && "Expected BasePtr operand");
7275
7276    // We need to replace ptr0 in the following expression:
7277    //   x0 * offset0 + y0 * ptr0 = t0
7278    // knowing that
7279    //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7280    //
7281    // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7282    // indexed load/store and the expresion that needs to be re-written.
7283    //
7284    // Therefore, we have:
7285    //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7286
7287    ConstantSDNode *CN =
7288      cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7289    int X0, X1, Y0, Y1;
7290    APInt Offset0 = CN->getAPIntValue();
7291    APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7292
7293    X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7294    Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7295    X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7296    Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7297
7298    unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7299
7300    APInt CNV = Offset0;
7301    if (X0 < 0) CNV = -CNV;
7302    if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7303    else CNV = CNV - Offset1;
7304
7305    // We can now generate the new expression.
7306    SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7307    SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7308
7309    SDValue NewUse = DAG.getNode(Opcode,
7310                                 SDLoc(OtherUses[i]),
7311                                 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7312    DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7313    removeFromWorkList(OtherUses[i]);
7314    DAG.DeleteNode(OtherUses[i]);
7315  }
7316
7317  // Replace the uses of Ptr with uses of the updated base value.
7318  DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7319  removeFromWorkList(Ptr.getNode());
7320  DAG.DeleteNode(Ptr.getNode());
7321
7322  return true;
7323}
7324
7325/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7326/// add / sub of the base pointer node into a post-indexed load / store.
7327/// The transformation folded the add / subtract into the new indexed
7328/// load / store effectively and all of its uses are redirected to the
7329/// new load / store.
7330bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7331  if (Level < AfterLegalizeDAG)
7332    return false;
7333
7334  bool isLoad = true;
7335  SDValue Ptr;
7336  EVT VT;
7337  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7338    if (LD->isIndexed())
7339      return false;
7340    VT = LD->getMemoryVT();
7341    if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7342        !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7343      return false;
7344    Ptr = LD->getBasePtr();
7345  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7346    if (ST->isIndexed())
7347      return false;
7348    VT = ST->getMemoryVT();
7349    if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7350        !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7351      return false;
7352    Ptr = ST->getBasePtr();
7353    isLoad = false;
7354  } else {
7355    return false;
7356  }
7357
7358  if (Ptr.getNode()->hasOneUse())
7359    return false;
7360
7361  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7362         E = Ptr.getNode()->use_end(); I != E; ++I) {
7363    SDNode *Op = *I;
7364    if (Op == N ||
7365        (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7366      continue;
7367
7368    SDValue BasePtr;
7369    SDValue Offset;
7370    ISD::MemIndexedMode AM = ISD::UNINDEXED;
7371    if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7372      // Don't create a indexed load / store with zero offset.
7373      if (isa<ConstantSDNode>(Offset) &&
7374          cast<ConstantSDNode>(Offset)->isNullValue())
7375        continue;
7376
7377      // Try turning it into a post-indexed load / store except when
7378      // 1) All uses are load / store ops that use it as base ptr (and
7379      //    it may be folded as addressing mmode).
7380      // 2) Op must be independent of N, i.e. Op is neither a predecessor
7381      //    nor a successor of N. Otherwise, if Op is folded that would
7382      //    create a cycle.
7383
7384      if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7385        continue;
7386
7387      // Check for #1.
7388      bool TryNext = false;
7389      for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7390             EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7391        SDNode *Use = *II;
7392        if (Use == Ptr.getNode())
7393          continue;
7394
7395        // If all the uses are load / store addresses, then don't do the
7396        // transformation.
7397        if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7398          bool RealUse = false;
7399          for (SDNode::use_iterator III = Use->use_begin(),
7400                 EEE = Use->use_end(); III != EEE; ++III) {
7401            SDNode *UseUse = *III;
7402            if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7403              RealUse = true;
7404          }
7405
7406          if (!RealUse) {
7407            TryNext = true;
7408            break;
7409          }
7410        }
7411      }
7412
7413      if (TryNext)
7414        continue;
7415
7416      // Check for #2
7417      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7418        SDValue Result = isLoad
7419          ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7420                               BasePtr, Offset, AM)
7421          : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7422                                BasePtr, Offset, AM);
7423        ++PostIndexedNodes;
7424        ++NodesCombined;
7425        DEBUG(dbgs() << "\nReplacing.5 ";
7426              N->dump(&DAG);
7427              dbgs() << "\nWith: ";
7428              Result.getNode()->dump(&DAG);
7429              dbgs() << '\n');
7430        WorkListRemover DeadNodes(*this);
7431        if (isLoad) {
7432          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7433          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7434        } else {
7435          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7436        }
7437
7438        // Finally, since the node is now dead, remove it from the graph.
7439        DAG.DeleteNode(N);
7440
7441        // Replace the uses of Use with uses of the updated base value.
7442        DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7443                                      Result.getValue(isLoad ? 1 : 0));
7444        removeFromWorkList(Op);
7445        DAG.DeleteNode(Op);
7446        return true;
7447      }
7448    }
7449  }
7450
7451  return false;
7452}
7453
7454SDValue DAGCombiner::visitLOAD(SDNode *N) {
7455  LoadSDNode *LD  = cast<LoadSDNode>(N);
7456  SDValue Chain = LD->getChain();
7457  SDValue Ptr   = LD->getBasePtr();
7458
7459  // If load is not volatile and there are no uses of the loaded value (and
7460  // the updated indexed value in case of indexed loads), change uses of the
7461  // chain value into uses of the chain input (i.e. delete the dead load).
7462  if (!LD->isVolatile()) {
7463    if (N->getValueType(1) == MVT::Other) {
7464      // Unindexed loads.
7465      if (!N->hasAnyUseOfValue(0)) {
7466        // It's not safe to use the two value CombineTo variant here. e.g.
7467        // v1, chain2 = load chain1, loc
7468        // v2, chain3 = load chain2, loc
7469        // v3         = add v2, c
7470        // Now we replace use of chain2 with chain1.  This makes the second load
7471        // isomorphic to the one we are deleting, and thus makes this load live.
7472        DEBUG(dbgs() << "\nReplacing.6 ";
7473              N->dump(&DAG);
7474              dbgs() << "\nWith chain: ";
7475              Chain.getNode()->dump(&DAG);
7476              dbgs() << "\n");
7477        WorkListRemover DeadNodes(*this);
7478        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7479
7480        if (N->use_empty()) {
7481          removeFromWorkList(N);
7482          DAG.DeleteNode(N);
7483        }
7484
7485        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7486      }
7487    } else {
7488      // Indexed loads.
7489      assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7490      if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7491        SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7492        DEBUG(dbgs() << "\nReplacing.7 ";
7493              N->dump(&DAG);
7494              dbgs() << "\nWith: ";
7495              Undef.getNode()->dump(&DAG);
7496              dbgs() << " and 2 other values\n");
7497        WorkListRemover DeadNodes(*this);
7498        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7499        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7500                                      DAG.getUNDEF(N->getValueType(1)));
7501        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7502        removeFromWorkList(N);
7503        DAG.DeleteNode(N);
7504        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7505      }
7506    }
7507  }
7508
7509  // If this load is directly stored, replace the load value with the stored
7510  // value.
7511  // TODO: Handle store large -> read small portion.
7512  // TODO: Handle TRUNCSTORE/LOADEXT
7513  if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7514    if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7515      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7516      if (PrevST->getBasePtr() == Ptr &&
7517          PrevST->getValue().getValueType() == N->getValueType(0))
7518      return CombineTo(N, Chain.getOperand(1), Chain);
7519    }
7520  }
7521
7522  // Try to infer better alignment information than the load already has.
7523  if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7524    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7525      if (Align > LD->getMemOperand()->getBaseAlignment()) {
7526        SDValue NewLoad =
7527               DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7528                              LD->getValueType(0),
7529                              Chain, Ptr, LD->getPointerInfo(),
7530                              LD->getMemoryVT(),
7531                              LD->isVolatile(), LD->isNonTemporal(), Align,
7532                              LD->getTBAAInfo());
7533        return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7534      }
7535    }
7536  }
7537
7538  bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7539    TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7540  if (UseAA) {
7541    // Walk up chain skipping non-aliasing memory nodes.
7542    SDValue BetterChain = FindBetterChain(N, Chain);
7543
7544    // If there is a better chain.
7545    if (Chain != BetterChain) {
7546      SDValue ReplLoad;
7547
7548      // Replace the chain to void dependency.
7549      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7550        ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7551                               BetterChain, Ptr, LD->getMemOperand());
7552      } else {
7553        ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7554                                  LD->getValueType(0),
7555                                  BetterChain, Ptr, LD->getMemoryVT(),
7556                                  LD->getMemOperand());
7557      }
7558
7559      // Create token factor to keep old chain connected.
7560      SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7561                                  MVT::Other, Chain, ReplLoad.getValue(1));
7562
7563      // Make sure the new and old chains are cleaned up.
7564      AddToWorkList(Token.getNode());
7565
7566      // Replace uses with load result and token factor. Don't add users
7567      // to work list.
7568      return CombineTo(N, ReplLoad.getValue(0), Token, false);
7569    }
7570  }
7571
7572  // Try transforming N to an indexed load.
7573  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7574    return SDValue(N, 0);
7575
7576  // Try to slice up N to more direct loads if the slices are mapped to
7577  // different register banks or pairing can take place.
7578  if (SliceUpLoad(N))
7579    return SDValue(N, 0);
7580
7581  return SDValue();
7582}
7583
7584namespace {
7585/// \brief Helper structure used to slice a load in smaller loads.
7586/// Basically a slice is obtained from the following sequence:
7587/// Origin = load Ty1, Base
7588/// Shift = srl Ty1 Origin, CstTy Amount
7589/// Inst = trunc Shift to Ty2
7590///
7591/// Then, it will be rewriten into:
7592/// Slice = load SliceTy, Base + SliceOffset
7593/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7594///
7595/// SliceTy is deduced from the number of bits that are actually used to
7596/// build Inst.
7597struct LoadedSlice {
7598  /// \brief Helper structure used to compute the cost of a slice.
7599  struct Cost {
7600    /// Are we optimizing for code size.
7601    bool ForCodeSize;
7602    /// Various cost.
7603    unsigned Loads;
7604    unsigned Truncates;
7605    unsigned CrossRegisterBanksCopies;
7606    unsigned ZExts;
7607    unsigned Shift;
7608
7609    Cost(bool ForCodeSize = false)
7610        : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7611          CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7612
7613    /// \brief Get the cost of one isolated slice.
7614    Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7615        : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7616          CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7617      EVT TruncType = LS.Inst->getValueType(0);
7618      EVT LoadedType = LS.getLoadedType();
7619      if (TruncType != LoadedType &&
7620          !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7621        ZExts = 1;
7622    }
7623
7624    /// \brief Account for slicing gain in the current cost.
7625    /// Slicing provide a few gains like removing a shift or a
7626    /// truncate. This method allows to grow the cost of the original
7627    /// load with the gain from this slice.
7628    void addSliceGain(const LoadedSlice &LS) {
7629      // Each slice saves a truncate.
7630      const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7631      if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7632                              LS.Inst->getOperand(0).getValueType()))
7633        ++Truncates;
7634      // If there is a shift amount, this slice gets rid of it.
7635      if (LS.Shift)
7636        ++Shift;
7637      // If this slice can merge a cross register bank copy, account for it.
7638      if (LS.canMergeExpensiveCrossRegisterBankCopy())
7639        ++CrossRegisterBanksCopies;
7640    }
7641
7642    Cost &operator+=(const Cost &RHS) {
7643      Loads += RHS.Loads;
7644      Truncates += RHS.Truncates;
7645      CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7646      ZExts += RHS.ZExts;
7647      Shift += RHS.Shift;
7648      return *this;
7649    }
7650
7651    bool operator==(const Cost &RHS) const {
7652      return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7653             CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7654             ZExts == RHS.ZExts && Shift == RHS.Shift;
7655    }
7656
7657    bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7658
7659    bool operator<(const Cost &RHS) const {
7660      // Assume cross register banks copies are as expensive as loads.
7661      // FIXME: Do we want some more target hooks?
7662      unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7663      unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7664      // Unless we are optimizing for code size, consider the
7665      // expensive operation first.
7666      if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7667        return ExpensiveOpsLHS < ExpensiveOpsRHS;
7668      return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7669             (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7670    }
7671
7672    bool operator>(const Cost &RHS) const { return RHS < *this; }
7673
7674    bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7675
7676    bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7677  };
7678  // The last instruction that represent the slice. This should be a
7679  // truncate instruction.
7680  SDNode *Inst;
7681  // The original load instruction.
7682  LoadSDNode *Origin;
7683  // The right shift amount in bits from the original load.
7684  unsigned Shift;
7685  // The DAG from which Origin came from.
7686  // This is used to get some contextual information about legal types, etc.
7687  SelectionDAG *DAG;
7688
7689  LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7690              unsigned Shift = 0, SelectionDAG *DAG = NULL)
7691      : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7692
7693  LoadedSlice(const LoadedSlice &LS)
7694      : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7695
7696  /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7697  /// \return Result is \p BitWidth and has used bits set to 1 and
7698  ///         not used bits set to 0.
7699  APInt getUsedBits() const {
7700    // Reproduce the trunc(lshr) sequence:
7701    // - Start from the truncated value.
7702    // - Zero extend to the desired bit width.
7703    // - Shift left.
7704    assert(Origin && "No original load to compare against.");
7705    unsigned BitWidth = Origin->getValueSizeInBits(0);
7706    assert(Inst && "This slice is not bound to an instruction");
7707    assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7708           "Extracted slice is bigger than the whole type!");
7709    APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7710    UsedBits.setAllBits();
7711    UsedBits = UsedBits.zext(BitWidth);
7712    UsedBits <<= Shift;
7713    return UsedBits;
7714  }
7715
7716  /// \brief Get the size of the slice to be loaded in bytes.
7717  unsigned getLoadedSize() const {
7718    unsigned SliceSize = getUsedBits().countPopulation();
7719    assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7720    return SliceSize / 8;
7721  }
7722
7723  /// \brief Get the type that will be loaded for this slice.
7724  /// Note: This may not be the final type for the slice.
7725  EVT getLoadedType() const {
7726    assert(DAG && "Missing context");
7727    LLVMContext &Ctxt = *DAG->getContext();
7728    return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7729  }
7730
7731  /// \brief Get the alignment of the load used for this slice.
7732  unsigned getAlignment() const {
7733    unsigned Alignment = Origin->getAlignment();
7734    unsigned Offset = getOffsetFromBase();
7735    if (Offset != 0)
7736      Alignment = MinAlign(Alignment, Alignment + Offset);
7737    return Alignment;
7738  }
7739
7740  /// \brief Check if this slice can be rewritten with legal operations.
7741  bool isLegal() const {
7742    // An invalid slice is not legal.
7743    if (!Origin || !Inst || !DAG)
7744      return false;
7745
7746    // Offsets are for indexed load only, we do not handle that.
7747    if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7748      return false;
7749
7750    const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7751
7752    // Check that the type is legal.
7753    EVT SliceType = getLoadedType();
7754    if (!TLI.isTypeLegal(SliceType))
7755      return false;
7756
7757    // Check that the load is legal for this type.
7758    if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7759      return false;
7760
7761    // Check that the offset can be computed.
7762    // 1. Check its type.
7763    EVT PtrType = Origin->getBasePtr().getValueType();
7764    if (PtrType == MVT::Untyped || PtrType.isExtended())
7765      return false;
7766
7767    // 2. Check that it fits in the immediate.
7768    if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7769      return false;
7770
7771    // 3. Check that the computation is legal.
7772    if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7773      return false;
7774
7775    // Check that the zext is legal if it needs one.
7776    EVT TruncateType = Inst->getValueType(0);
7777    if (TruncateType != SliceType &&
7778        !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7779      return false;
7780
7781    return true;
7782  }
7783
7784  /// \brief Get the offset in bytes of this slice in the original chunk of
7785  /// bits.
7786  /// \pre DAG != NULL.
7787  uint64_t getOffsetFromBase() const {
7788    assert(DAG && "Missing context.");
7789    bool IsBigEndian =
7790        DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7791    assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7792    uint64_t Offset = Shift / 8;
7793    unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7794    assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7795           "The size of the original loaded type is not a multiple of a"
7796           " byte.");
7797    // If Offset is bigger than TySizeInBytes, it means we are loading all
7798    // zeros. This should have been optimized before in the process.
7799    assert(TySizeInBytes > Offset &&
7800           "Invalid shift amount for given loaded size");
7801    if (IsBigEndian)
7802      Offset = TySizeInBytes - Offset - getLoadedSize();
7803    return Offset;
7804  }
7805
7806  /// \brief Generate the sequence of instructions to load the slice
7807  /// represented by this object and redirect the uses of this slice to
7808  /// this new sequence of instructions.
7809  /// \pre this->Inst && this->Origin are valid Instructions and this
7810  /// object passed the legal check: LoadedSlice::isLegal returned true.
7811  /// \return The last instruction of the sequence used to load the slice.
7812  SDValue loadSlice() const {
7813    assert(Inst && Origin && "Unable to replace a non-existing slice.");
7814    const SDValue &OldBaseAddr = Origin->getBasePtr();
7815    SDValue BaseAddr = OldBaseAddr;
7816    // Get the offset in that chunk of bytes w.r.t. the endianess.
7817    int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7818    assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7819    if (Offset) {
7820      // BaseAddr = BaseAddr + Offset.
7821      EVT ArithType = BaseAddr.getValueType();
7822      BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7823                              DAG->getConstant(Offset, ArithType));
7824    }
7825
7826    // Create the type of the loaded slice according to its size.
7827    EVT SliceType = getLoadedType();
7828
7829    // Create the load for the slice.
7830    SDValue LastInst = DAG->getLoad(
7831        SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7832        Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7833        Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7834    // If the final type is not the same as the loaded type, this means that
7835    // we have to pad with zero. Create a zero extend for that.
7836    EVT FinalType = Inst->getValueType(0);
7837    if (SliceType != FinalType)
7838      LastInst =
7839          DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7840    return LastInst;
7841  }
7842
7843  /// \brief Check if this slice can be merged with an expensive cross register
7844  /// bank copy. E.g.,
7845  /// i = load i32
7846  /// f = bitcast i32 i to float
7847  bool canMergeExpensiveCrossRegisterBankCopy() const {
7848    if (!Inst || !Inst->hasOneUse())
7849      return false;
7850    SDNode *Use = *Inst->use_begin();
7851    if (Use->getOpcode() != ISD::BITCAST)
7852      return false;
7853    assert(DAG && "Missing context");
7854    const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7855    EVT ResVT = Use->getValueType(0);
7856    const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7857    const TargetRegisterClass *ArgRC =
7858        TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7859    if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7860      return false;
7861
7862    // At this point, we know that we perform a cross-register-bank copy.
7863    // Check if it is expensive.
7864    const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7865    // Assume bitcasts are cheap, unless both register classes do not
7866    // explicitly share a common sub class.
7867    if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7868      return false;
7869
7870    // Check if it will be merged with the load.
7871    // 1. Check the alignment constraint.
7872    unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7873        ResVT.getTypeForEVT(*DAG->getContext()));
7874
7875    if (RequiredAlignment > getAlignment())
7876      return false;
7877
7878    // 2. Check that the load is a legal operation for that type.
7879    if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7880      return false;
7881
7882    // 3. Check that we do not have a zext in the way.
7883    if (Inst->getValueType(0) != getLoadedType())
7884      return false;
7885
7886    return true;
7887  }
7888};
7889}
7890
7891/// \brief Sorts LoadedSlice according to their offset.
7892struct LoadedSliceSorter {
7893  bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7894    assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7895    return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7896  }
7897};
7898
7899/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7900/// \p UsedBits looks like 0..0 1..1 0..0.
7901static bool areUsedBitsDense(const APInt &UsedBits) {
7902  // If all the bits are one, this is dense!
7903  if (UsedBits.isAllOnesValue())
7904    return true;
7905
7906  // Get rid of the unused bits on the right.
7907  APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7908  // Get rid of the unused bits on the left.
7909  if (NarrowedUsedBits.countLeadingZeros())
7910    NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7911  // Check that the chunk of bits is completely used.
7912  return NarrowedUsedBits.isAllOnesValue();
7913}
7914
7915/// \brief Check whether or not \p First and \p Second are next to each other
7916/// in memory. This means that there is no hole between the bits loaded
7917/// by \p First and the bits loaded by \p Second.
7918static bool areSlicesNextToEachOther(const LoadedSlice &First,
7919                                     const LoadedSlice &Second) {
7920  assert(First.Origin == Second.Origin && First.Origin &&
7921         "Unable to match different memory origins.");
7922  APInt UsedBits = First.getUsedBits();
7923  assert((UsedBits & Second.getUsedBits()) == 0 &&
7924         "Slices are not supposed to overlap.");
7925  UsedBits |= Second.getUsedBits();
7926  return areUsedBitsDense(UsedBits);
7927}
7928
7929/// \brief Adjust the \p GlobalLSCost according to the target
7930/// paring capabilities and the layout of the slices.
7931/// \pre \p GlobalLSCost should account for at least as many loads as
7932/// there is in the slices in \p LoadedSlices.
7933static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7934                                 LoadedSlice::Cost &GlobalLSCost) {
7935  unsigned NumberOfSlices = LoadedSlices.size();
7936  // If there is less than 2 elements, no pairing is possible.
7937  if (NumberOfSlices < 2)
7938    return;
7939
7940  // Sort the slices so that elements that are likely to be next to each
7941  // other in memory are next to each other in the list.
7942  std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
7943  const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
7944  // First (resp. Second) is the first (resp. Second) potentially candidate
7945  // to be placed in a paired load.
7946  const LoadedSlice *First = NULL;
7947  const LoadedSlice *Second = NULL;
7948  for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
7949                // Set the beginning of the pair.
7950                                                           First = Second) {
7951
7952    Second = &LoadedSlices[CurrSlice];
7953
7954    // If First is NULL, it means we start a new pair.
7955    // Get to the next slice.
7956    if (!First)
7957      continue;
7958
7959    EVT LoadedType = First->getLoadedType();
7960
7961    // If the types of the slices are different, we cannot pair them.
7962    if (LoadedType != Second->getLoadedType())
7963      continue;
7964
7965    // Check if the target supplies paired loads for this type.
7966    unsigned RequiredAlignment = 0;
7967    if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
7968      // move to the next pair, this type is hopeless.
7969      Second = NULL;
7970      continue;
7971    }
7972    // Check if we meet the alignment requirement.
7973    if (RequiredAlignment > First->getAlignment())
7974      continue;
7975
7976    // Check that both loads are next to each other in memory.
7977    if (!areSlicesNextToEachOther(*First, *Second))
7978      continue;
7979
7980    assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
7981    --GlobalLSCost.Loads;
7982    // Move to the next pair.
7983    Second = NULL;
7984  }
7985}
7986
7987/// \brief Check the profitability of all involved LoadedSlice.
7988/// Currently, it is considered profitable if there is exactly two
7989/// involved slices (1) which are (2) next to each other in memory, and
7990/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
7991///
7992/// Note: The order of the elements in \p LoadedSlices may be modified, but not
7993/// the elements themselves.
7994///
7995/// FIXME: When the cost model will be mature enough, we can relax
7996/// constraints (1) and (2).
7997static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7998                                const APInt &UsedBits, bool ForCodeSize) {
7999  unsigned NumberOfSlices = LoadedSlices.size();
8000  if (StressLoadSlicing)
8001    return NumberOfSlices > 1;
8002
8003  // Check (1).
8004  if (NumberOfSlices != 2)
8005    return false;
8006
8007  // Check (2).
8008  if (!areUsedBitsDense(UsedBits))
8009    return false;
8010
8011  // Check (3).
8012  LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8013  // The original code has one big load.
8014  OrigCost.Loads = 1;
8015  for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8016    const LoadedSlice &LS = LoadedSlices[CurrSlice];
8017    // Accumulate the cost of all the slices.
8018    LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8019    GlobalSlicingCost += SliceCost;
8020
8021    // Account as cost in the original configuration the gain obtained
8022    // with the current slices.
8023    OrigCost.addSliceGain(LS);
8024  }
8025
8026  // If the target supports paired load, adjust the cost accordingly.
8027  adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8028  return OrigCost > GlobalSlicingCost;
8029}
8030
8031/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8032/// operations, split it in the various pieces being extracted.
8033///
8034/// This sort of thing is introduced by SROA.
8035/// This slicing takes care not to insert overlapping loads.
8036/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8037bool DAGCombiner::SliceUpLoad(SDNode *N) {
8038  if (Level < AfterLegalizeDAG)
8039    return false;
8040
8041  LoadSDNode *LD = cast<LoadSDNode>(N);
8042  if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8043      !LD->getValueType(0).isInteger())
8044    return false;
8045
8046  // Keep track of already used bits to detect overlapping values.
8047  // In that case, we will just abort the transformation.
8048  APInt UsedBits(LD->getValueSizeInBits(0), 0);
8049
8050  SmallVector<LoadedSlice, 4> LoadedSlices;
8051
8052  // Check if this load is used as several smaller chunks of bits.
8053  // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8054  // of computation for each trunc.
8055  for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8056       UI != UIEnd; ++UI) {
8057    // Skip the uses of the chain.
8058    if (UI.getUse().getResNo() != 0)
8059      continue;
8060
8061    SDNode *User = *UI;
8062    unsigned Shift = 0;
8063
8064    // Check if this is a trunc(lshr).
8065    if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8066        isa<ConstantSDNode>(User->getOperand(1))) {
8067      Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8068      User = *User->use_begin();
8069    }
8070
8071    // At this point, User is a Truncate, iff we encountered, trunc or
8072    // trunc(lshr).
8073    if (User->getOpcode() != ISD::TRUNCATE)
8074      return false;
8075
8076    // The width of the type must be a power of 2 and greater than 8-bits.
8077    // Otherwise the load cannot be represented in LLVM IR.
8078    // Moreover, if we shifted with a non 8-bits multiple, the slice
8079    // will be accross several bytes. We do not support that.
8080    unsigned Width = User->getValueSizeInBits(0);
8081    if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8082      return 0;
8083
8084    // Build the slice for this chain of computations.
8085    LoadedSlice LS(User, LD, Shift, &DAG);
8086    APInt CurrentUsedBits = LS.getUsedBits();
8087
8088    // Check if this slice overlaps with another.
8089    if ((CurrentUsedBits & UsedBits) != 0)
8090      return false;
8091    // Update the bits used globally.
8092    UsedBits |= CurrentUsedBits;
8093
8094    // Check if the new slice would be legal.
8095    if (!LS.isLegal())
8096      return false;
8097
8098    // Record the slice.
8099    LoadedSlices.push_back(LS);
8100  }
8101
8102  // Abort slicing if it does not seem to be profitable.
8103  if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8104    return false;
8105
8106  ++SlicedLoads;
8107
8108  // Rewrite each chain to use an independent load.
8109  // By construction, each chain can be represented by a unique load.
8110
8111  // Prepare the argument for the new token factor for all the slices.
8112  SmallVector<SDValue, 8> ArgChains;
8113  for (SmallVectorImpl<LoadedSlice>::const_iterator
8114           LSIt = LoadedSlices.begin(),
8115           LSItEnd = LoadedSlices.end();
8116       LSIt != LSItEnd; ++LSIt) {
8117    SDValue SliceInst = LSIt->loadSlice();
8118    CombineTo(LSIt->Inst, SliceInst, true);
8119    if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8120      SliceInst = SliceInst.getOperand(0);
8121    assert(SliceInst->getOpcode() == ISD::LOAD &&
8122           "It takes more than a zext to get to the loaded slice!!");
8123    ArgChains.push_back(SliceInst.getValue(1));
8124  }
8125
8126  SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8127                              &ArgChains[0], ArgChains.size());
8128  DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8129  return true;
8130}
8131
8132/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8133/// load is having specific bytes cleared out.  If so, return the byte size
8134/// being masked out and the shift amount.
8135static std::pair<unsigned, unsigned>
8136CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8137  std::pair<unsigned, unsigned> Result(0, 0);
8138
8139  // Check for the structure we're looking for.
8140  if (V->getOpcode() != ISD::AND ||
8141      !isa<ConstantSDNode>(V->getOperand(1)) ||
8142      !ISD::isNormalLoad(V->getOperand(0).getNode()))
8143    return Result;
8144
8145  // Check the chain and pointer.
8146  LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8147  if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8148
8149  // The store should be chained directly to the load or be an operand of a
8150  // tokenfactor.
8151  if (LD == Chain.getNode())
8152    ; // ok.
8153  else if (Chain->getOpcode() != ISD::TokenFactor)
8154    return Result; // Fail.
8155  else {
8156    bool isOk = false;
8157    for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8158      if (Chain->getOperand(i).getNode() == LD) {
8159        isOk = true;
8160        break;
8161      }
8162    if (!isOk) return Result;
8163  }
8164
8165  // This only handles simple types.
8166  if (V.getValueType() != MVT::i16 &&
8167      V.getValueType() != MVT::i32 &&
8168      V.getValueType() != MVT::i64)
8169    return Result;
8170
8171  // Check the constant mask.  Invert it so that the bits being masked out are
8172  // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8173  // follow the sign bit for uniformity.
8174  uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8175  unsigned NotMaskLZ = countLeadingZeros(NotMask);
8176  if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8177  unsigned NotMaskTZ = countTrailingZeros(NotMask);
8178  if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8179  if (NotMaskLZ == 64) return Result;  // All zero mask.
8180
8181  // See if we have a continuous run of bits.  If so, we have 0*1+0*
8182  if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8183    return Result;
8184
8185  // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8186  if (V.getValueType() != MVT::i64 && NotMaskLZ)
8187    NotMaskLZ -= 64-V.getValueSizeInBits();
8188
8189  unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8190  switch (MaskedBytes) {
8191  case 1:
8192  case 2:
8193  case 4: break;
8194  default: return Result; // All one mask, or 5-byte mask.
8195  }
8196
8197  // Verify that the first bit starts at a multiple of mask so that the access
8198  // is aligned the same as the access width.
8199  if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8200
8201  Result.first = MaskedBytes;
8202  Result.second = NotMaskTZ/8;
8203  return Result;
8204}
8205
8206
8207/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8208/// provides a value as specified by MaskInfo.  If so, replace the specified
8209/// store with a narrower store of truncated IVal.
8210static SDNode *
8211ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8212                                SDValue IVal, StoreSDNode *St,
8213                                DAGCombiner *DC) {
8214  unsigned NumBytes = MaskInfo.first;
8215  unsigned ByteShift = MaskInfo.second;
8216  SelectionDAG &DAG = DC->getDAG();
8217
8218  // Check to see if IVal is all zeros in the part being masked in by the 'or'
8219  // that uses this.  If not, this is not a replacement.
8220  APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8221                                  ByteShift*8, (ByteShift+NumBytes)*8);
8222  if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8223
8224  // Check that it is legal on the target to do this.  It is legal if the new
8225  // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8226  // legalization.
8227  MVT VT = MVT::getIntegerVT(NumBytes*8);
8228  if (!DC->isTypeLegal(VT))
8229    return 0;
8230
8231  // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8232  // shifted by ByteShift and truncated down to NumBytes.
8233  if (ByteShift)
8234    IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8235                       DAG.getConstant(ByteShift*8,
8236                                    DC->getShiftAmountTy(IVal.getValueType())));
8237
8238  // Figure out the offset for the store and the alignment of the access.
8239  unsigned StOffset;
8240  unsigned NewAlign = St->getAlignment();
8241
8242  if (DAG.getTargetLoweringInfo().isLittleEndian())
8243    StOffset = ByteShift;
8244  else
8245    StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8246
8247  SDValue Ptr = St->getBasePtr();
8248  if (StOffset) {
8249    Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8250                      Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8251    NewAlign = MinAlign(NewAlign, StOffset);
8252  }
8253
8254  // Truncate down to the new size.
8255  IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8256
8257  ++OpsNarrowed;
8258  return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8259                      St->getPointerInfo().getWithOffset(StOffset),
8260                      false, false, NewAlign).getNode();
8261}
8262
8263
8264/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8265/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8266/// of the loaded bits, try narrowing the load and store if it would end up
8267/// being a win for performance or code size.
8268SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8269  StoreSDNode *ST  = cast<StoreSDNode>(N);
8270  if (ST->isVolatile())
8271    return SDValue();
8272
8273  SDValue Chain = ST->getChain();
8274  SDValue Value = ST->getValue();
8275  SDValue Ptr   = ST->getBasePtr();
8276  EVT VT = Value.getValueType();
8277
8278  if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8279    return SDValue();
8280
8281  unsigned Opc = Value.getOpcode();
8282
8283  // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8284  // is a byte mask indicating a consecutive number of bytes, check to see if
8285  // Y is known to provide just those bytes.  If so, we try to replace the
8286  // load + replace + store sequence with a single (narrower) store, which makes
8287  // the load dead.
8288  if (Opc == ISD::OR) {
8289    std::pair<unsigned, unsigned> MaskedLoad;
8290    MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8291    if (MaskedLoad.first)
8292      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8293                                                  Value.getOperand(1), ST,this))
8294        return SDValue(NewST, 0);
8295
8296    // Or is commutative, so try swapping X and Y.
8297    MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8298    if (MaskedLoad.first)
8299      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8300                                                  Value.getOperand(0), ST,this))
8301        return SDValue(NewST, 0);
8302  }
8303
8304  if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8305      Value.getOperand(1).getOpcode() != ISD::Constant)
8306    return SDValue();
8307
8308  SDValue N0 = Value.getOperand(0);
8309  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8310      Chain == SDValue(N0.getNode(), 1)) {
8311    LoadSDNode *LD = cast<LoadSDNode>(N0);
8312    if (LD->getBasePtr() != Ptr ||
8313        LD->getPointerInfo().getAddrSpace() !=
8314        ST->getPointerInfo().getAddrSpace())
8315      return SDValue();
8316
8317    // Find the type to narrow it the load / op / store to.
8318    SDValue N1 = Value.getOperand(1);
8319    unsigned BitWidth = N1.getValueSizeInBits();
8320    APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8321    if (Opc == ISD::AND)
8322      Imm ^= APInt::getAllOnesValue(BitWidth);
8323    if (Imm == 0 || Imm.isAllOnesValue())
8324      return SDValue();
8325    unsigned ShAmt = Imm.countTrailingZeros();
8326    unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8327    unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8328    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8329    while (NewBW < BitWidth &&
8330           !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8331             TLI.isNarrowingProfitable(VT, NewVT))) {
8332      NewBW = NextPowerOf2(NewBW);
8333      NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8334    }
8335    if (NewBW >= BitWidth)
8336      return SDValue();
8337
8338    // If the lsb changed does not start at the type bitwidth boundary,
8339    // start at the previous one.
8340    if (ShAmt % NewBW)
8341      ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8342    APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8343                                   std::min(BitWidth, ShAmt + NewBW));
8344    if ((Imm & Mask) == Imm) {
8345      APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8346      if (Opc == ISD::AND)
8347        NewImm ^= APInt::getAllOnesValue(NewBW);
8348      uint64_t PtrOff = ShAmt / 8;
8349      // For big endian targets, we need to adjust the offset to the pointer to
8350      // load the correct bytes.
8351      if (TLI.isBigEndian())
8352        PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8353
8354      unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8355      Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8356      if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8357        return SDValue();
8358
8359      SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8360                                   Ptr.getValueType(), Ptr,
8361                                   DAG.getConstant(PtrOff, Ptr.getValueType()));
8362      SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8363                                  LD->getChain(), NewPtr,
8364                                  LD->getPointerInfo().getWithOffset(PtrOff),
8365                                  LD->isVolatile(), LD->isNonTemporal(),
8366                                  LD->isInvariant(), NewAlign,
8367                                  LD->getTBAAInfo());
8368      SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8369                                   DAG.getConstant(NewImm, NewVT));
8370      SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8371                                   NewVal, NewPtr,
8372                                   ST->getPointerInfo().getWithOffset(PtrOff),
8373                                   false, false, NewAlign);
8374
8375      AddToWorkList(NewPtr.getNode());
8376      AddToWorkList(NewLD.getNode());
8377      AddToWorkList(NewVal.getNode());
8378      WorkListRemover DeadNodes(*this);
8379      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8380      ++OpsNarrowed;
8381      return NewST;
8382    }
8383  }
8384
8385  return SDValue();
8386}
8387
8388/// TransformFPLoadStorePair - For a given floating point load / store pair,
8389/// if the load value isn't used by any other operations, then consider
8390/// transforming the pair to integer load / store operations if the target
8391/// deems the transformation profitable.
8392SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8393  StoreSDNode *ST  = cast<StoreSDNode>(N);
8394  SDValue Chain = ST->getChain();
8395  SDValue Value = ST->getValue();
8396  if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8397      Value.hasOneUse() &&
8398      Chain == SDValue(Value.getNode(), 1)) {
8399    LoadSDNode *LD = cast<LoadSDNode>(Value);
8400    EVT VT = LD->getMemoryVT();
8401    if (!VT.isFloatingPoint() ||
8402        VT != ST->getMemoryVT() ||
8403        LD->isNonTemporal() ||
8404        ST->isNonTemporal() ||
8405        LD->getPointerInfo().getAddrSpace() != 0 ||
8406        ST->getPointerInfo().getAddrSpace() != 0)
8407      return SDValue();
8408
8409    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8410    if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8411        !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8412        !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8413        !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8414      return SDValue();
8415
8416    unsigned LDAlign = LD->getAlignment();
8417    unsigned STAlign = ST->getAlignment();
8418    Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8419    unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8420    if (LDAlign < ABIAlign || STAlign < ABIAlign)
8421      return SDValue();
8422
8423    SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8424                                LD->getChain(), LD->getBasePtr(),
8425                                LD->getPointerInfo(),
8426                                false, false, false, LDAlign);
8427
8428    SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8429                                 NewLD, ST->getBasePtr(),
8430                                 ST->getPointerInfo(),
8431                                 false, false, STAlign);
8432
8433    AddToWorkList(NewLD.getNode());
8434    AddToWorkList(NewST.getNode());
8435    WorkListRemover DeadNodes(*this);
8436    DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8437    ++LdStFP2Int;
8438    return NewST;
8439  }
8440
8441  return SDValue();
8442}
8443
8444/// Helper struct to parse and store a memory address as base + index + offset.
8445/// We ignore sign extensions when it is safe to do so.
8446/// The following two expressions are not equivalent. To differentiate we need
8447/// to store whether there was a sign extension involved in the index
8448/// computation.
8449///  (load (i64 add (i64 copyfromreg %c)
8450///                 (i64 signextend (add (i8 load %index)
8451///                                      (i8 1))))
8452/// vs
8453///
8454/// (load (i64 add (i64 copyfromreg %c)
8455///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8456///                                         (i32 1)))))
8457struct BaseIndexOffset {
8458  SDValue Base;
8459  SDValue Index;
8460  int64_t Offset;
8461  bool IsIndexSignExt;
8462
8463  BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8464
8465  BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8466                  bool IsIndexSignExt) :
8467    Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8468
8469  bool equalBaseIndex(const BaseIndexOffset &Other) {
8470    return Other.Base == Base && Other.Index == Index &&
8471      Other.IsIndexSignExt == IsIndexSignExt;
8472  }
8473
8474  /// Parses tree in Ptr for base, index, offset addresses.
8475  static BaseIndexOffset match(SDValue Ptr) {
8476    bool IsIndexSignExt = false;
8477
8478    // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8479    // instruction, then it could be just the BASE or everything else we don't
8480    // know how to handle. Just use Ptr as BASE and give up.
8481    if (Ptr->getOpcode() != ISD::ADD)
8482      return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8483
8484    // We know that we have at least an ADD instruction. Try to pattern match
8485    // the simple case of BASE + OFFSET.
8486    if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8487      int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8488      return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8489                              IsIndexSignExt);
8490    }
8491
8492    // Inside a loop the current BASE pointer is calculated using an ADD and a
8493    // MUL instruction. In this case Ptr is the actual BASE pointer.
8494    // (i64 add (i64 %array_ptr)
8495    //          (i64 mul (i64 %induction_var)
8496    //                   (i64 %element_size)))
8497    if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8498      return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8499
8500    // Look at Base + Index + Offset cases.
8501    SDValue Base = Ptr->getOperand(0);
8502    SDValue IndexOffset = Ptr->getOperand(1);
8503
8504    // Skip signextends.
8505    if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8506      IndexOffset = IndexOffset->getOperand(0);
8507      IsIndexSignExt = true;
8508    }
8509
8510    // Either the case of Base + Index (no offset) or something else.
8511    if (IndexOffset->getOpcode() != ISD::ADD)
8512      return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8513
8514    // Now we have the case of Base + Index + offset.
8515    SDValue Index = IndexOffset->getOperand(0);
8516    SDValue Offset = IndexOffset->getOperand(1);
8517
8518    if (!isa<ConstantSDNode>(Offset))
8519      return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8520
8521    // Ignore signextends.
8522    if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8523      Index = Index->getOperand(0);
8524      IsIndexSignExt = true;
8525    } else IsIndexSignExt = false;
8526
8527    int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8528    return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8529  }
8530};
8531
8532/// Holds a pointer to an LSBaseSDNode as well as information on where it
8533/// is located in a sequence of memory operations connected by a chain.
8534struct MemOpLink {
8535  MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8536    MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8537  // Ptr to the mem node.
8538  LSBaseSDNode *MemNode;
8539  // Offset from the base ptr.
8540  int64_t OffsetFromBase;
8541  // What is the sequence number of this mem node.
8542  // Lowest mem operand in the DAG starts at zero.
8543  unsigned SequenceNum;
8544};
8545
8546/// Sorts store nodes in a link according to their offset from a shared
8547// base ptr.
8548struct ConsecutiveMemoryChainSorter {
8549  bool operator()(MemOpLink LHS, MemOpLink RHS) {
8550    return LHS.OffsetFromBase < RHS.OffsetFromBase;
8551  }
8552};
8553
8554bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8555  EVT MemVT = St->getMemoryVT();
8556  int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8557  bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8558    hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8559
8560  // Don't merge vectors into wider inputs.
8561  if (MemVT.isVector() || !MemVT.isSimple())
8562    return false;
8563
8564  // Perform an early exit check. Do not bother looking at stored values that
8565  // are not constants or loads.
8566  SDValue StoredVal = St->getValue();
8567  bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8568  if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8569      !IsLoadSrc)
8570    return false;
8571
8572  // Only look at ends of store sequences.
8573  SDValue Chain = SDValue(St, 1);
8574  if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8575    return false;
8576
8577  // This holds the base pointer, index, and the offset in bytes from the base
8578  // pointer.
8579  BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8580
8581  // We must have a base and an offset.
8582  if (!BasePtr.Base.getNode())
8583    return false;
8584
8585  // Do not handle stores to undef base pointers.
8586  if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8587    return false;
8588
8589  // Save the LoadSDNodes that we find in the chain.
8590  // We need to make sure that these nodes do not interfere with
8591  // any of the store nodes.
8592  SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8593
8594  // Save the StoreSDNodes that we find in the chain.
8595  SmallVector<MemOpLink, 8> StoreNodes;
8596
8597  // Walk up the chain and look for nodes with offsets from the same
8598  // base pointer. Stop when reaching an instruction with a different kind
8599  // or instruction which has a different base pointer.
8600  unsigned Seq = 0;
8601  StoreSDNode *Index = St;
8602  while (Index) {
8603    // If the chain has more than one use, then we can't reorder the mem ops.
8604    if (Index != St && !SDValue(Index, 1)->hasOneUse())
8605      break;
8606
8607    // Find the base pointer and offset for this memory node.
8608    BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8609
8610    // Check that the base pointer is the same as the original one.
8611    if (!Ptr.equalBaseIndex(BasePtr))
8612      break;
8613
8614    // Check that the alignment is the same.
8615    if (Index->getAlignment() != St->getAlignment())
8616      break;
8617
8618    // The memory operands must not be volatile.
8619    if (Index->isVolatile() || Index->isIndexed())
8620      break;
8621
8622    // No truncation.
8623    if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8624      if (St->isTruncatingStore())
8625        break;
8626
8627    // The stored memory type must be the same.
8628    if (Index->getMemoryVT() != MemVT)
8629      break;
8630
8631    // We do not allow unaligned stores because we want to prevent overriding
8632    // stores.
8633    if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8634      break;
8635
8636    // We found a potential memory operand to merge.
8637    StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8638
8639    // Find the next memory operand in the chain. If the next operand in the
8640    // chain is a store then move up and continue the scan with the next
8641    // memory operand. If the next operand is a load save it and use alias
8642    // information to check if it interferes with anything.
8643    SDNode *NextInChain = Index->getChain().getNode();
8644    while (1) {
8645      if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8646        // We found a store node. Use it for the next iteration.
8647        Index = STn;
8648        break;
8649      } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8650        if (Ldn->isVolatile()) {
8651          Index = NULL;
8652          break;
8653        }
8654
8655        // Save the load node for later. Continue the scan.
8656        AliasLoadNodes.push_back(Ldn);
8657        NextInChain = Ldn->getChain().getNode();
8658        continue;
8659      } else {
8660        Index = NULL;
8661        break;
8662      }
8663    }
8664  }
8665
8666  // Check if there is anything to merge.
8667  if (StoreNodes.size() < 2)
8668    return false;
8669
8670  // Sort the memory operands according to their distance from the base pointer.
8671  std::sort(StoreNodes.begin(), StoreNodes.end(),
8672            ConsecutiveMemoryChainSorter());
8673
8674  // Scan the memory operations on the chain and find the first non-consecutive
8675  // store memory address.
8676  unsigned LastConsecutiveStore = 0;
8677  int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8678  for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8679
8680    // Check that the addresses are consecutive starting from the second
8681    // element in the list of stores.
8682    if (i > 0) {
8683      int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8684      if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8685        break;
8686    }
8687
8688    bool Alias = false;
8689    // Check if this store interferes with any of the loads that we found.
8690    for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8691      if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8692        Alias = true;
8693        break;
8694      }
8695    // We found a load that alias with this store. Stop the sequence.
8696    if (Alias)
8697      break;
8698
8699    // Mark this node as useful.
8700    LastConsecutiveStore = i;
8701  }
8702
8703  // The node with the lowest store address.
8704  LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8705
8706  // Store the constants into memory as one consecutive store.
8707  if (!IsLoadSrc) {
8708    unsigned LastLegalType = 0;
8709    unsigned LastLegalVectorType = 0;
8710    bool NonZero = false;
8711    for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8712      StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8713      SDValue StoredVal = St->getValue();
8714
8715      if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8716        NonZero |= !C->isNullValue();
8717      } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8718        NonZero |= !C->getConstantFPValue()->isNullValue();
8719      } else {
8720        // Non constant.
8721        break;
8722      }
8723
8724      // Find a legal type for the constant store.
8725      unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8726      EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8727      if (TLI.isTypeLegal(StoreTy))
8728        LastLegalType = i+1;
8729      // Or check whether a truncstore is legal.
8730      else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8731               TargetLowering::TypePromoteInteger) {
8732        EVT LegalizedStoredValueTy =
8733          TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8734        if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8735          LastLegalType = i+1;
8736      }
8737
8738      // Find a legal type for the vector store.
8739      EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8740      if (TLI.isTypeLegal(Ty))
8741        LastLegalVectorType = i + 1;
8742    }
8743
8744    // We only use vectors if the constant is known to be zero and the
8745    // function is not marked with the noimplicitfloat attribute.
8746    if (NonZero || NoVectors)
8747      LastLegalVectorType = 0;
8748
8749    // Check if we found a legal integer type to store.
8750    if (LastLegalType == 0 && LastLegalVectorType == 0)
8751      return false;
8752
8753    bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8754    unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8755
8756    // Make sure we have something to merge.
8757    if (NumElem < 2)
8758      return false;
8759
8760    unsigned EarliestNodeUsed = 0;
8761    for (unsigned i=0; i < NumElem; ++i) {
8762      // Find a chain for the new wide-store operand. Notice that some
8763      // of the store nodes that we found may not be selected for inclusion
8764      // in the wide store. The chain we use needs to be the chain of the
8765      // earliest store node which is *used* and replaced by the wide store.
8766      if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8767        EarliestNodeUsed = i;
8768    }
8769
8770    // The earliest Node in the DAG.
8771    LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8772    SDLoc DL(StoreNodes[0].MemNode);
8773
8774    SDValue StoredVal;
8775    if (UseVector) {
8776      // Find a legal type for the vector store.
8777      EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8778      assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8779      StoredVal = DAG.getConstant(0, Ty);
8780    } else {
8781      unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8782      APInt StoreInt(StoreBW, 0);
8783
8784      // Construct a single integer constant which is made of the smaller
8785      // constant inputs.
8786      bool IsLE = TLI.isLittleEndian();
8787      for (unsigned i = 0; i < NumElem ; ++i) {
8788        unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8789        StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8790        SDValue Val = St->getValue();
8791        StoreInt<<=ElementSizeBytes*8;
8792        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8793          StoreInt|=C->getAPIntValue().zext(StoreBW);
8794        } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8795          StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8796        } else {
8797          assert(false && "Invalid constant element type");
8798        }
8799      }
8800
8801      // Create the new Load and Store operations.
8802      EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8803      StoredVal = DAG.getConstant(StoreInt, StoreTy);
8804    }
8805
8806    SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8807                                    FirstInChain->getBasePtr(),
8808                                    FirstInChain->getPointerInfo(),
8809                                    false, false,
8810                                    FirstInChain->getAlignment());
8811
8812    // Replace the first store with the new store
8813    CombineTo(EarliestOp, NewStore);
8814    // Erase all other stores.
8815    for (unsigned i = 0; i < NumElem ; ++i) {
8816      if (StoreNodes[i].MemNode == EarliestOp)
8817        continue;
8818      StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8819      // ReplaceAllUsesWith will replace all uses that existed when it was
8820      // called, but graph optimizations may cause new ones to appear. For
8821      // example, the case in pr14333 looks like
8822      //
8823      //  St's chain -> St -> another store -> X
8824      //
8825      // And the only difference from St to the other store is the chain.
8826      // When we change it's chain to be St's chain they become identical,
8827      // get CSEed and the net result is that X is now a use of St.
8828      // Since we know that St is redundant, just iterate.
8829      while (!St->use_empty())
8830        DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8831      removeFromWorkList(St);
8832      DAG.DeleteNode(St);
8833    }
8834
8835    return true;
8836  }
8837
8838  // Below we handle the case of multiple consecutive stores that
8839  // come from multiple consecutive loads. We merge them into a single
8840  // wide load and a single wide store.
8841
8842  // Look for load nodes which are used by the stored values.
8843  SmallVector<MemOpLink, 8> LoadNodes;
8844
8845  // Find acceptable loads. Loads need to have the same chain (token factor),
8846  // must not be zext, volatile, indexed, and they must be consecutive.
8847  BaseIndexOffset LdBasePtr;
8848  for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8849    StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8850    LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8851    if (!Ld) break;
8852
8853    // Loads must only have one use.
8854    if (!Ld->hasNUsesOfValue(1, 0))
8855      break;
8856
8857    // Check that the alignment is the same as the stores.
8858    if (Ld->getAlignment() != St->getAlignment())
8859      break;
8860
8861    // The memory operands must not be volatile.
8862    if (Ld->isVolatile() || Ld->isIndexed())
8863      break;
8864
8865    // We do not accept ext loads.
8866    if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8867      break;
8868
8869    // The stored memory type must be the same.
8870    if (Ld->getMemoryVT() != MemVT)
8871      break;
8872
8873    BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8874    // If this is not the first ptr that we check.
8875    if (LdBasePtr.Base.getNode()) {
8876      // The base ptr must be the same.
8877      if (!LdPtr.equalBaseIndex(LdBasePtr))
8878        break;
8879    } else {
8880      // Check that all other base pointers are the same as this one.
8881      LdBasePtr = LdPtr;
8882    }
8883
8884    // We found a potential memory operand to merge.
8885    LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8886  }
8887
8888  if (LoadNodes.size() < 2)
8889    return false;
8890
8891  // Scan the memory operations on the chain and find the first non-consecutive
8892  // load memory address. These variables hold the index in the store node
8893  // array.
8894  unsigned LastConsecutiveLoad = 0;
8895  // This variable refers to the size and not index in the array.
8896  unsigned LastLegalVectorType = 0;
8897  unsigned LastLegalIntegerType = 0;
8898  StartAddress = LoadNodes[0].OffsetFromBase;
8899  SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8900  for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8901    // All loads much share the same chain.
8902    if (LoadNodes[i].MemNode->getChain() != FirstChain)
8903      break;
8904
8905    int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8906    if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8907      break;
8908    LastConsecutiveLoad = i;
8909
8910    // Find a legal type for the vector store.
8911    EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8912    if (TLI.isTypeLegal(StoreTy))
8913      LastLegalVectorType = i + 1;
8914
8915    // Find a legal type for the integer store.
8916    unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8917    StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8918    if (TLI.isTypeLegal(StoreTy))
8919      LastLegalIntegerType = i + 1;
8920    // Or check whether a truncstore and extload is legal.
8921    else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8922             TargetLowering::TypePromoteInteger) {
8923      EVT LegalizedStoredValueTy =
8924        TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8925      if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8926          TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8927          TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8928          TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8929        LastLegalIntegerType = i+1;
8930    }
8931  }
8932
8933  // Only use vector types if the vector type is larger than the integer type.
8934  // If they are the same, use integers.
8935  bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8936  unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8937
8938  // We add +1 here because the LastXXX variables refer to location while
8939  // the NumElem refers to array/index size.
8940  unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8941  NumElem = std::min(LastLegalType, NumElem);
8942
8943  if (NumElem < 2)
8944    return false;
8945
8946  // The earliest Node in the DAG.
8947  unsigned EarliestNodeUsed = 0;
8948  LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8949  for (unsigned i=1; i<NumElem; ++i) {
8950    // Find a chain for the new wide-store operand. Notice that some
8951    // of the store nodes that we found may not be selected for inclusion
8952    // in the wide store. The chain we use needs to be the chain of the
8953    // earliest store node which is *used* and replaced by the wide store.
8954    if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8955      EarliestNodeUsed = i;
8956  }
8957
8958  // Find if it is better to use vectors or integers to load and store
8959  // to memory.
8960  EVT JointMemOpVT;
8961  if (UseVectorTy) {
8962    JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8963  } else {
8964    unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8965    JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8966  }
8967
8968  SDLoc LoadDL(LoadNodes[0].MemNode);
8969  SDLoc StoreDL(StoreNodes[0].MemNode);
8970
8971  LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8972  SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8973                                FirstLoad->getChain(),
8974                                FirstLoad->getBasePtr(),
8975                                FirstLoad->getPointerInfo(),
8976                                false, false, false,
8977                                FirstLoad->getAlignment());
8978
8979  SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8980                                  FirstInChain->getBasePtr(),
8981                                  FirstInChain->getPointerInfo(), false, false,
8982                                  FirstInChain->getAlignment());
8983
8984  // Replace one of the loads with the new load.
8985  LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8986  DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8987                                SDValue(NewLoad.getNode(), 1));
8988
8989  // Remove the rest of the load chains.
8990  for (unsigned i = 1; i < NumElem ; ++i) {
8991    // Replace all chain users of the old load nodes with the chain of the new
8992    // load node.
8993    LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8994    DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8995  }
8996
8997  // Replace the first store with the new store.
8998  CombineTo(EarliestOp, NewStore);
8999  // Erase all other stores.
9000  for (unsigned i = 0; i < NumElem ; ++i) {
9001    // Remove all Store nodes.
9002    if (StoreNodes[i].MemNode == EarliestOp)
9003      continue;
9004    StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9005    DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9006    removeFromWorkList(St);
9007    DAG.DeleteNode(St);
9008  }
9009
9010  return true;
9011}
9012
9013SDValue DAGCombiner::visitSTORE(SDNode *N) {
9014  StoreSDNode *ST  = cast<StoreSDNode>(N);
9015  SDValue Chain = ST->getChain();
9016  SDValue Value = ST->getValue();
9017  SDValue Ptr   = ST->getBasePtr();
9018
9019  // If this is a store of a bit convert, store the input value if the
9020  // resultant store does not need a higher alignment than the original.
9021  if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9022      ST->isUnindexed()) {
9023    unsigned OrigAlign = ST->getAlignment();
9024    EVT SVT = Value.getOperand(0).getValueType();
9025    unsigned Align = TLI.getDataLayout()->
9026      getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9027    if (Align <= OrigAlign &&
9028        ((!LegalOperations && !ST->isVolatile()) ||
9029         TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9030      return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9031                          Ptr, ST->getPointerInfo(), ST->isVolatile(),
9032                          ST->isNonTemporal(), OrigAlign,
9033                          ST->getTBAAInfo());
9034  }
9035
9036  // Turn 'store undef, Ptr' -> nothing.
9037  if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9038    return Chain;
9039
9040  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9041  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9042    // NOTE: If the original store is volatile, this transform must not increase
9043    // the number of stores.  For example, on x86-32 an f64 can be stored in one
9044    // processor operation but an i64 (which is not legal) requires two.  So the
9045    // transform should not be done in this case.
9046    if (Value.getOpcode() != ISD::TargetConstantFP) {
9047      SDValue Tmp;
9048      switch (CFP->getSimpleValueType(0).SimpleTy) {
9049      default: llvm_unreachable("Unknown FP type");
9050      case MVT::f16:    // We don't do this for these yet.
9051      case MVT::f80:
9052      case MVT::f128:
9053      case MVT::ppcf128:
9054        break;
9055      case MVT::f32:
9056        if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9057            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9058          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9059                              bitcastToAPInt().getZExtValue(), MVT::i32);
9060          return DAG.getStore(Chain, SDLoc(N), Tmp,
9061                              Ptr, ST->getMemOperand());
9062        }
9063        break;
9064      case MVT::f64:
9065        if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9066             !ST->isVolatile()) ||
9067            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9068          Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9069                                getZExtValue(), MVT::i64);
9070          return DAG.getStore(Chain, SDLoc(N), Tmp,
9071                              Ptr, ST->getMemOperand());
9072        }
9073
9074        if (!ST->isVolatile() &&
9075            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9076          // Many FP stores are not made apparent until after legalize, e.g. for
9077          // argument passing.  Since this is so common, custom legalize the
9078          // 64-bit integer store into two 32-bit stores.
9079          uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9080          SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9081          SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9082          if (TLI.isBigEndian()) std::swap(Lo, Hi);
9083
9084          unsigned Alignment = ST->getAlignment();
9085          bool isVolatile = ST->isVolatile();
9086          bool isNonTemporal = ST->isNonTemporal();
9087          const MDNode *TBAAInfo = ST->getTBAAInfo();
9088
9089          SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9090                                     Ptr, ST->getPointerInfo(),
9091                                     isVolatile, isNonTemporal,
9092                                     ST->getAlignment(), TBAAInfo);
9093          Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9094                            DAG.getConstant(4, Ptr.getValueType()));
9095          Alignment = MinAlign(Alignment, 4U);
9096          SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9097                                     Ptr, ST->getPointerInfo().getWithOffset(4),
9098                                     isVolatile, isNonTemporal,
9099                                     Alignment, TBAAInfo);
9100          return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9101                             St0, St1);
9102        }
9103
9104        break;
9105      }
9106    }
9107  }
9108
9109  // Try to infer better alignment information than the store already has.
9110  if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9111    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9112      if (Align > ST->getAlignment())
9113        return DAG.getTruncStore(Chain, SDLoc(N), Value,
9114                                 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9115                                 ST->isVolatile(), ST->isNonTemporal(), Align,
9116                                 ST->getTBAAInfo());
9117    }
9118  }
9119
9120  // Try transforming a pair floating point load / store ops to integer
9121  // load / store ops.
9122  SDValue NewST = TransformFPLoadStorePair(N);
9123  if (NewST.getNode())
9124    return NewST;
9125
9126  bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9127    TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9128  if (UseAA) {
9129    // Walk up chain skipping non-aliasing memory nodes.
9130    SDValue BetterChain = FindBetterChain(N, Chain);
9131
9132    // If there is a better chain.
9133    if (Chain != BetterChain) {
9134      SDValue ReplStore;
9135
9136      // Replace the chain to avoid dependency.
9137      if (ST->isTruncatingStore()) {
9138        ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9139                                      ST->getMemoryVT(), ST->getMemOperand());
9140      } else {
9141        ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9142                                 ST->getMemOperand());
9143      }
9144
9145      // Create token to keep both nodes around.
9146      SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9147                                  MVT::Other, Chain, ReplStore);
9148
9149      // Make sure the new and old chains are cleaned up.
9150      AddToWorkList(Token.getNode());
9151
9152      // Don't add users to work list.
9153      return CombineTo(N, Token, false);
9154    }
9155  }
9156
9157  // Try transforming N to an indexed store.
9158  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9159    return SDValue(N, 0);
9160
9161  // FIXME: is there such a thing as a truncating indexed store?
9162  if (ST->isTruncatingStore() && ST->isUnindexed() &&
9163      Value.getValueType().isInteger()) {
9164    // See if we can simplify the input to this truncstore with knowledge that
9165    // only the low bits are being used.  For example:
9166    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9167    SDValue Shorter =
9168      GetDemandedBits(Value,
9169                      APInt::getLowBitsSet(
9170                        Value.getValueType().getScalarType().getSizeInBits(),
9171                        ST->getMemoryVT().getScalarType().getSizeInBits()));
9172    AddToWorkList(Value.getNode());
9173    if (Shorter.getNode())
9174      return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9175                               Ptr, ST->getMemoryVT(), ST->getMemOperand());
9176
9177    // Otherwise, see if we can simplify the operation with
9178    // SimplifyDemandedBits, which only works if the value has a single use.
9179    if (SimplifyDemandedBits(Value,
9180                        APInt::getLowBitsSet(
9181                          Value.getValueType().getScalarType().getSizeInBits(),
9182                          ST->getMemoryVT().getScalarType().getSizeInBits())))
9183      return SDValue(N, 0);
9184  }
9185
9186  // If this is a load followed by a store to the same location, then the store
9187  // is dead/noop.
9188  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9189    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9190        ST->isUnindexed() && !ST->isVolatile() &&
9191        // There can't be any side effects between the load and store, such as
9192        // a call or store.
9193        Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9194      // The store is dead, remove it.
9195      return Chain;
9196    }
9197  }
9198
9199  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9200  // truncating store.  We can do this even if this is already a truncstore.
9201  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9202      && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9203      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9204                            ST->getMemoryVT())) {
9205    return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9206                             Ptr, ST->getMemoryVT(), ST->getMemOperand());
9207  }
9208
9209  // Only perform this optimization before the types are legal, because we
9210  // don't want to perform this optimization on every DAGCombine invocation.
9211  if (!LegalTypes) {
9212    bool EverChanged = false;
9213
9214    do {
9215      // There can be multiple store sequences on the same chain.
9216      // Keep trying to merge store sequences until we are unable to do so
9217      // or until we merge the last store on the chain.
9218      bool Changed = MergeConsecutiveStores(ST);
9219      EverChanged |= Changed;
9220      if (!Changed) break;
9221    } while (ST->getOpcode() != ISD::DELETED_NODE);
9222
9223    if (EverChanged)
9224      return SDValue(N, 0);
9225  }
9226
9227  return ReduceLoadOpStoreWidth(N);
9228}
9229
9230SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9231  SDValue InVec = N->getOperand(0);
9232  SDValue InVal = N->getOperand(1);
9233  SDValue EltNo = N->getOperand(2);
9234  SDLoc dl(N);
9235
9236  // If the inserted element is an UNDEF, just use the input vector.
9237  if (InVal.getOpcode() == ISD::UNDEF)
9238    return InVec;
9239
9240  EVT VT = InVec.getValueType();
9241
9242  // If we can't generate a legal BUILD_VECTOR, exit
9243  if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9244    return SDValue();
9245
9246  // Check that we know which element is being inserted
9247  if (!isa<ConstantSDNode>(EltNo))
9248    return SDValue();
9249  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9250
9251  // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9252  // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9253  // vector elements.
9254  SmallVector<SDValue, 8> Ops;
9255  // Do not combine these two vectors if the output vector will not replace
9256  // the input vector.
9257  if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9258    Ops.append(InVec.getNode()->op_begin(),
9259               InVec.getNode()->op_end());
9260  } else if (InVec.getOpcode() == ISD::UNDEF) {
9261    unsigned NElts = VT.getVectorNumElements();
9262    Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9263  } else {
9264    return SDValue();
9265  }
9266
9267  // Insert the element
9268  if (Elt < Ops.size()) {
9269    // All the operands of BUILD_VECTOR must have the same type;
9270    // we enforce that here.
9271    EVT OpVT = Ops[0].getValueType();
9272    if (InVal.getValueType() != OpVT)
9273      InVal = OpVT.bitsGT(InVal.getValueType()) ?
9274                DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9275                DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9276    Ops[Elt] = InVal;
9277  }
9278
9279  // Return the new vector
9280  return DAG.getNode(ISD::BUILD_VECTOR, dl,
9281                     VT, &Ops[0], Ops.size());
9282}
9283
9284SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9285  // (vextract (scalar_to_vector val, 0) -> val
9286  SDValue InVec = N->getOperand(0);
9287  EVT VT = InVec.getValueType();
9288  EVT NVT = N->getValueType(0);
9289
9290  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9291    // Check if the result type doesn't match the inserted element type. A
9292    // SCALAR_TO_VECTOR may truncate the inserted element and the
9293    // EXTRACT_VECTOR_ELT may widen the extracted vector.
9294    SDValue InOp = InVec.getOperand(0);
9295    if (InOp.getValueType() != NVT) {
9296      assert(InOp.getValueType().isInteger() && NVT.isInteger());
9297      return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9298    }
9299    return InOp;
9300  }
9301
9302  SDValue EltNo = N->getOperand(1);
9303  bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9304
9305  // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9306  // We only perform this optimization before the op legalization phase because
9307  // we may introduce new vector instructions which are not backed by TD
9308  // patterns. For example on AVX, extracting elements from a wide vector
9309  // without using extract_subvector.
9310  if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9311      && ConstEltNo && !LegalOperations) {
9312    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9313    int NumElem = VT.getVectorNumElements();
9314    ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9315    // Find the new index to extract from.
9316    int OrigElt = SVOp->getMaskElt(Elt);
9317
9318    // Extracting an undef index is undef.
9319    if (OrigElt == -1)
9320      return DAG.getUNDEF(NVT);
9321
9322    // Select the right vector half to extract from.
9323    if (OrigElt < NumElem) {
9324      InVec = InVec->getOperand(0);
9325    } else {
9326      InVec = InVec->getOperand(1);
9327      OrigElt -= NumElem;
9328    }
9329
9330    EVT IndexTy = TLI.getVectorIdxTy();
9331    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9332                       InVec, DAG.getConstant(OrigElt, IndexTy));
9333  }
9334
9335  // Perform only after legalization to ensure build_vector / vector_shuffle
9336  // optimizations have already been done.
9337  if (!LegalOperations) return SDValue();
9338
9339  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9340  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9341  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9342
9343  if (ConstEltNo) {
9344    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9345    bool NewLoad = false;
9346    bool BCNumEltsChanged = false;
9347    EVT ExtVT = VT.getVectorElementType();
9348    EVT LVT = ExtVT;
9349
9350    // If the result of load has to be truncated, then it's not necessarily
9351    // profitable.
9352    if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9353      return SDValue();
9354
9355    if (InVec.getOpcode() == ISD::BITCAST) {
9356      // Don't duplicate a load with other uses.
9357      if (!InVec.hasOneUse())
9358        return SDValue();
9359
9360      EVT BCVT = InVec.getOperand(0).getValueType();
9361      if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9362        return SDValue();
9363      if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9364        BCNumEltsChanged = true;
9365      InVec = InVec.getOperand(0);
9366      ExtVT = BCVT.getVectorElementType();
9367      NewLoad = true;
9368    }
9369
9370    LoadSDNode *LN0 = NULL;
9371    const ShuffleVectorSDNode *SVN = NULL;
9372    if (ISD::isNormalLoad(InVec.getNode())) {
9373      LN0 = cast<LoadSDNode>(InVec);
9374    } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9375               InVec.getOperand(0).getValueType() == ExtVT &&
9376               ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9377      // Don't duplicate a load with other uses.
9378      if (!InVec.hasOneUse())
9379        return SDValue();
9380
9381      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9382    } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9383      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9384      // =>
9385      // (load $addr+1*size)
9386
9387      // Don't duplicate a load with other uses.
9388      if (!InVec.hasOneUse())
9389        return SDValue();
9390
9391      // If the bit convert changed the number of elements, it is unsafe
9392      // to examine the mask.
9393      if (BCNumEltsChanged)
9394        return SDValue();
9395
9396      // Select the input vector, guarding against out of range extract vector.
9397      unsigned NumElems = VT.getVectorNumElements();
9398      int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9399      InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9400
9401      if (InVec.getOpcode() == ISD::BITCAST) {
9402        // Don't duplicate a load with other uses.
9403        if (!InVec.hasOneUse())
9404          return SDValue();
9405
9406        InVec = InVec.getOperand(0);
9407      }
9408      if (ISD::isNormalLoad(InVec.getNode())) {
9409        LN0 = cast<LoadSDNode>(InVec);
9410        Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9411      }
9412    }
9413
9414    // Make sure we found a non-volatile load and the extractelement is
9415    // the only use.
9416    if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9417      return SDValue();
9418
9419    // If Idx was -1 above, Elt is going to be -1, so just return undef.
9420    if (Elt == -1)
9421      return DAG.getUNDEF(LVT);
9422
9423    unsigned Align = LN0->getAlignment();
9424    if (NewLoad) {
9425      // Check the resultant load doesn't need a higher alignment than the
9426      // original load.
9427      unsigned NewAlign =
9428        TLI.getDataLayout()
9429            ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9430
9431      if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9432        return SDValue();
9433
9434      Align = NewAlign;
9435    }
9436
9437    SDValue NewPtr = LN0->getBasePtr();
9438    unsigned PtrOff = 0;
9439
9440    if (Elt) {
9441      PtrOff = LVT.getSizeInBits() * Elt / 8;
9442      EVT PtrType = NewPtr.getValueType();
9443      if (TLI.isBigEndian())
9444        PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9445      NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9446                           DAG.getConstant(PtrOff, PtrType));
9447    }
9448
9449    // The replacement we need to do here is a little tricky: we need to
9450    // replace an extractelement of a load with a load.
9451    // Use ReplaceAllUsesOfValuesWith to do the replacement.
9452    // Note that this replacement assumes that the extractvalue is the only
9453    // use of the load; that's okay because we don't want to perform this
9454    // transformation in other cases anyway.
9455    SDValue Load;
9456    SDValue Chain;
9457    if (NVT.bitsGT(LVT)) {
9458      // If the result type of vextract is wider than the load, then issue an
9459      // extending load instead.
9460      ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9461        ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9462      Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9463                            NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9464                            LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9465                            Align, LN0->getTBAAInfo());
9466      Chain = Load.getValue(1);
9467    } else {
9468      Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9469                         LN0->getPointerInfo().getWithOffset(PtrOff),
9470                         LN0->isVolatile(), LN0->isNonTemporal(),
9471                         LN0->isInvariant(), Align, LN0->getTBAAInfo());
9472      Chain = Load.getValue(1);
9473      if (NVT.bitsLT(LVT))
9474        Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9475      else
9476        Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9477    }
9478    WorkListRemover DeadNodes(*this);
9479    SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9480    SDValue To[] = { Load, Chain };
9481    DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9482    // Since we're explcitly calling ReplaceAllUses, add the new node to the
9483    // worklist explicitly as well.
9484    AddToWorkList(Load.getNode());
9485    AddUsersToWorkList(Load.getNode()); // Add users too
9486    // Make sure to revisit this node to clean it up; it will usually be dead.
9487    AddToWorkList(N);
9488    return SDValue(N, 0);
9489  }
9490
9491  return SDValue();
9492}
9493
9494// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9495SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9496  // We perform this optimization post type-legalization because
9497  // the type-legalizer often scalarizes integer-promoted vectors.
9498  // Performing this optimization before may create bit-casts which
9499  // will be type-legalized to complex code sequences.
9500  // We perform this optimization only before the operation legalizer because we
9501  // may introduce illegal operations.
9502  if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9503    return SDValue();
9504
9505  unsigned NumInScalars = N->getNumOperands();
9506  SDLoc dl(N);
9507  EVT VT = N->getValueType(0);
9508
9509  // Check to see if this is a BUILD_VECTOR of a bunch of values
9510  // which come from any_extend or zero_extend nodes. If so, we can create
9511  // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9512  // optimizations. We do not handle sign-extend because we can't fill the sign
9513  // using shuffles.
9514  EVT SourceType = MVT::Other;
9515  bool AllAnyExt = true;
9516
9517  for (unsigned i = 0; i != NumInScalars; ++i) {
9518    SDValue In = N->getOperand(i);
9519    // Ignore undef inputs.
9520    if (In.getOpcode() == ISD::UNDEF) continue;
9521
9522    bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9523    bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9524
9525    // Abort if the element is not an extension.
9526    if (!ZeroExt && !AnyExt) {
9527      SourceType = MVT::Other;
9528      break;
9529    }
9530
9531    // The input is a ZeroExt or AnyExt. Check the original type.
9532    EVT InTy = In.getOperand(0).getValueType();
9533
9534    // Check that all of the widened source types are the same.
9535    if (SourceType == MVT::Other)
9536      // First time.
9537      SourceType = InTy;
9538    else if (InTy != SourceType) {
9539      // Multiple income types. Abort.
9540      SourceType = MVT::Other;
9541      break;
9542    }
9543
9544    // Check if all of the extends are ANY_EXTENDs.
9545    AllAnyExt &= AnyExt;
9546  }
9547
9548  // In order to have valid types, all of the inputs must be extended from the
9549  // same source type and all of the inputs must be any or zero extend.
9550  // Scalar sizes must be a power of two.
9551  EVT OutScalarTy = VT.getScalarType();
9552  bool ValidTypes = SourceType != MVT::Other &&
9553                 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9554                 isPowerOf2_32(SourceType.getSizeInBits());
9555
9556  // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9557  // turn into a single shuffle instruction.
9558  if (!ValidTypes)
9559    return SDValue();
9560
9561  bool isLE = TLI.isLittleEndian();
9562  unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9563  assert(ElemRatio > 1 && "Invalid element size ratio");
9564  SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9565                               DAG.getConstant(0, SourceType);
9566
9567  unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9568  SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9569
9570  // Populate the new build_vector
9571  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9572    SDValue Cast = N->getOperand(i);
9573    assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9574            Cast.getOpcode() == ISD::ZERO_EXTEND ||
9575            Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9576    SDValue In;
9577    if (Cast.getOpcode() == ISD::UNDEF)
9578      In = DAG.getUNDEF(SourceType);
9579    else
9580      In = Cast->getOperand(0);
9581    unsigned Index = isLE ? (i * ElemRatio) :
9582                            (i * ElemRatio + (ElemRatio - 1));
9583
9584    assert(Index < Ops.size() && "Invalid index");
9585    Ops[Index] = In;
9586  }
9587
9588  // The type of the new BUILD_VECTOR node.
9589  EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9590  assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9591         "Invalid vector size");
9592  // Check if the new vector type is legal.
9593  if (!isTypeLegal(VecVT)) return SDValue();
9594
9595  // Make the new BUILD_VECTOR.
9596  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9597
9598  // The new BUILD_VECTOR node has the potential to be further optimized.
9599  AddToWorkList(BV.getNode());
9600  // Bitcast to the desired type.
9601  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9602}
9603
9604SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9605  EVT VT = N->getValueType(0);
9606
9607  unsigned NumInScalars = N->getNumOperands();
9608  SDLoc dl(N);
9609
9610  EVT SrcVT = MVT::Other;
9611  unsigned Opcode = ISD::DELETED_NODE;
9612  unsigned NumDefs = 0;
9613
9614  for (unsigned i = 0; i != NumInScalars; ++i) {
9615    SDValue In = N->getOperand(i);
9616    unsigned Opc = In.getOpcode();
9617
9618    if (Opc == ISD::UNDEF)
9619      continue;
9620
9621    // If all scalar values are floats and converted from integers.
9622    if (Opcode == ISD::DELETED_NODE &&
9623        (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9624      Opcode = Opc;
9625    }
9626
9627    if (Opc != Opcode)
9628      return SDValue();
9629
9630    EVT InVT = In.getOperand(0).getValueType();
9631
9632    // If all scalar values are typed differently, bail out. It's chosen to
9633    // simplify BUILD_VECTOR of integer types.
9634    if (SrcVT == MVT::Other)
9635      SrcVT = InVT;
9636    if (SrcVT != InVT)
9637      return SDValue();
9638    NumDefs++;
9639  }
9640
9641  // If the vector has just one element defined, it's not worth to fold it into
9642  // a vectorized one.
9643  if (NumDefs < 2)
9644    return SDValue();
9645
9646  assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9647         && "Should only handle conversion from integer to float.");
9648  assert(SrcVT != MVT::Other && "Cannot determine source type!");
9649
9650  EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9651
9652  if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9653    return SDValue();
9654
9655  SmallVector<SDValue, 8> Opnds;
9656  for (unsigned i = 0; i != NumInScalars; ++i) {
9657    SDValue In = N->getOperand(i);
9658
9659    if (In.getOpcode() == ISD::UNDEF)
9660      Opnds.push_back(DAG.getUNDEF(SrcVT));
9661    else
9662      Opnds.push_back(In.getOperand(0));
9663  }
9664  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9665                           &Opnds[0], Opnds.size());
9666  AddToWorkList(BV.getNode());
9667
9668  return DAG.getNode(Opcode, dl, VT, BV);
9669}
9670
9671SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9672  unsigned NumInScalars = N->getNumOperands();
9673  SDLoc dl(N);
9674  EVT VT = N->getValueType(0);
9675
9676  // A vector built entirely of undefs is undef.
9677  if (ISD::allOperandsUndef(N))
9678    return DAG.getUNDEF(VT);
9679
9680  SDValue V = reduceBuildVecExtToExtBuildVec(N);
9681  if (V.getNode())
9682    return V;
9683
9684  V = reduceBuildVecConvertToConvertBuildVec(N);
9685  if (V.getNode())
9686    return V;
9687
9688  // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9689  // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9690  // at most two distinct vectors, turn this into a shuffle node.
9691
9692  // May only combine to shuffle after legalize if shuffle is legal.
9693  if (LegalOperations &&
9694      !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9695    return SDValue();
9696
9697  SDValue VecIn1, VecIn2;
9698  for (unsigned i = 0; i != NumInScalars; ++i) {
9699    // Ignore undef inputs.
9700    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9701
9702    // If this input is something other than a EXTRACT_VECTOR_ELT with a
9703    // constant index, bail out.
9704    if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9705        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9706      VecIn1 = VecIn2 = SDValue(0, 0);
9707      break;
9708    }
9709
9710    // We allow up to two distinct input vectors.
9711    SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9712    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9713      continue;
9714
9715    if (VecIn1.getNode() == 0) {
9716      VecIn1 = ExtractedFromVec;
9717    } else if (VecIn2.getNode() == 0) {
9718      VecIn2 = ExtractedFromVec;
9719    } else {
9720      // Too many inputs.
9721      VecIn1 = VecIn2 = SDValue(0, 0);
9722      break;
9723    }
9724  }
9725
9726    // If everything is good, we can make a shuffle operation.
9727  if (VecIn1.getNode()) {
9728    SmallVector<int, 8> Mask;
9729    for (unsigned i = 0; i != NumInScalars; ++i) {
9730      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9731        Mask.push_back(-1);
9732        continue;
9733      }
9734
9735      // If extracting from the first vector, just use the index directly.
9736      SDValue Extract = N->getOperand(i);
9737      SDValue ExtVal = Extract.getOperand(1);
9738      if (Extract.getOperand(0) == VecIn1) {
9739        unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9740        if (ExtIndex > VT.getVectorNumElements())
9741          return SDValue();
9742
9743        Mask.push_back(ExtIndex);
9744        continue;
9745      }
9746
9747      // Otherwise, use InIdx + VecSize
9748      unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9749      Mask.push_back(Idx+NumInScalars);
9750    }
9751
9752    // We can't generate a shuffle node with mismatched input and output types.
9753    // Attempt to transform a single input vector to the correct type.
9754    if ((VT != VecIn1.getValueType())) {
9755      // We don't support shuffeling between TWO values of different types.
9756      if (VecIn2.getNode() != 0)
9757        return SDValue();
9758
9759      // We only support widening of vectors which are half the size of the
9760      // output registers. For example XMM->YMM widening on X86 with AVX.
9761      if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9762        return SDValue();
9763
9764      // If the input vector type has a different base type to the output
9765      // vector type, bail out.
9766      if (VecIn1.getValueType().getVectorElementType() !=
9767          VT.getVectorElementType())
9768        return SDValue();
9769
9770      // Widen the input vector by adding undef values.
9771      VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9772                           VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9773    }
9774
9775    // If VecIn2 is unused then change it to undef.
9776    VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9777
9778    // Check that we were able to transform all incoming values to the same
9779    // type.
9780    if (VecIn2.getValueType() != VecIn1.getValueType() ||
9781        VecIn1.getValueType() != VT)
9782          return SDValue();
9783
9784    // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9785    if (!isTypeLegal(VT))
9786      return SDValue();
9787
9788    // Return the new VECTOR_SHUFFLE node.
9789    SDValue Ops[2];
9790    Ops[0] = VecIn1;
9791    Ops[1] = VecIn2;
9792    return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9793  }
9794
9795  return SDValue();
9796}
9797
9798SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9799  // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9800  // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9801  // inputs come from at most two distinct vectors, turn this into a shuffle
9802  // node.
9803
9804  // If we only have one input vector, we don't need to do any concatenation.
9805  if (N->getNumOperands() == 1)
9806    return N->getOperand(0);
9807
9808  // Check if all of the operands are undefs.
9809  EVT VT = N->getValueType(0);
9810  if (ISD::allOperandsUndef(N))
9811    return DAG.getUNDEF(VT);
9812
9813  // Optimize concat_vectors where one of the vectors is undef.
9814  if (N->getNumOperands() == 2 &&
9815      N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9816    SDValue In = N->getOperand(0);
9817    assert(In->getValueType(0).isVector() && "Must concat vectors");
9818
9819    // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9820    if (In->getOpcode() == ISD::BITCAST &&
9821        !In->getOperand(0)->getValueType(0).isVector()) {
9822      SDValue Scalar = In->getOperand(0);
9823      EVT SclTy = Scalar->getValueType(0);
9824
9825      if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9826        return SDValue();
9827
9828      EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9829                                 VT.getSizeInBits() / SclTy.getSizeInBits());
9830      if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9831        return SDValue();
9832
9833      SDLoc dl = SDLoc(N);
9834      SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9835      return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9836    }
9837  }
9838
9839  // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9840  // nodes often generate nop CONCAT_VECTOR nodes.
9841  // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9842  // place the incoming vectors at the exact same location.
9843  SDValue SingleSource = SDValue();
9844  unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9845
9846  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9847    SDValue Op = N->getOperand(i);
9848
9849    if (Op.getOpcode() == ISD::UNDEF)
9850      continue;
9851
9852    // Check if this is the identity extract:
9853    if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9854      return SDValue();
9855
9856    // Find the single incoming vector for the extract_subvector.
9857    if (SingleSource.getNode()) {
9858      if (Op.getOperand(0) != SingleSource)
9859        return SDValue();
9860    } else {
9861      SingleSource = Op.getOperand(0);
9862
9863      // Check the source type is the same as the type of the result.
9864      // If not, this concat may extend the vector, so we can not
9865      // optimize it away.
9866      if (SingleSource.getValueType() != N->getValueType(0))
9867        return SDValue();
9868    }
9869
9870    unsigned IdentityIndex = i * PartNumElem;
9871    ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9872    // The extract index must be constant.
9873    if (!CS)
9874      return SDValue();
9875
9876    // Check that we are reading from the identity index.
9877    if (CS->getZExtValue() != IdentityIndex)
9878      return SDValue();
9879  }
9880
9881  if (SingleSource.getNode())
9882    return SingleSource;
9883
9884  return SDValue();
9885}
9886
9887SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9888  EVT NVT = N->getValueType(0);
9889  SDValue V = N->getOperand(0);
9890
9891  if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9892    // Combine:
9893    //    (extract_subvec (concat V1, V2, ...), i)
9894    // Into:
9895    //    Vi if possible
9896    // Only operand 0 is checked as 'concat' assumes all inputs of the same
9897    // type.
9898    if (V->getOperand(0).getValueType() != NVT)
9899      return SDValue();
9900    unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9901    unsigned NumElems = NVT.getVectorNumElements();
9902    assert((Idx % NumElems) == 0 &&
9903           "IDX in concat is not a multiple of the result vector length.");
9904    return V->getOperand(Idx / NumElems);
9905  }
9906
9907  // Skip bitcasting
9908  if (V->getOpcode() == ISD::BITCAST)
9909    V = V.getOperand(0);
9910
9911  if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9912    SDLoc dl(N);
9913    // Handle only simple case where vector being inserted and vector
9914    // being extracted are of same type, and are half size of larger vectors.
9915    EVT BigVT = V->getOperand(0).getValueType();
9916    EVT SmallVT = V->getOperand(1).getValueType();
9917    if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9918      return SDValue();
9919
9920    // Only handle cases where both indexes are constants with the same type.
9921    ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9922    ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9923
9924    if (InsIdx && ExtIdx &&
9925        InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9926        ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9927      // Combine:
9928      //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9929      // Into:
9930      //    indices are equal or bit offsets are equal => V1
9931      //    otherwise => (extract_subvec V1, ExtIdx)
9932      if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9933          ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9934        return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9935      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9936                         DAG.getNode(ISD::BITCAST, dl,
9937                                     N->getOperand(0).getValueType(),
9938                                     V->getOperand(0)), N->getOperand(1));
9939    }
9940  }
9941
9942  return SDValue();
9943}
9944
9945// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9946static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9947  EVT VT = N->getValueType(0);
9948  unsigned NumElts = VT.getVectorNumElements();
9949
9950  SDValue N0 = N->getOperand(0);
9951  SDValue N1 = N->getOperand(1);
9952  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9953
9954  SmallVector<SDValue, 4> Ops;
9955  EVT ConcatVT = N0.getOperand(0).getValueType();
9956  unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9957  unsigned NumConcats = NumElts / NumElemsPerConcat;
9958
9959  // Look at every vector that's inserted. We're looking for exact
9960  // subvector-sized copies from a concatenated vector
9961  for (unsigned I = 0; I != NumConcats; ++I) {
9962    // Make sure we're dealing with a copy.
9963    unsigned Begin = I * NumElemsPerConcat;
9964    bool AllUndef = true, NoUndef = true;
9965    for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9966      if (SVN->getMaskElt(J) >= 0)
9967        AllUndef = false;
9968      else
9969        NoUndef = false;
9970    }
9971
9972    if (NoUndef) {
9973      if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9974        return SDValue();
9975
9976      for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9977        if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9978          return SDValue();
9979
9980      unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9981      if (FirstElt < N0.getNumOperands())
9982        Ops.push_back(N0.getOperand(FirstElt));
9983      else
9984        Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9985
9986    } else if (AllUndef) {
9987      Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9988    } else { // Mixed with general masks and undefs, can't do optimization.
9989      return SDValue();
9990    }
9991  }
9992
9993  return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9994                     Ops.size());
9995}
9996
9997SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9998  EVT VT = N->getValueType(0);
9999  unsigned NumElts = VT.getVectorNumElements();
10000
10001  SDValue N0 = N->getOperand(0);
10002  SDValue N1 = N->getOperand(1);
10003
10004  assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10005
10006  // Canonicalize shuffle undef, undef -> undef
10007  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10008    return DAG.getUNDEF(VT);
10009
10010  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10011
10012  // Canonicalize shuffle v, v -> v, undef
10013  if (N0 == N1) {
10014    SmallVector<int, 8> NewMask;
10015    for (unsigned i = 0; i != NumElts; ++i) {
10016      int Idx = SVN->getMaskElt(i);
10017      if (Idx >= (int)NumElts) Idx -= NumElts;
10018      NewMask.push_back(Idx);
10019    }
10020    return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10021                                &NewMask[0]);
10022  }
10023
10024  // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10025  if (N0.getOpcode() == ISD::UNDEF) {
10026    SmallVector<int, 8> NewMask;
10027    for (unsigned i = 0; i != NumElts; ++i) {
10028      int Idx = SVN->getMaskElt(i);
10029      if (Idx >= 0) {
10030        if (Idx >= (int)NumElts)
10031          Idx -= NumElts;
10032        else
10033          Idx = -1; // remove reference to lhs
10034      }
10035      NewMask.push_back(Idx);
10036    }
10037    return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10038                                &NewMask[0]);
10039  }
10040
10041  // Remove references to rhs if it is undef
10042  if (N1.getOpcode() == ISD::UNDEF) {
10043    bool Changed = false;
10044    SmallVector<int, 8> NewMask;
10045    for (unsigned i = 0; i != NumElts; ++i) {
10046      int Idx = SVN->getMaskElt(i);
10047      if (Idx >= (int)NumElts) {
10048        Idx = -1;
10049        Changed = true;
10050      }
10051      NewMask.push_back(Idx);
10052    }
10053    if (Changed)
10054      return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10055  }
10056
10057  // If it is a splat, check if the argument vector is another splat or a
10058  // build_vector with all scalar elements the same.
10059  if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10060    SDNode *V = N0.getNode();
10061
10062    // If this is a bit convert that changes the element type of the vector but
10063    // not the number of vector elements, look through it.  Be careful not to
10064    // look though conversions that change things like v4f32 to v2f64.
10065    if (V->getOpcode() == ISD::BITCAST) {
10066      SDValue ConvInput = V->getOperand(0);
10067      if (ConvInput.getValueType().isVector() &&
10068          ConvInput.getValueType().getVectorNumElements() == NumElts)
10069        V = ConvInput.getNode();
10070    }
10071
10072    if (V->getOpcode() == ISD::BUILD_VECTOR) {
10073      assert(V->getNumOperands() == NumElts &&
10074             "BUILD_VECTOR has wrong number of operands");
10075      SDValue Base;
10076      bool AllSame = true;
10077      for (unsigned i = 0; i != NumElts; ++i) {
10078        if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10079          Base = V->getOperand(i);
10080          break;
10081        }
10082      }
10083      // Splat of <u, u, u, u>, return <u, u, u, u>
10084      if (!Base.getNode())
10085        return N0;
10086      for (unsigned i = 0; i != NumElts; ++i) {
10087        if (V->getOperand(i) != Base) {
10088          AllSame = false;
10089          break;
10090        }
10091      }
10092      // Splat of <x, x, x, x>, return <x, x, x, x>
10093      if (AllSame)
10094        return N0;
10095    }
10096  }
10097
10098  if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10099      Level < AfterLegalizeVectorOps &&
10100      (N1.getOpcode() == ISD::UNDEF ||
10101      (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10102       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10103    SDValue V = partitionShuffleOfConcats(N, DAG);
10104
10105    if (V.getNode())
10106      return V;
10107  }
10108
10109  // If this shuffle node is simply a swizzle of another shuffle node,
10110  // and it reverses the swizzle of the previous shuffle then we can
10111  // optimize shuffle(shuffle(x, undef), undef) -> x.
10112  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10113      N1.getOpcode() == ISD::UNDEF) {
10114
10115    ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10116
10117    // Shuffle nodes can only reverse shuffles with a single non-undef value.
10118    if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10119      return SDValue();
10120
10121    // The incoming shuffle must be of the same type as the result of the
10122    // current shuffle.
10123    assert(OtherSV->getOperand(0).getValueType() == VT &&
10124           "Shuffle types don't match");
10125
10126    for (unsigned i = 0; i != NumElts; ++i) {
10127      int Idx = SVN->getMaskElt(i);
10128      assert(Idx < (int)NumElts && "Index references undef operand");
10129      // Next, this index comes from the first value, which is the incoming
10130      // shuffle. Adopt the incoming index.
10131      if (Idx >= 0)
10132        Idx = OtherSV->getMaskElt(Idx);
10133
10134      // The combined shuffle must map each index to itself.
10135      if (Idx >= 0 && (unsigned)Idx != i)
10136        return SDValue();
10137    }
10138
10139    return OtherSV->getOperand(0);
10140  }
10141
10142  return SDValue();
10143}
10144
10145/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10146/// an AND to a vector_shuffle with the destination vector and a zero vector.
10147/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10148///      vector_shuffle V, Zero, <0, 4, 2, 4>
10149SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10150  EVT VT = N->getValueType(0);
10151  SDLoc dl(N);
10152  SDValue LHS = N->getOperand(0);
10153  SDValue RHS = N->getOperand(1);
10154  if (N->getOpcode() == ISD::AND) {
10155    if (RHS.getOpcode() == ISD::BITCAST)
10156      RHS = RHS.getOperand(0);
10157    if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10158      SmallVector<int, 8> Indices;
10159      unsigned NumElts = RHS.getNumOperands();
10160      for (unsigned i = 0; i != NumElts; ++i) {
10161        SDValue Elt = RHS.getOperand(i);
10162        if (!isa<ConstantSDNode>(Elt))
10163          return SDValue();
10164
10165        if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10166          Indices.push_back(i);
10167        else if (cast<ConstantSDNode>(Elt)->isNullValue())
10168          Indices.push_back(NumElts);
10169        else
10170          return SDValue();
10171      }
10172
10173      // Let's see if the target supports this vector_shuffle.
10174      EVT RVT = RHS.getValueType();
10175      if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10176        return SDValue();
10177
10178      // Return the new VECTOR_SHUFFLE node.
10179      EVT EltVT = RVT.getVectorElementType();
10180      SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10181                                     DAG.getConstant(0, EltVT));
10182      SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10183                                 RVT, &ZeroOps[0], ZeroOps.size());
10184      LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10185      SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10186      return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10187    }
10188  }
10189
10190  return SDValue();
10191}
10192
10193/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10194SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10195  assert(N->getValueType(0).isVector() &&
10196         "SimplifyVBinOp only works on vectors!");
10197
10198  SDValue LHS = N->getOperand(0);
10199  SDValue RHS = N->getOperand(1);
10200  SDValue Shuffle = XformToShuffleWithZero(N);
10201  if (Shuffle.getNode()) return Shuffle;
10202
10203  // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10204  // this operation.
10205  if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10206      RHS.getOpcode() == ISD::BUILD_VECTOR) {
10207    SmallVector<SDValue, 8> Ops;
10208    for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10209      SDValue LHSOp = LHS.getOperand(i);
10210      SDValue RHSOp = RHS.getOperand(i);
10211      // If these two elements can't be folded, bail out.
10212      if ((LHSOp.getOpcode() != ISD::UNDEF &&
10213           LHSOp.getOpcode() != ISD::Constant &&
10214           LHSOp.getOpcode() != ISD::ConstantFP) ||
10215          (RHSOp.getOpcode() != ISD::UNDEF &&
10216           RHSOp.getOpcode() != ISD::Constant &&
10217           RHSOp.getOpcode() != ISD::ConstantFP))
10218        break;
10219
10220      // Can't fold divide by zero.
10221      if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10222          N->getOpcode() == ISD::FDIV) {
10223        if ((RHSOp.getOpcode() == ISD::Constant &&
10224             cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10225            (RHSOp.getOpcode() == ISD::ConstantFP &&
10226             cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10227          break;
10228      }
10229
10230      EVT VT = LHSOp.getValueType();
10231      EVT RVT = RHSOp.getValueType();
10232      if (RVT != VT) {
10233        // Integer BUILD_VECTOR operands may have types larger than the element
10234        // size (e.g., when the element type is not legal).  Prior to type
10235        // legalization, the types may not match between the two BUILD_VECTORS.
10236        // Truncate one of the operands to make them match.
10237        if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10238          RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10239        } else {
10240          LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10241          VT = RVT;
10242        }
10243      }
10244      SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10245                                   LHSOp, RHSOp);
10246      if (FoldOp.getOpcode() != ISD::UNDEF &&
10247          FoldOp.getOpcode() != ISD::Constant &&
10248          FoldOp.getOpcode() != ISD::ConstantFP)
10249        break;
10250      Ops.push_back(FoldOp);
10251      AddToWorkList(FoldOp.getNode());
10252    }
10253
10254    if (Ops.size() == LHS.getNumOperands())
10255      return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10256                         LHS.getValueType(), &Ops[0], Ops.size());
10257  }
10258
10259  return SDValue();
10260}
10261
10262/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10263SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10264  assert(N->getValueType(0).isVector() &&
10265         "SimplifyVUnaryOp only works on vectors!");
10266
10267  SDValue N0 = N->getOperand(0);
10268
10269  if (N0.getOpcode() != ISD::BUILD_VECTOR)
10270    return SDValue();
10271
10272  // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10273  SmallVector<SDValue, 8> Ops;
10274  for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10275    SDValue Op = N0.getOperand(i);
10276    if (Op.getOpcode() != ISD::UNDEF &&
10277        Op.getOpcode() != ISD::ConstantFP)
10278      break;
10279    EVT EltVT = Op.getValueType();
10280    SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10281    if (FoldOp.getOpcode() != ISD::UNDEF &&
10282        FoldOp.getOpcode() != ISD::ConstantFP)
10283      break;
10284    Ops.push_back(FoldOp);
10285    AddToWorkList(FoldOp.getNode());
10286  }
10287
10288  if (Ops.size() != N0.getNumOperands())
10289    return SDValue();
10290
10291  return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10292                     N0.getValueType(), &Ops[0], Ops.size());
10293}
10294
10295SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10296                                    SDValue N1, SDValue N2){
10297  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10298
10299  SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10300                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10301
10302  // If we got a simplified select_cc node back from SimplifySelectCC, then
10303  // break it down into a new SETCC node, and a new SELECT node, and then return
10304  // the SELECT node, since we were called with a SELECT node.
10305  if (SCC.getNode()) {
10306    // Check to see if we got a select_cc back (to turn into setcc/select).
10307    // Otherwise, just return whatever node we got back, like fabs.
10308    if (SCC.getOpcode() == ISD::SELECT_CC) {
10309      SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10310                                  N0.getValueType(),
10311                                  SCC.getOperand(0), SCC.getOperand(1),
10312                                  SCC.getOperand(4));
10313      AddToWorkList(SETCC.getNode());
10314      return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10315                           SCC.getOperand(2), SCC.getOperand(3), SETCC);
10316    }
10317
10318    return SCC;
10319  }
10320  return SDValue();
10321}
10322
10323/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10324/// are the two values being selected between, see if we can simplify the
10325/// select.  Callers of this should assume that TheSelect is deleted if this
10326/// returns true.  As such, they should return the appropriate thing (e.g. the
10327/// node) back to the top-level of the DAG combiner loop to avoid it being
10328/// looked at.
10329bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10330                                    SDValue RHS) {
10331
10332  // Cannot simplify select with vector condition
10333  if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10334
10335  // If this is a select from two identical things, try to pull the operation
10336  // through the select.
10337  if (LHS.getOpcode() != RHS.getOpcode() ||
10338      !LHS.hasOneUse() || !RHS.hasOneUse())
10339    return false;
10340
10341  // If this is a load and the token chain is identical, replace the select
10342  // of two loads with a load through a select of the address to load from.
10343  // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10344  // constants have been dropped into the constant pool.
10345  if (LHS.getOpcode() == ISD::LOAD) {
10346    LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10347    LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10348
10349    // Token chains must be identical.
10350    if (LHS.getOperand(0) != RHS.getOperand(0) ||
10351        // Do not let this transformation reduce the number of volatile loads.
10352        LLD->isVolatile() || RLD->isVolatile() ||
10353        // If this is an EXTLOAD, the VT's must match.
10354        LLD->getMemoryVT() != RLD->getMemoryVT() ||
10355        // If this is an EXTLOAD, the kind of extension must match.
10356        (LLD->getExtensionType() != RLD->getExtensionType() &&
10357         // The only exception is if one of the extensions is anyext.
10358         LLD->getExtensionType() != ISD::EXTLOAD &&
10359         RLD->getExtensionType() != ISD::EXTLOAD) ||
10360        // FIXME: this discards src value information.  This is
10361        // over-conservative. It would be beneficial to be able to remember
10362        // both potential memory locations.  Since we are discarding
10363        // src value info, don't do the transformation if the memory
10364        // locations are not in the default address space.
10365        LLD->getPointerInfo().getAddrSpace() != 0 ||
10366        RLD->getPointerInfo().getAddrSpace() != 0 ||
10367        !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10368                                      LLD->getBasePtr().getValueType()))
10369      return false;
10370
10371    // Check that the select condition doesn't reach either load.  If so,
10372    // folding this will induce a cycle into the DAG.  If not, this is safe to
10373    // xform, so create a select of the addresses.
10374    SDValue Addr;
10375    if (TheSelect->getOpcode() == ISD::SELECT) {
10376      SDNode *CondNode = TheSelect->getOperand(0).getNode();
10377      if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10378          (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10379        return false;
10380      // The loads must not depend on one another.
10381      if (LLD->isPredecessorOf(RLD) ||
10382          RLD->isPredecessorOf(LLD))
10383        return false;
10384      Addr = DAG.getSelect(SDLoc(TheSelect),
10385                           LLD->getBasePtr().getValueType(),
10386                           TheSelect->getOperand(0), LLD->getBasePtr(),
10387                           RLD->getBasePtr());
10388    } else {  // Otherwise SELECT_CC
10389      SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10390      SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10391
10392      if ((LLD->hasAnyUseOfValue(1) &&
10393           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10394          (RLD->hasAnyUseOfValue(1) &&
10395           (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10396        return false;
10397
10398      Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10399                         LLD->getBasePtr().getValueType(),
10400                         TheSelect->getOperand(0),
10401                         TheSelect->getOperand(1),
10402                         LLD->getBasePtr(), RLD->getBasePtr(),
10403                         TheSelect->getOperand(4));
10404    }
10405
10406    SDValue Load;
10407    if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10408      Load = DAG.getLoad(TheSelect->getValueType(0),
10409                         SDLoc(TheSelect),
10410                         // FIXME: Discards pointer and TBAA info.
10411                         LLD->getChain(), Addr, MachinePointerInfo(),
10412                         LLD->isVolatile(), LLD->isNonTemporal(),
10413                         LLD->isInvariant(), LLD->getAlignment());
10414    } else {
10415      Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10416                            RLD->getExtensionType() : LLD->getExtensionType(),
10417                            SDLoc(TheSelect),
10418                            TheSelect->getValueType(0),
10419                            // FIXME: Discards pointer and TBAA info.
10420                            LLD->getChain(), Addr, MachinePointerInfo(),
10421                            LLD->getMemoryVT(), LLD->isVolatile(),
10422                            LLD->isNonTemporal(), LLD->getAlignment());
10423    }
10424
10425    // Users of the select now use the result of the load.
10426    CombineTo(TheSelect, Load);
10427
10428    // Users of the old loads now use the new load's chain.  We know the
10429    // old-load value is dead now.
10430    CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10431    CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10432    return true;
10433  }
10434
10435  return false;
10436}
10437
10438/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10439/// where 'cond' is the comparison specified by CC.
10440SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10441                                      SDValue N2, SDValue N3,
10442                                      ISD::CondCode CC, bool NotExtCompare) {
10443  // (x ? y : y) -> y.
10444  if (N2 == N3) return N2;
10445
10446  EVT VT = N2.getValueType();
10447  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10448  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10449  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10450
10451  // Determine if the condition we're dealing with is constant
10452  SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10453                              N0, N1, CC, DL, false);
10454  if (SCC.getNode()) AddToWorkList(SCC.getNode());
10455  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10456
10457  // fold select_cc true, x, y -> x
10458  if (SCCC && !SCCC->isNullValue())
10459    return N2;
10460  // fold select_cc false, x, y -> y
10461  if (SCCC && SCCC->isNullValue())
10462    return N3;
10463
10464  // Check to see if we can simplify the select into an fabs node
10465  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10466    // Allow either -0.0 or 0.0
10467    if (CFP->getValueAPF().isZero()) {
10468      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10469      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10470          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10471          N2 == N3.getOperand(0))
10472        return DAG.getNode(ISD::FABS, DL, VT, N0);
10473
10474      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10475      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10476          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10477          N2.getOperand(0) == N3)
10478        return DAG.getNode(ISD::FABS, DL, VT, N3);
10479    }
10480  }
10481
10482  // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10483  // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10484  // in it.  This is a win when the constant is not otherwise available because
10485  // it replaces two constant pool loads with one.  We only do this if the FP
10486  // type is known to be legal, because if it isn't, then we are before legalize
10487  // types an we want the other legalization to happen first (e.g. to avoid
10488  // messing with soft float) and if the ConstantFP is not legal, because if
10489  // it is legal, we may not need to store the FP constant in a constant pool.
10490  if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10491    if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10492      if (TLI.isTypeLegal(N2.getValueType()) &&
10493          (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10494           TargetLowering::Legal) &&
10495          // If both constants have multiple uses, then we won't need to do an
10496          // extra load, they are likely around in registers for other users.
10497          (TV->hasOneUse() || FV->hasOneUse())) {
10498        Constant *Elts[] = {
10499          const_cast<ConstantFP*>(FV->getConstantFPValue()),
10500          const_cast<ConstantFP*>(TV->getConstantFPValue())
10501        };
10502        Type *FPTy = Elts[0]->getType();
10503        const DataLayout &TD = *TLI.getDataLayout();
10504
10505        // Create a ConstantArray of the two constants.
10506        Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10507        SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10508                                            TD.getPrefTypeAlignment(FPTy));
10509        unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10510
10511        // Get the offsets to the 0 and 1 element of the array so that we can
10512        // select between them.
10513        SDValue Zero = DAG.getIntPtrConstant(0);
10514        unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10515        SDValue One = DAG.getIntPtrConstant(EltSize);
10516
10517        SDValue Cond = DAG.getSetCC(DL,
10518                                    getSetCCResultType(N0.getValueType()),
10519                                    N0, N1, CC);
10520        AddToWorkList(Cond.getNode());
10521        SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10522                                          Cond, One, Zero);
10523        AddToWorkList(CstOffset.getNode());
10524        CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10525                            CstOffset);
10526        AddToWorkList(CPIdx.getNode());
10527        return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10528                           MachinePointerInfo::getConstantPool(), false,
10529                           false, false, Alignment);
10530
10531      }
10532    }
10533
10534  // Check to see if we can perform the "gzip trick", transforming
10535  // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10536  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10537      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10538       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10539    EVT XType = N0.getValueType();
10540    EVT AType = N2.getValueType();
10541    if (XType.bitsGE(AType)) {
10542      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10543      // single-bit constant.
10544      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10545        unsigned ShCtV = N2C->getAPIntValue().logBase2();
10546        ShCtV = XType.getSizeInBits()-ShCtV-1;
10547        SDValue ShCt = DAG.getConstant(ShCtV,
10548                                       getShiftAmountTy(N0.getValueType()));
10549        SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10550                                    XType, N0, ShCt);
10551        AddToWorkList(Shift.getNode());
10552
10553        if (XType.bitsGT(AType)) {
10554          Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10555          AddToWorkList(Shift.getNode());
10556        }
10557
10558        return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10559      }
10560
10561      SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10562                                  XType, N0,
10563                                  DAG.getConstant(XType.getSizeInBits()-1,
10564                                         getShiftAmountTy(N0.getValueType())));
10565      AddToWorkList(Shift.getNode());
10566
10567      if (XType.bitsGT(AType)) {
10568        Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10569        AddToWorkList(Shift.getNode());
10570      }
10571
10572      return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10573    }
10574  }
10575
10576  // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10577  // where y is has a single bit set.
10578  // A plaintext description would be, we can turn the SELECT_CC into an AND
10579  // when the condition can be materialized as an all-ones register.  Any
10580  // single bit-test can be materialized as an all-ones register with
10581  // shift-left and shift-right-arith.
10582  if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10583      N0->getValueType(0) == VT &&
10584      N1C && N1C->isNullValue() &&
10585      N2C && N2C->isNullValue()) {
10586    SDValue AndLHS = N0->getOperand(0);
10587    ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10588    if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10589      // Shift the tested bit over the sign bit.
10590      APInt AndMask = ConstAndRHS->getAPIntValue();
10591      SDValue ShlAmt =
10592        DAG.getConstant(AndMask.countLeadingZeros(),
10593                        getShiftAmountTy(AndLHS.getValueType()));
10594      SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10595
10596      // Now arithmetic right shift it all the way over, so the result is either
10597      // all-ones, or zero.
10598      SDValue ShrAmt =
10599        DAG.getConstant(AndMask.getBitWidth()-1,
10600                        getShiftAmountTy(Shl.getValueType()));
10601      SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10602
10603      return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10604    }
10605  }
10606
10607  // fold select C, 16, 0 -> shl C, 4
10608  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10609    TLI.getBooleanContents(N0.getValueType().isVector()) ==
10610      TargetLowering::ZeroOrOneBooleanContent) {
10611
10612    // If the caller doesn't want us to simplify this into a zext of a compare,
10613    // don't do it.
10614    if (NotExtCompare && N2C->getAPIntValue() == 1)
10615      return SDValue();
10616
10617    // Get a SetCC of the condition
10618    // NOTE: Don't create a SETCC if it's not legal on this target.
10619    if (!LegalOperations ||
10620        TLI.isOperationLegal(ISD::SETCC,
10621          LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10622      SDValue Temp, SCC;
10623      // cast from setcc result type to select result type
10624      if (LegalTypes) {
10625        SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10626                            N0, N1, CC);
10627        if (N2.getValueType().bitsLT(SCC.getValueType()))
10628          Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10629                                        N2.getValueType());
10630        else
10631          Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10632                             N2.getValueType(), SCC);
10633      } else {
10634        SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10635        Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10636                           N2.getValueType(), SCC);
10637      }
10638
10639      AddToWorkList(SCC.getNode());
10640      AddToWorkList(Temp.getNode());
10641
10642      if (N2C->getAPIntValue() == 1)
10643        return Temp;
10644
10645      // shl setcc result by log2 n2c
10646      return DAG.getNode(
10647          ISD::SHL, DL, N2.getValueType(), Temp,
10648          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10649                          getShiftAmountTy(Temp.getValueType())));
10650    }
10651  }
10652
10653  // Check to see if this is the equivalent of setcc
10654  // FIXME: Turn all of these into setcc if setcc if setcc is legal
10655  // otherwise, go ahead with the folds.
10656  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10657    EVT XType = N0.getValueType();
10658    if (!LegalOperations ||
10659        TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10660      SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10661      if (Res.getValueType() != VT)
10662        Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10663      return Res;
10664    }
10665
10666    // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10667    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10668        (!LegalOperations ||
10669         TLI.isOperationLegal(ISD::CTLZ, XType))) {
10670      SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10671      return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10672                         DAG.getConstant(Log2_32(XType.getSizeInBits()),
10673                                       getShiftAmountTy(Ctlz.getValueType())));
10674    }
10675    // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10676    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10677      SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10678                                  XType, DAG.getConstant(0, XType), N0);
10679      SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10680      return DAG.getNode(ISD::SRL, DL, XType,
10681                         DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10682                         DAG.getConstant(XType.getSizeInBits()-1,
10683                                         getShiftAmountTy(XType)));
10684    }
10685    // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10686    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10687      SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10688                                 DAG.getConstant(XType.getSizeInBits()-1,
10689                                         getShiftAmountTy(N0.getValueType())));
10690      return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10691    }
10692  }
10693
10694  // Check to see if this is an integer abs.
10695  // select_cc setg[te] X,  0,  X, -X ->
10696  // select_cc setgt    X, -1,  X, -X ->
10697  // select_cc setl[te] X,  0, -X,  X ->
10698  // select_cc setlt    X,  1, -X,  X ->
10699  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10700  if (N1C) {
10701    ConstantSDNode *SubC = NULL;
10702    if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10703         (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10704        N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10705      SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10706    else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10707              (N1C->isOne() && CC == ISD::SETLT)) &&
10708             N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10709      SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10710
10711    EVT XType = N0.getValueType();
10712    if (SubC && SubC->isNullValue() && XType.isInteger()) {
10713      SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10714                                  N0,
10715                                  DAG.getConstant(XType.getSizeInBits()-1,
10716                                         getShiftAmountTy(N0.getValueType())));
10717      SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10718                                XType, N0, Shift);
10719      AddToWorkList(Shift.getNode());
10720      AddToWorkList(Add.getNode());
10721      return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10722    }
10723  }
10724
10725  return SDValue();
10726}
10727
10728/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10729SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10730                                   SDValue N1, ISD::CondCode Cond,
10731                                   SDLoc DL, bool foldBooleans) {
10732  TargetLowering::DAGCombinerInfo
10733    DagCombineInfo(DAG, Level, false, this);
10734  return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10735}
10736
10737/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10738/// return a DAG expression to select that will generate the same value by
10739/// multiplying by a magic number.  See:
10740/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10741SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10742  std::vector<SDNode*> Built;
10743  SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10744
10745  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10746       ii != ee; ++ii)
10747    AddToWorkList(*ii);
10748  return S;
10749}
10750
10751/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10752/// return a DAG expression to select that will generate the same value by
10753/// multiplying by a magic number.  See:
10754/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10755SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10756  std::vector<SDNode*> Built;
10757  SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10758
10759  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10760       ii != ee; ++ii)
10761    AddToWorkList(*ii);
10762  return S;
10763}
10764
10765/// FindBaseOffset - Return true if base is a frame index, which is known not
10766// to alias with anything but itself.  Provides base object and offset as
10767// results.
10768static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10769                           const GlobalValue *&GV, const void *&CV) {
10770  // Assume it is a primitive operation.
10771  Base = Ptr; Offset = 0; GV = 0; CV = 0;
10772
10773  // If it's an adding a simple constant then integrate the offset.
10774  if (Base.getOpcode() == ISD::ADD) {
10775    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10776      Base = Base.getOperand(0);
10777      Offset += C->getZExtValue();
10778    }
10779  }
10780
10781  // Return the underlying GlobalValue, and update the Offset.  Return false
10782  // for GlobalAddressSDNode since the same GlobalAddress may be represented
10783  // by multiple nodes with different offsets.
10784  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10785    GV = G->getGlobal();
10786    Offset += G->getOffset();
10787    return false;
10788  }
10789
10790  // Return the underlying Constant value, and update the Offset.  Return false
10791  // for ConstantSDNodes since the same constant pool entry may be represented
10792  // by multiple nodes with different offsets.
10793  if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10794    CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10795                                         : (const void *)C->getConstVal();
10796    Offset += C->getOffset();
10797    return false;
10798  }
10799  // If it's any of the following then it can't alias with anything but itself.
10800  return isa<FrameIndexSDNode>(Base);
10801}
10802
10803/// isAlias - Return true if there is any possibility that the two addresses
10804/// overlap.
10805bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10806                          const Value *SrcValue1, int SrcValueOffset1,
10807                          unsigned SrcValueAlign1,
10808                          const MDNode *TBAAInfo1,
10809                          SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10810                          const Value *SrcValue2, int SrcValueOffset2,
10811                          unsigned SrcValueAlign2,
10812                          const MDNode *TBAAInfo2) const {
10813  // If they are the same then they must be aliases.
10814  if (Ptr1 == Ptr2) return true;
10815
10816  // If they are both volatile then they cannot be reordered.
10817  if (IsVolatile1 && IsVolatile2) return true;
10818
10819  // Gather base node and offset information.
10820  SDValue Base1, Base2;
10821  int64_t Offset1, Offset2;
10822  const GlobalValue *GV1, *GV2;
10823  const void *CV1, *CV2;
10824  bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10825  bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10826
10827  // If they have a same base address then check to see if they overlap.
10828  if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10829    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10830
10831  // It is possible for different frame indices to alias each other, mostly
10832  // when tail call optimization reuses return address slots for arguments.
10833  // To catch this case, look up the actual index of frame indices to compute
10834  // the real alias relationship.
10835  if (isFrameIndex1 && isFrameIndex2) {
10836    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10837    Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10838    Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10839    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10840  }
10841
10842  // Otherwise, if we know what the bases are, and they aren't identical, then
10843  // we know they cannot alias.
10844  if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10845    return false;
10846
10847  // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10848  // compared to the size and offset of the access, we may be able to prove they
10849  // do not alias.  This check is conservative for now to catch cases created by
10850  // splitting vector types.
10851  if ((SrcValueAlign1 == SrcValueAlign2) &&
10852      (SrcValueOffset1 != SrcValueOffset2) &&
10853      (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10854    int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10855    int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10856
10857    // There is no overlap between these relatively aligned accesses of similar
10858    // size, return no alias.
10859    if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10860      return false;
10861  }
10862
10863  bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10864    TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10865  if (UseAA && SrcValue1 && SrcValue2) {
10866    // Use alias analysis information.
10867    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10868    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10869    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10870    AliasAnalysis::AliasResult AAResult =
10871      AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10872               AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10873    if (AAResult == AliasAnalysis::NoAlias)
10874      return false;
10875  }
10876
10877  // Otherwise we have to assume they alias.
10878  return true;
10879}
10880
10881bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10882  SDValue Ptr0, Ptr1;
10883  int64_t Size0, Size1;
10884  bool IsVolatile0, IsVolatile1;
10885  const Value *SrcValue0, *SrcValue1;
10886  int SrcValueOffset0, SrcValueOffset1;
10887  unsigned SrcValueAlign0, SrcValueAlign1;
10888  const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10889  FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10890                SrcValueAlign0, SrcTBAAInfo0);
10891  FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10892                SrcValueAlign1, SrcTBAAInfo1);
10893  return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10894                 SrcValueAlign0, SrcTBAAInfo0,
10895                 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10896                 SrcValueAlign1, SrcTBAAInfo1);
10897}
10898
10899/// FindAliasInfo - Extracts the relevant alias information from the memory
10900/// node.  Returns true if the operand was a nonvolatile load.
10901bool DAGCombiner::FindAliasInfo(SDNode *N,
10902                                SDValue &Ptr, int64_t &Size, bool &IsVolatile,
10903                                const Value *&SrcValue,
10904                                int &SrcValueOffset,
10905                                unsigned &SrcValueAlign,
10906                                const MDNode *&TBAAInfo) const {
10907  LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10908
10909  Ptr = LS->getBasePtr();
10910  Size = LS->getMemoryVT().getSizeInBits() >> 3;
10911  IsVolatile = LS->isVolatile();
10912  SrcValue = LS->getSrcValue();
10913  SrcValueOffset = LS->getSrcValueOffset();
10914  SrcValueAlign = LS->getOriginalAlignment();
10915  TBAAInfo = LS->getTBAAInfo();
10916  return isa<LoadSDNode>(LS) && !IsVolatile;
10917}
10918
10919/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10920/// looking for aliasing nodes and adding them to the Aliases vector.
10921void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10922                                   SmallVectorImpl<SDValue> &Aliases) {
10923  SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10924  SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10925
10926  // Get alias information for node.
10927  SDValue Ptr;
10928  int64_t Size;
10929  bool IsVolatile;
10930  const Value *SrcValue;
10931  int SrcValueOffset;
10932  unsigned SrcValueAlign;
10933  const MDNode *SrcTBAAInfo;
10934  bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
10935                              SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
10936
10937  // Starting off.
10938  Chains.push_back(OriginalChain);
10939  unsigned Depth = 0;
10940
10941  // Look at each chain and determine if it is an alias.  If so, add it to the
10942  // aliases list.  If not, then continue up the chain looking for the next
10943  // candidate.
10944  while (!Chains.empty()) {
10945    SDValue Chain = Chains.back();
10946    Chains.pop_back();
10947
10948    // For TokenFactor nodes, look at each operand and only continue up the
10949    // chain until we find two aliases.  If we've seen two aliases, assume we'll
10950    // find more and revert to original chain since the xform is unlikely to be
10951    // profitable.
10952    //
10953    // FIXME: The depth check could be made to return the last non-aliasing
10954    // chain we found before we hit a tokenfactor rather than the original
10955    // chain.
10956    if (Depth > 6 || Aliases.size() == 2) {
10957      Aliases.clear();
10958      Aliases.push_back(OriginalChain);
10959      break;
10960    }
10961
10962    // Don't bother if we've been before.
10963    if (!Visited.insert(Chain.getNode()))
10964      continue;
10965
10966    switch (Chain.getOpcode()) {
10967    case ISD::EntryToken:
10968      // Entry token is ideal chain operand, but handled in FindBetterChain.
10969      break;
10970
10971    case ISD::LOAD:
10972    case ISD::STORE: {
10973      // Get alias information for Chain.
10974      SDValue OpPtr;
10975      int64_t OpSize;
10976      bool OpIsVolatile;
10977      const Value *OpSrcValue;
10978      int OpSrcValueOffset;
10979      unsigned OpSrcValueAlign;
10980      const MDNode *OpSrcTBAAInfo;
10981      bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10982                                    OpIsVolatile, OpSrcValue, OpSrcValueOffset,
10983                                    OpSrcValueAlign,
10984                                    OpSrcTBAAInfo);
10985
10986      // If chain is alias then stop here.
10987      if (!(IsLoad && IsOpLoad) &&
10988          isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
10989                  SrcValueAlign, SrcTBAAInfo,
10990                  OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
10991                  OpSrcValueAlign, OpSrcTBAAInfo)) {
10992        Aliases.push_back(Chain);
10993      } else {
10994        // Look further up the chain.
10995        Chains.push_back(Chain.getOperand(0));
10996        ++Depth;
10997      }
10998      break;
10999    }
11000
11001    case ISD::TokenFactor:
11002      // We have to check each of the operands of the token factor for "small"
11003      // token factors, so we queue them up.  Adding the operands to the queue
11004      // (stack) in reverse order maintains the original order and increases the
11005      // likelihood that getNode will find a matching token factor (CSE.)
11006      if (Chain.getNumOperands() > 16) {
11007        Aliases.push_back(Chain);
11008        break;
11009      }
11010      for (unsigned n = Chain.getNumOperands(); n;)
11011        Chains.push_back(Chain.getOperand(--n));
11012      ++Depth;
11013      break;
11014
11015    default:
11016      // For all other instructions we will just have to take what we can get.
11017      Aliases.push_back(Chain);
11018      break;
11019    }
11020  }
11021}
11022
11023/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11024/// for a better chain (aliasing node.)
11025SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11026  SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11027
11028  // Accumulate all the aliases to this node.
11029  GatherAllAliases(N, OldChain, Aliases);
11030
11031  // If no operands then chain to entry token.
11032  if (Aliases.size() == 0)
11033    return DAG.getEntryNode();
11034
11035  // If a single operand then chain to it.  We don't need to revisit it.
11036  if (Aliases.size() == 1)
11037    return Aliases[0];
11038
11039  // Construct a custom tailored token factor.
11040  return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11041                     &Aliases[0], Aliases.size());
11042}
11043
11044// SelectionDAG::Combine - This is the entry point for the file.
11045//
11046void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11047                           CodeGenOpt::Level OptLevel) {
11048  /// run - This is the main entry point to this class.
11049  ///
11050  DAGCombiner(*this, AA, OptLevel).Run(Level);
11051}
11052