DAGCombiner.cpp revision bc7d448f242b1bbc1031fb87cd69c285ff9aaffa
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11// both before and after the DAG is legalized.
12//
13// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
17//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "dagcombine"
20#include "llvm/CodeGen/SelectionDAG.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/LLVMContext.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/Analysis/AliasAnalysis.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetOptions.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/ErrorHandling.h"
35#include "llvm/Support/MathExtras.h"
36#include "llvm/Support/raw_ostream.h"
37#include <algorithm>
38using namespace llvm;
39
40STATISTIC(NodesCombined   , "Number of dag nodes combined");
41STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
42STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
43STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
44STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
45
46namespace {
47  static cl::opt<bool>
48    CombinerAA("combiner-alias-analysis", cl::Hidden,
49               cl::desc("Turn on alias analysis during testing"));
50
51  static cl::opt<bool>
52    CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
53               cl::desc("Include global information in alias analysis"));
54
55//------------------------------ DAGCombiner ---------------------------------//
56
57  class DAGCombiner {
58    SelectionDAG &DAG;
59    const TargetLowering &TLI;
60    CombineLevel Level;
61    CodeGenOpt::Level OptLevel;
62    bool LegalOperations;
63    bool LegalTypes;
64
65    // Worklist of all of the nodes that need to be simplified.
66    //
67    // This has the semantics that when adding to the worklist,
68    // the item added must be next to be processed. It should
69    // also only appear once. The naive approach to this takes
70    // linear time.
71    //
72    // To reduce the insert/remove time to logarithmic, we use
73    // a set and a vector to maintain our worklist.
74    //
75    // The set contains the items on the worklist, but does not
76    // maintain the order they should be visited.
77    //
78    // The vector maintains the order nodes should be visited, but may
79    // contain duplicate or removed nodes. When choosing a node to
80    // visit, we pop off the order stack until we find an item that is
81    // also in the contents set. All operations are O(log N).
82    SmallPtrSet<SDNode*, 64> WorkListContents;
83    SmallVector<SDNode*, 64> WorkListOrder;
84
85    // AA - Used for DAG load/store alias analysis.
86    AliasAnalysis &AA;
87
88    /// AddUsersToWorkList - When an instruction is simplified, add all users of
89    /// the instruction to the work lists because they might get more simplified
90    /// now.
91    ///
92    void AddUsersToWorkList(SDNode *N) {
93      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
94           UI != UE; ++UI)
95        AddToWorkList(*UI);
96    }
97
98    /// visit - call the node-specific routine that knows how to fold each
99    /// particular type of node.
100    SDValue visit(SDNode *N);
101
102  public:
103    /// AddToWorkList - Add to the work list making sure its instance is at the
104    /// back (next to be processed.)
105    void AddToWorkList(SDNode *N) {
106      WorkListContents.insert(N);
107      WorkListOrder.push_back(N);
108    }
109
110    /// removeFromWorkList - remove all instances of N from the worklist.
111    ///
112    void removeFromWorkList(SDNode *N) {
113      WorkListContents.erase(N);
114    }
115
116    SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
117                      bool AddTo = true);
118
119    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
120      return CombineTo(N, &Res, 1, AddTo);
121    }
122
123    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
124                      bool AddTo = true) {
125      SDValue To[] = { Res0, Res1 };
126      return CombineTo(N, To, 2, AddTo);
127    }
128
129    void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
130
131  private:
132
133    /// SimplifyDemandedBits - Check the specified integer node value to see if
134    /// it can be simplified or if things it uses can be simplified by bit
135    /// propagation.  If so, return true.
136    bool SimplifyDemandedBits(SDValue Op) {
137      unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
138      APInt Demanded = APInt::getAllOnesValue(BitWidth);
139      return SimplifyDemandedBits(Op, Demanded);
140    }
141
142    bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
143
144    bool CombineToPreIndexedLoadStore(SDNode *N);
145    bool CombineToPostIndexedLoadStore(SDNode *N);
146
147    void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
148    SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
149    SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
150    SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
151    SDValue PromoteIntBinOp(SDValue Op);
152    SDValue PromoteIntShiftOp(SDValue Op);
153    SDValue PromoteExtend(SDValue Op);
154    bool PromoteLoad(SDValue Op);
155
156    void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
157                         SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
158                         ISD::NodeType ExtType);
159
160    /// combine - call the node-specific routine that knows how to fold each
161    /// particular type of node. If that doesn't do anything, try the
162    /// target-specific DAG combines.
163    SDValue combine(SDNode *N);
164
165    // Visitation implementation - Implement dag node combining for different
166    // node types.  The semantics are as follows:
167    // Return Value:
168    //   SDValue.getNode() == 0 - No change was made
169    //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
170    //   otherwise              - N should be replaced by the returned Operand.
171    //
172    SDValue visitTokenFactor(SDNode *N);
173    SDValue visitMERGE_VALUES(SDNode *N);
174    SDValue visitADD(SDNode *N);
175    SDValue visitSUB(SDNode *N);
176    SDValue visitADDC(SDNode *N);
177    SDValue visitSUBC(SDNode *N);
178    SDValue visitADDE(SDNode *N);
179    SDValue visitSUBE(SDNode *N);
180    SDValue visitMUL(SDNode *N);
181    SDValue visitSDIV(SDNode *N);
182    SDValue visitUDIV(SDNode *N);
183    SDValue visitSREM(SDNode *N);
184    SDValue visitUREM(SDNode *N);
185    SDValue visitMULHU(SDNode *N);
186    SDValue visitMULHS(SDNode *N);
187    SDValue visitSMUL_LOHI(SDNode *N);
188    SDValue visitUMUL_LOHI(SDNode *N);
189    SDValue visitSMULO(SDNode *N);
190    SDValue visitUMULO(SDNode *N);
191    SDValue visitSDIVREM(SDNode *N);
192    SDValue visitUDIVREM(SDNode *N);
193    SDValue visitAND(SDNode *N);
194    SDValue visitOR(SDNode *N);
195    SDValue visitXOR(SDNode *N);
196    SDValue SimplifyVBinOp(SDNode *N);
197    SDValue visitSHL(SDNode *N);
198    SDValue visitSRA(SDNode *N);
199    SDValue visitSRL(SDNode *N);
200    SDValue visitCTLZ(SDNode *N);
201    SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
202    SDValue visitCTTZ(SDNode *N);
203    SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
204    SDValue visitCTPOP(SDNode *N);
205    SDValue visitSELECT(SDNode *N);
206    SDValue visitSELECT_CC(SDNode *N);
207    SDValue visitSETCC(SDNode *N);
208    SDValue visitSIGN_EXTEND(SDNode *N);
209    SDValue visitZERO_EXTEND(SDNode *N);
210    SDValue visitANY_EXTEND(SDNode *N);
211    SDValue visitSIGN_EXTEND_INREG(SDNode *N);
212    SDValue visitTRUNCATE(SDNode *N);
213    SDValue visitBITCAST(SDNode *N);
214    SDValue visitBUILD_PAIR(SDNode *N);
215    SDValue visitFADD(SDNode *N);
216    SDValue visitFSUB(SDNode *N);
217    SDValue visitFMUL(SDNode *N);
218    SDValue visitFDIV(SDNode *N);
219    SDValue visitFREM(SDNode *N);
220    SDValue visitFCOPYSIGN(SDNode *N);
221    SDValue visitSINT_TO_FP(SDNode *N);
222    SDValue visitUINT_TO_FP(SDNode *N);
223    SDValue visitFP_TO_SINT(SDNode *N);
224    SDValue visitFP_TO_UINT(SDNode *N);
225    SDValue visitFP_ROUND(SDNode *N);
226    SDValue visitFP_ROUND_INREG(SDNode *N);
227    SDValue visitFP_EXTEND(SDNode *N);
228    SDValue visitFNEG(SDNode *N);
229    SDValue visitFABS(SDNode *N);
230    SDValue visitBRCOND(SDNode *N);
231    SDValue visitBR_CC(SDNode *N);
232    SDValue visitLOAD(SDNode *N);
233    SDValue visitSTORE(SDNode *N);
234    SDValue visitINSERT_VECTOR_ELT(SDNode *N);
235    SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
236    SDValue visitBUILD_VECTOR(SDNode *N);
237    SDValue visitCONCAT_VECTORS(SDNode *N);
238    SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
239    SDValue visitVECTOR_SHUFFLE(SDNode *N);
240    SDValue visitMEMBARRIER(SDNode *N);
241
242    SDValue XformToShuffleWithZero(SDNode *N);
243    SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
244
245    SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
246
247    bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
248    SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
249    SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
250    SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
251                             SDValue N3, ISD::CondCode CC,
252                             bool NotExtCompare = false);
253    SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
254                          DebugLoc DL, bool foldBooleans = true);
255    SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
256                                         unsigned HiOp);
257    SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
258    SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
259    SDValue BuildSDIV(SDNode *N);
260    SDValue BuildUDIV(SDNode *N);
261    SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
262                               bool DemandHighBits = true);
263    SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
264    SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
265    SDValue ReduceLoadWidth(SDNode *N);
266    SDValue ReduceLoadOpStoreWidth(SDNode *N);
267    SDValue TransformFPLoadStorePair(SDNode *N);
268
269    SDValue GetDemandedBits(SDValue V, const APInt &Mask);
270
271    /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
272    /// looking for aliasing nodes and adding them to the Aliases vector.
273    void GatherAllAliases(SDNode *N, SDValue OriginalChain,
274                          SmallVector<SDValue, 8> &Aliases);
275
276    /// isAlias - Return true if there is any possibility that the two addresses
277    /// overlap.
278    bool isAlias(SDValue Ptr1, int64_t Size1,
279                 const Value *SrcValue1, int SrcValueOffset1,
280                 unsigned SrcValueAlign1,
281                 const MDNode *TBAAInfo1,
282                 SDValue Ptr2, int64_t Size2,
283                 const Value *SrcValue2, int SrcValueOffset2,
284                 unsigned SrcValueAlign2,
285                 const MDNode *TBAAInfo2) const;
286
287    /// FindAliasInfo - Extracts the relevant alias information from the memory
288    /// node.  Returns true if the operand was a load.
289    bool FindAliasInfo(SDNode *N,
290                       SDValue &Ptr, int64_t &Size,
291                       const Value *&SrcValue, int &SrcValueOffset,
292                       unsigned &SrcValueAlignment,
293                       const MDNode *&TBAAInfo) const;
294
295    /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
296    /// looking for a better chain (aliasing node.)
297    SDValue FindBetterChain(SDNode *N, SDValue Chain);
298
299  public:
300    DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
301      : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
302        OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
303
304    /// Run - runs the dag combiner on all nodes in the work list
305    void Run(CombineLevel AtLevel);
306
307    SelectionDAG &getDAG() const { return DAG; }
308
309    /// getShiftAmountTy - Returns a type large enough to hold any valid
310    /// shift amount - before type legalization these can be huge.
311    EVT getShiftAmountTy(EVT LHSTy) {
312      return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
313    }
314
315    /// isTypeLegal - This method returns true if we are running before type
316    /// legalization or if the specified VT is legal.
317    bool isTypeLegal(const EVT &VT) {
318      if (!LegalTypes) return true;
319      return TLI.isTypeLegal(VT);
320    }
321  };
322}
323
324
325namespace {
326/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
327/// nodes from the worklist.
328class WorkListRemover : public SelectionDAG::DAGUpdateListener {
329  DAGCombiner &DC;
330public:
331  explicit WorkListRemover(DAGCombiner &dc)
332    : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
333
334  virtual void NodeDeleted(SDNode *N, SDNode *E) {
335    DC.removeFromWorkList(N);
336  }
337};
338}
339
340//===----------------------------------------------------------------------===//
341//  TargetLowering::DAGCombinerInfo implementation
342//===----------------------------------------------------------------------===//
343
344void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
345  ((DAGCombiner*)DC)->AddToWorkList(N);
346}
347
348void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
349  ((DAGCombiner*)DC)->removeFromWorkList(N);
350}
351
352SDValue TargetLowering::DAGCombinerInfo::
353CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
354  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
355}
356
357SDValue TargetLowering::DAGCombinerInfo::
358CombineTo(SDNode *N, SDValue Res, bool AddTo) {
359  return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
360}
361
362
363SDValue TargetLowering::DAGCombinerInfo::
364CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
365  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
366}
367
368void TargetLowering::DAGCombinerInfo::
369CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
370  return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
371}
372
373//===----------------------------------------------------------------------===//
374// Helper Functions
375//===----------------------------------------------------------------------===//
376
377/// isNegatibleForFree - Return 1 if we can compute the negated form of the
378/// specified expression for the same cost as the expression itself, or 2 if we
379/// can compute the negated form more cheaply than the expression itself.
380static char isNegatibleForFree(SDValue Op, bool LegalOperations,
381                               const TargetLowering &TLI,
382                               const TargetOptions *Options,
383                               unsigned Depth = 0) {
384  // No compile time optimizations on this type.
385  if (Op.getValueType() == MVT::ppcf128)
386    return 0;
387
388  // fneg is removable even if it has multiple uses.
389  if (Op.getOpcode() == ISD::FNEG) return 2;
390
391  // Don't allow anything with multiple uses.
392  if (!Op.hasOneUse()) return 0;
393
394  // Don't recurse exponentially.
395  if (Depth > 6) return 0;
396
397  switch (Op.getOpcode()) {
398  default: return false;
399  case ISD::ConstantFP:
400    // Don't invert constant FP values after legalize.  The negated constant
401    // isn't necessarily legal.
402    return LegalOperations ? 0 : 1;
403  case ISD::FADD:
404    // FIXME: determine better conditions for this xform.
405    if (!Options->UnsafeFPMath) return 0;
406
407    // After operation legalization, it might not be legal to create new FSUBs.
408    if (LegalOperations &&
409        !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
410      return 0;
411
412    // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
413    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
414                                    Options, Depth + 1))
415      return V;
416    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
417    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
418                              Depth + 1);
419  case ISD::FSUB:
420    // We can't turn -(A-B) into B-A when we honor signed zeros.
421    if (!Options->UnsafeFPMath) return 0;
422
423    // fold (fneg (fsub A, B)) -> (fsub B, A)
424    return 1;
425
426  case ISD::FMUL:
427  case ISD::FDIV:
428    if (Options->HonorSignDependentRoundingFPMath()) return 0;
429
430    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
431    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
432                                    Options, Depth + 1))
433      return V;
434
435    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
436                              Depth + 1);
437
438  case ISD::FP_EXTEND:
439  case ISD::FP_ROUND:
440  case ISD::FSIN:
441    return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
442                              Depth + 1);
443  }
444}
445
446/// GetNegatedExpression - If isNegatibleForFree returns true, this function
447/// returns the newly negated expression.
448static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
449                                    bool LegalOperations, unsigned Depth = 0) {
450  // fneg is removable even if it has multiple uses.
451  if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
452
453  // Don't allow anything with multiple uses.
454  assert(Op.hasOneUse() && "Unknown reuse!");
455
456  assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
457  switch (Op.getOpcode()) {
458  default: llvm_unreachable("Unknown code");
459  case ISD::ConstantFP: {
460    APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
461    V.changeSign();
462    return DAG.getConstantFP(V, Op.getValueType());
463  }
464  case ISD::FADD:
465    // FIXME: determine better conditions for this xform.
466    assert(DAG.getTarget().Options.UnsafeFPMath);
467
468    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
469    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
470                           DAG.getTargetLoweringInfo(),
471                           &DAG.getTarget().Options, Depth+1))
472      return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
473                         GetNegatedExpression(Op.getOperand(0), DAG,
474                                              LegalOperations, Depth+1),
475                         Op.getOperand(1));
476    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
477    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
478                       GetNegatedExpression(Op.getOperand(1), DAG,
479                                            LegalOperations, Depth+1),
480                       Op.getOperand(0));
481  case ISD::FSUB:
482    // We can't turn -(A-B) into B-A when we honor signed zeros.
483    assert(DAG.getTarget().Options.UnsafeFPMath);
484
485    // fold (fneg (fsub 0, B)) -> B
486    if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
487      if (N0CFP->getValueAPF().isZero())
488        return Op.getOperand(1);
489
490    // fold (fneg (fsub A, B)) -> (fsub B, A)
491    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
492                       Op.getOperand(1), Op.getOperand(0));
493
494  case ISD::FMUL:
495  case ISD::FDIV:
496    assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
497
498    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
499    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
500                           DAG.getTargetLoweringInfo(),
501                           &DAG.getTarget().Options, Depth+1))
502      return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
503                         GetNegatedExpression(Op.getOperand(0), DAG,
504                                              LegalOperations, Depth+1),
505                         Op.getOperand(1));
506
507    // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
508    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
509                       Op.getOperand(0),
510                       GetNegatedExpression(Op.getOperand(1), DAG,
511                                            LegalOperations, Depth+1));
512
513  case ISD::FP_EXTEND:
514  case ISD::FSIN:
515    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
516                       GetNegatedExpression(Op.getOperand(0), DAG,
517                                            LegalOperations, Depth+1));
518  case ISD::FP_ROUND:
519      return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
520                         GetNegatedExpression(Op.getOperand(0), DAG,
521                                              LegalOperations, Depth+1),
522                         Op.getOperand(1));
523  }
524}
525
526
527// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
528// that selects between the values 1 and 0, making it equivalent to a setcc.
529// Also, set the incoming LHS, RHS, and CC references to the appropriate
530// nodes based on the type of node we are checking.  This simplifies life a
531// bit for the callers.
532static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
533                              SDValue &CC) {
534  if (N.getOpcode() == ISD::SETCC) {
535    LHS = N.getOperand(0);
536    RHS = N.getOperand(1);
537    CC  = N.getOperand(2);
538    return true;
539  }
540  if (N.getOpcode() == ISD::SELECT_CC &&
541      N.getOperand(2).getOpcode() == ISD::Constant &&
542      N.getOperand(3).getOpcode() == ISD::Constant &&
543      cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
544      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
545    LHS = N.getOperand(0);
546    RHS = N.getOperand(1);
547    CC  = N.getOperand(4);
548    return true;
549  }
550  return false;
551}
552
553// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
554// one use.  If this is true, it allows the users to invert the operation for
555// free when it is profitable to do so.
556static bool isOneUseSetCC(SDValue N) {
557  SDValue N0, N1, N2;
558  if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
559    return true;
560  return false;
561}
562
563SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
564                                    SDValue N0, SDValue N1) {
565  EVT VT = N0.getValueType();
566  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
567    if (isa<ConstantSDNode>(N1)) {
568      // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
569      SDValue OpNode =
570        DAG.FoldConstantArithmetic(Opc, VT,
571                                   cast<ConstantSDNode>(N0.getOperand(1)),
572                                   cast<ConstantSDNode>(N1));
573      return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
574    }
575    if (N0.hasOneUse()) {
576      // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
577      SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
578                                   N0.getOperand(0), N1);
579      AddToWorkList(OpNode.getNode());
580      return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
581    }
582  }
583
584  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
585    if (isa<ConstantSDNode>(N0)) {
586      // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
587      SDValue OpNode =
588        DAG.FoldConstantArithmetic(Opc, VT,
589                                   cast<ConstantSDNode>(N1.getOperand(1)),
590                                   cast<ConstantSDNode>(N0));
591      return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
592    }
593    if (N1.hasOneUse()) {
594      // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
595      SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
596                                   N1.getOperand(0), N0);
597      AddToWorkList(OpNode.getNode());
598      return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
599    }
600  }
601
602  return SDValue();
603}
604
605SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
606                               bool AddTo) {
607  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
608  ++NodesCombined;
609  DEBUG(dbgs() << "\nReplacing.1 ";
610        N->dump(&DAG);
611        dbgs() << "\nWith: ";
612        To[0].getNode()->dump(&DAG);
613        dbgs() << " and " << NumTo-1 << " other values\n";
614        for (unsigned i = 0, e = NumTo; i != e; ++i)
615          assert((!To[i].getNode() ||
616                  N->getValueType(i) == To[i].getValueType()) &&
617                 "Cannot combine value to value of different type!"));
618  WorkListRemover DeadNodes(*this);
619  DAG.ReplaceAllUsesWith(N, To);
620  if (AddTo) {
621    // Push the new nodes and any users onto the worklist
622    for (unsigned i = 0, e = NumTo; i != e; ++i) {
623      if (To[i].getNode()) {
624        AddToWorkList(To[i].getNode());
625        AddUsersToWorkList(To[i].getNode());
626      }
627    }
628  }
629
630  // Finally, if the node is now dead, remove it from the graph.  The node
631  // may not be dead if the replacement process recursively simplified to
632  // something else needing this node.
633  if (N->use_empty()) {
634    // Nodes can be reintroduced into the worklist.  Make sure we do not
635    // process a node that has been replaced.
636    removeFromWorkList(N);
637
638    // Finally, since the node is now dead, remove it from the graph.
639    DAG.DeleteNode(N);
640  }
641  return SDValue(N, 0);
642}
643
644void DAGCombiner::
645CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
646  // Replace all uses.  If any nodes become isomorphic to other nodes and
647  // are deleted, make sure to remove them from our worklist.
648  WorkListRemover DeadNodes(*this);
649  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
650
651  // Push the new node and any (possibly new) users onto the worklist.
652  AddToWorkList(TLO.New.getNode());
653  AddUsersToWorkList(TLO.New.getNode());
654
655  // Finally, if the node is now dead, remove it from the graph.  The node
656  // may not be dead if the replacement process recursively simplified to
657  // something else needing this node.
658  if (TLO.Old.getNode()->use_empty()) {
659    removeFromWorkList(TLO.Old.getNode());
660
661    // If the operands of this node are only used by the node, they will now
662    // be dead.  Make sure to visit them first to delete dead nodes early.
663    for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
664      if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
665        AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
666
667    DAG.DeleteNode(TLO.Old.getNode());
668  }
669}
670
671/// SimplifyDemandedBits - Check the specified integer node value to see if
672/// it can be simplified or if things it uses can be simplified by bit
673/// propagation.  If so, return true.
674bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
675  TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
676  APInt KnownZero, KnownOne;
677  if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
678    return false;
679
680  // Revisit the node.
681  AddToWorkList(Op.getNode());
682
683  // Replace the old value with the new one.
684  ++NodesCombined;
685  DEBUG(dbgs() << "\nReplacing.2 ";
686        TLO.Old.getNode()->dump(&DAG);
687        dbgs() << "\nWith: ";
688        TLO.New.getNode()->dump(&DAG);
689        dbgs() << '\n');
690
691  CommitTargetLoweringOpt(TLO);
692  return true;
693}
694
695void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
696  DebugLoc dl = Load->getDebugLoc();
697  EVT VT = Load->getValueType(0);
698  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
699
700  DEBUG(dbgs() << "\nReplacing.9 ";
701        Load->dump(&DAG);
702        dbgs() << "\nWith: ";
703        Trunc.getNode()->dump(&DAG);
704        dbgs() << '\n');
705  WorkListRemover DeadNodes(*this);
706  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
707  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
708  removeFromWorkList(Load);
709  DAG.DeleteNode(Load);
710  AddToWorkList(Trunc.getNode());
711}
712
713SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
714  Replace = false;
715  DebugLoc dl = Op.getDebugLoc();
716  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
717    EVT MemVT = LD->getMemoryVT();
718    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
719      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
720                                                  : ISD::EXTLOAD)
721      : LD->getExtensionType();
722    Replace = true;
723    return DAG.getExtLoad(ExtType, dl, PVT,
724                          LD->getChain(), LD->getBasePtr(),
725                          LD->getPointerInfo(),
726                          MemVT, LD->isVolatile(),
727                          LD->isNonTemporal(), LD->getAlignment());
728  }
729
730  unsigned Opc = Op.getOpcode();
731  switch (Opc) {
732  default: break;
733  case ISD::AssertSext:
734    return DAG.getNode(ISD::AssertSext, dl, PVT,
735                       SExtPromoteOperand(Op.getOperand(0), PVT),
736                       Op.getOperand(1));
737  case ISD::AssertZext:
738    return DAG.getNode(ISD::AssertZext, dl, PVT,
739                       ZExtPromoteOperand(Op.getOperand(0), PVT),
740                       Op.getOperand(1));
741  case ISD::Constant: {
742    unsigned ExtOpc =
743      Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
744    return DAG.getNode(ExtOpc, dl, PVT, Op);
745  }
746  }
747
748  if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
749    return SDValue();
750  return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
751}
752
753SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
754  if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
755    return SDValue();
756  EVT OldVT = Op.getValueType();
757  DebugLoc dl = Op.getDebugLoc();
758  bool Replace = false;
759  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
760  if (NewOp.getNode() == 0)
761    return SDValue();
762  AddToWorkList(NewOp.getNode());
763
764  if (Replace)
765    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
766  return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
767                     DAG.getValueType(OldVT));
768}
769
770SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
771  EVT OldVT = Op.getValueType();
772  DebugLoc dl = Op.getDebugLoc();
773  bool Replace = false;
774  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
775  if (NewOp.getNode() == 0)
776    return SDValue();
777  AddToWorkList(NewOp.getNode());
778
779  if (Replace)
780    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
781  return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
782}
783
784/// PromoteIntBinOp - Promote the specified integer binary operation if the
785/// target indicates it is beneficial. e.g. On x86, it's usually better to
786/// promote i16 operations to i32 since i16 instructions are longer.
787SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
788  if (!LegalOperations)
789    return SDValue();
790
791  EVT VT = Op.getValueType();
792  if (VT.isVector() || !VT.isInteger())
793    return SDValue();
794
795  // If operation type is 'undesirable', e.g. i16 on x86, consider
796  // promoting it.
797  unsigned Opc = Op.getOpcode();
798  if (TLI.isTypeDesirableForOp(Opc, VT))
799    return SDValue();
800
801  EVT PVT = VT;
802  // Consult target whether it is a good idea to promote this operation and
803  // what's the right type to promote it to.
804  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
805    assert(PVT != VT && "Don't know what type to promote to!");
806
807    bool Replace0 = false;
808    SDValue N0 = Op.getOperand(0);
809    SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
810    if (NN0.getNode() == 0)
811      return SDValue();
812
813    bool Replace1 = false;
814    SDValue N1 = Op.getOperand(1);
815    SDValue NN1;
816    if (N0 == N1)
817      NN1 = NN0;
818    else {
819      NN1 = PromoteOperand(N1, PVT, Replace1);
820      if (NN1.getNode() == 0)
821        return SDValue();
822    }
823
824    AddToWorkList(NN0.getNode());
825    if (NN1.getNode())
826      AddToWorkList(NN1.getNode());
827
828    if (Replace0)
829      ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
830    if (Replace1)
831      ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
832
833    DEBUG(dbgs() << "\nPromoting ";
834          Op.getNode()->dump(&DAG));
835    DebugLoc dl = Op.getDebugLoc();
836    return DAG.getNode(ISD::TRUNCATE, dl, VT,
837                       DAG.getNode(Opc, dl, PVT, NN0, NN1));
838  }
839  return SDValue();
840}
841
842/// PromoteIntShiftOp - Promote the specified integer shift operation if the
843/// target indicates it is beneficial. e.g. On x86, it's usually better to
844/// promote i16 operations to i32 since i16 instructions are longer.
845SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
846  if (!LegalOperations)
847    return SDValue();
848
849  EVT VT = Op.getValueType();
850  if (VT.isVector() || !VT.isInteger())
851    return SDValue();
852
853  // If operation type is 'undesirable', e.g. i16 on x86, consider
854  // promoting it.
855  unsigned Opc = Op.getOpcode();
856  if (TLI.isTypeDesirableForOp(Opc, VT))
857    return SDValue();
858
859  EVT PVT = VT;
860  // Consult target whether it is a good idea to promote this operation and
861  // what's the right type to promote it to.
862  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
863    assert(PVT != VT && "Don't know what type to promote to!");
864
865    bool Replace = false;
866    SDValue N0 = Op.getOperand(0);
867    if (Opc == ISD::SRA)
868      N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
869    else if (Opc == ISD::SRL)
870      N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
871    else
872      N0 = PromoteOperand(N0, PVT, Replace);
873    if (N0.getNode() == 0)
874      return SDValue();
875
876    AddToWorkList(N0.getNode());
877    if (Replace)
878      ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
879
880    DEBUG(dbgs() << "\nPromoting ";
881          Op.getNode()->dump(&DAG));
882    DebugLoc dl = Op.getDebugLoc();
883    return DAG.getNode(ISD::TRUNCATE, dl, VT,
884                       DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
885  }
886  return SDValue();
887}
888
889SDValue DAGCombiner::PromoteExtend(SDValue Op) {
890  if (!LegalOperations)
891    return SDValue();
892
893  EVT VT = Op.getValueType();
894  if (VT.isVector() || !VT.isInteger())
895    return SDValue();
896
897  // If operation type is 'undesirable', e.g. i16 on x86, consider
898  // promoting it.
899  unsigned Opc = Op.getOpcode();
900  if (TLI.isTypeDesirableForOp(Opc, VT))
901    return SDValue();
902
903  EVT PVT = VT;
904  // Consult target whether it is a good idea to promote this operation and
905  // what's the right type to promote it to.
906  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
907    assert(PVT != VT && "Don't know what type to promote to!");
908    // fold (aext (aext x)) -> (aext x)
909    // fold (aext (zext x)) -> (zext x)
910    // fold (aext (sext x)) -> (sext x)
911    DEBUG(dbgs() << "\nPromoting ";
912          Op.getNode()->dump(&DAG));
913    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
914  }
915  return SDValue();
916}
917
918bool DAGCombiner::PromoteLoad(SDValue Op) {
919  if (!LegalOperations)
920    return false;
921
922  EVT VT = Op.getValueType();
923  if (VT.isVector() || !VT.isInteger())
924    return false;
925
926  // If operation type is 'undesirable', e.g. i16 on x86, consider
927  // promoting it.
928  unsigned Opc = Op.getOpcode();
929  if (TLI.isTypeDesirableForOp(Opc, VT))
930    return false;
931
932  EVT PVT = VT;
933  // Consult target whether it is a good idea to promote this operation and
934  // what's the right type to promote it to.
935  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
936    assert(PVT != VT && "Don't know what type to promote to!");
937
938    DebugLoc dl = Op.getDebugLoc();
939    SDNode *N = Op.getNode();
940    LoadSDNode *LD = cast<LoadSDNode>(N);
941    EVT MemVT = LD->getMemoryVT();
942    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
943      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
944                                                  : ISD::EXTLOAD)
945      : LD->getExtensionType();
946    SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
947                                   LD->getChain(), LD->getBasePtr(),
948                                   LD->getPointerInfo(),
949                                   MemVT, LD->isVolatile(),
950                                   LD->isNonTemporal(), LD->getAlignment());
951    SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
952
953    DEBUG(dbgs() << "\nPromoting ";
954          N->dump(&DAG);
955          dbgs() << "\nTo: ";
956          Result.getNode()->dump(&DAG);
957          dbgs() << '\n');
958    WorkListRemover DeadNodes(*this);
959    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
960    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
961    removeFromWorkList(N);
962    DAG.DeleteNode(N);
963    AddToWorkList(Result.getNode());
964    return true;
965  }
966  return false;
967}
968
969
970//===----------------------------------------------------------------------===//
971//  Main DAG Combiner implementation
972//===----------------------------------------------------------------------===//
973
974void DAGCombiner::Run(CombineLevel AtLevel) {
975  // set the instance variables, so that the various visit routines may use it.
976  Level = AtLevel;
977  LegalOperations = Level >= AfterLegalizeVectorOps;
978  LegalTypes = Level >= AfterLegalizeTypes;
979
980  // Add all the dag nodes to the worklist.
981  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
982       E = DAG.allnodes_end(); I != E; ++I)
983    AddToWorkList(I);
984
985  // Create a dummy node (which is not added to allnodes), that adds a reference
986  // to the root node, preventing it from being deleted, and tracking any
987  // changes of the root.
988  HandleSDNode Dummy(DAG.getRoot());
989
990  // The root of the dag may dangle to deleted nodes until the dag combiner is
991  // done.  Set it to null to avoid confusion.
992  DAG.setRoot(SDValue());
993
994  // while the worklist isn't empty, find a node and
995  // try and combine it.
996  while (!WorkListContents.empty()) {
997    SDNode *N;
998    // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
999    // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1000    // worklist *should* contain, and check the node we want to visit is should
1001    // actually be visited.
1002    do {
1003      N = WorkListOrder.pop_back_val();
1004    } while (!WorkListContents.erase(N));
1005
1006    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1007    // N is deleted from the DAG, since they too may now be dead or may have a
1008    // reduced number of uses, allowing other xforms.
1009    if (N->use_empty() && N != &Dummy) {
1010      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1011        AddToWorkList(N->getOperand(i).getNode());
1012
1013      DAG.DeleteNode(N);
1014      continue;
1015    }
1016
1017    SDValue RV = combine(N);
1018
1019    if (RV.getNode() == 0)
1020      continue;
1021
1022    ++NodesCombined;
1023
1024    // If we get back the same node we passed in, rather than a new node or
1025    // zero, we know that the node must have defined multiple values and
1026    // CombineTo was used.  Since CombineTo takes care of the worklist
1027    // mechanics for us, we have no work to do in this case.
1028    if (RV.getNode() == N)
1029      continue;
1030
1031    assert(N->getOpcode() != ISD::DELETED_NODE &&
1032           RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1033           "Node was deleted but visit returned new node!");
1034
1035    DEBUG(dbgs() << "\nReplacing.3 ";
1036          N->dump(&DAG);
1037          dbgs() << "\nWith: ";
1038          RV.getNode()->dump(&DAG);
1039          dbgs() << '\n');
1040
1041    // Transfer debug value.
1042    DAG.TransferDbgValues(SDValue(N, 0), RV);
1043    WorkListRemover DeadNodes(*this);
1044    if (N->getNumValues() == RV.getNode()->getNumValues())
1045      DAG.ReplaceAllUsesWith(N, RV.getNode());
1046    else {
1047      assert(N->getValueType(0) == RV.getValueType() &&
1048             N->getNumValues() == 1 && "Type mismatch");
1049      SDValue OpV = RV;
1050      DAG.ReplaceAllUsesWith(N, &OpV);
1051    }
1052
1053    // Push the new node and any users onto the worklist
1054    AddToWorkList(RV.getNode());
1055    AddUsersToWorkList(RV.getNode());
1056
1057    // Add any uses of the old node to the worklist in case this node is the
1058    // last one that uses them.  They may become dead after this node is
1059    // deleted.
1060    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1061      AddToWorkList(N->getOperand(i).getNode());
1062
1063    // Finally, if the node is now dead, remove it from the graph.  The node
1064    // may not be dead if the replacement process recursively simplified to
1065    // something else needing this node.
1066    if (N->use_empty()) {
1067      // Nodes can be reintroduced into the worklist.  Make sure we do not
1068      // process a node that has been replaced.
1069      removeFromWorkList(N);
1070
1071      // Finally, since the node is now dead, remove it from the graph.
1072      DAG.DeleteNode(N);
1073    }
1074  }
1075
1076  // If the root changed (e.g. it was a dead load, update the root).
1077  DAG.setRoot(Dummy.getValue());
1078  DAG.RemoveDeadNodes();
1079}
1080
1081SDValue DAGCombiner::visit(SDNode *N) {
1082  switch (N->getOpcode()) {
1083  default: break;
1084  case ISD::TokenFactor:        return visitTokenFactor(N);
1085  case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1086  case ISD::ADD:                return visitADD(N);
1087  case ISD::SUB:                return visitSUB(N);
1088  case ISD::ADDC:               return visitADDC(N);
1089  case ISD::SUBC:               return visitSUBC(N);
1090  case ISD::ADDE:               return visitADDE(N);
1091  case ISD::SUBE:               return visitSUBE(N);
1092  case ISD::MUL:                return visitMUL(N);
1093  case ISD::SDIV:               return visitSDIV(N);
1094  case ISD::UDIV:               return visitUDIV(N);
1095  case ISD::SREM:               return visitSREM(N);
1096  case ISD::UREM:               return visitUREM(N);
1097  case ISD::MULHU:              return visitMULHU(N);
1098  case ISD::MULHS:              return visitMULHS(N);
1099  case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1100  case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1101  case ISD::SMULO:              return visitSMULO(N);
1102  case ISD::UMULO:              return visitUMULO(N);
1103  case ISD::SDIVREM:            return visitSDIVREM(N);
1104  case ISD::UDIVREM:            return visitUDIVREM(N);
1105  case ISD::AND:                return visitAND(N);
1106  case ISD::OR:                 return visitOR(N);
1107  case ISD::XOR:                return visitXOR(N);
1108  case ISD::SHL:                return visitSHL(N);
1109  case ISD::SRA:                return visitSRA(N);
1110  case ISD::SRL:                return visitSRL(N);
1111  case ISD::CTLZ:               return visitCTLZ(N);
1112  case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1113  case ISD::CTTZ:               return visitCTTZ(N);
1114  case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1115  case ISD::CTPOP:              return visitCTPOP(N);
1116  case ISD::SELECT:             return visitSELECT(N);
1117  case ISD::SELECT_CC:          return visitSELECT_CC(N);
1118  case ISD::SETCC:              return visitSETCC(N);
1119  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1120  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1121  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1122  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1123  case ISD::TRUNCATE:           return visitTRUNCATE(N);
1124  case ISD::BITCAST:            return visitBITCAST(N);
1125  case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1126  case ISD::FADD:               return visitFADD(N);
1127  case ISD::FSUB:               return visitFSUB(N);
1128  case ISD::FMUL:               return visitFMUL(N);
1129  case ISD::FDIV:               return visitFDIV(N);
1130  case ISD::FREM:               return visitFREM(N);
1131  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1132  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1133  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1134  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1135  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1136  case ISD::FP_ROUND:           return visitFP_ROUND(N);
1137  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1138  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1139  case ISD::FNEG:               return visitFNEG(N);
1140  case ISD::FABS:               return visitFABS(N);
1141  case ISD::BRCOND:             return visitBRCOND(N);
1142  case ISD::BR_CC:              return visitBR_CC(N);
1143  case ISD::LOAD:               return visitLOAD(N);
1144  case ISD::STORE:              return visitSTORE(N);
1145  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1146  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1147  case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1148  case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1149  case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1150  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1151  case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1152  }
1153  return SDValue();
1154}
1155
1156SDValue DAGCombiner::combine(SDNode *N) {
1157  SDValue RV = visit(N);
1158
1159  // If nothing happened, try a target-specific DAG combine.
1160  if (RV.getNode() == 0) {
1161    assert(N->getOpcode() != ISD::DELETED_NODE &&
1162           "Node was deleted but visit returned NULL!");
1163
1164    if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1165        TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1166
1167      // Expose the DAG combiner to the target combiner impls.
1168      TargetLowering::DAGCombinerInfo
1169        DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1170
1171      RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1172    }
1173  }
1174
1175  // If nothing happened still, try promoting the operation.
1176  if (RV.getNode() == 0) {
1177    switch (N->getOpcode()) {
1178    default: break;
1179    case ISD::ADD:
1180    case ISD::SUB:
1181    case ISD::MUL:
1182    case ISD::AND:
1183    case ISD::OR:
1184    case ISD::XOR:
1185      RV = PromoteIntBinOp(SDValue(N, 0));
1186      break;
1187    case ISD::SHL:
1188    case ISD::SRA:
1189    case ISD::SRL:
1190      RV = PromoteIntShiftOp(SDValue(N, 0));
1191      break;
1192    case ISD::SIGN_EXTEND:
1193    case ISD::ZERO_EXTEND:
1194    case ISD::ANY_EXTEND:
1195      RV = PromoteExtend(SDValue(N, 0));
1196      break;
1197    case ISD::LOAD:
1198      if (PromoteLoad(SDValue(N, 0)))
1199        RV = SDValue(N, 0);
1200      break;
1201    }
1202  }
1203
1204  // If N is a commutative binary node, try commuting it to enable more
1205  // sdisel CSE.
1206  if (RV.getNode() == 0 &&
1207      SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1208      N->getNumValues() == 1) {
1209    SDValue N0 = N->getOperand(0);
1210    SDValue N1 = N->getOperand(1);
1211
1212    // Constant operands are canonicalized to RHS.
1213    if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1214      SDValue Ops[] = { N1, N0 };
1215      SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1216                                            Ops, 2);
1217      if (CSENode)
1218        return SDValue(CSENode, 0);
1219    }
1220  }
1221
1222  return RV;
1223}
1224
1225/// getInputChainForNode - Given a node, return its input chain if it has one,
1226/// otherwise return a null sd operand.
1227static SDValue getInputChainForNode(SDNode *N) {
1228  if (unsigned NumOps = N->getNumOperands()) {
1229    if (N->getOperand(0).getValueType() == MVT::Other)
1230      return N->getOperand(0);
1231    else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1232      return N->getOperand(NumOps-1);
1233    for (unsigned i = 1; i < NumOps-1; ++i)
1234      if (N->getOperand(i).getValueType() == MVT::Other)
1235        return N->getOperand(i);
1236  }
1237  return SDValue();
1238}
1239
1240SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1241  // If N has two operands, where one has an input chain equal to the other,
1242  // the 'other' chain is redundant.
1243  if (N->getNumOperands() == 2) {
1244    if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1245      return N->getOperand(0);
1246    if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1247      return N->getOperand(1);
1248  }
1249
1250  SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1251  SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1252  SmallPtrSet<SDNode*, 16> SeenOps;
1253  bool Changed = false;             // If we should replace this token factor.
1254
1255  // Start out with this token factor.
1256  TFs.push_back(N);
1257
1258  // Iterate through token factors.  The TFs grows when new token factors are
1259  // encountered.
1260  for (unsigned i = 0; i < TFs.size(); ++i) {
1261    SDNode *TF = TFs[i];
1262
1263    // Check each of the operands.
1264    for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1265      SDValue Op = TF->getOperand(i);
1266
1267      switch (Op.getOpcode()) {
1268      case ISD::EntryToken:
1269        // Entry tokens don't need to be added to the list. They are
1270        // rededundant.
1271        Changed = true;
1272        break;
1273
1274      case ISD::TokenFactor:
1275        if (Op.hasOneUse() &&
1276            std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1277          // Queue up for processing.
1278          TFs.push_back(Op.getNode());
1279          // Clean up in case the token factor is removed.
1280          AddToWorkList(Op.getNode());
1281          Changed = true;
1282          break;
1283        }
1284        // Fall thru
1285
1286      default:
1287        // Only add if it isn't already in the list.
1288        if (SeenOps.insert(Op.getNode()))
1289          Ops.push_back(Op);
1290        else
1291          Changed = true;
1292        break;
1293      }
1294    }
1295  }
1296
1297  SDValue Result;
1298
1299  // If we've change things around then replace token factor.
1300  if (Changed) {
1301    if (Ops.empty()) {
1302      // The entry token is the only possible outcome.
1303      Result = DAG.getEntryNode();
1304    } else {
1305      // New and improved token factor.
1306      Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1307                           MVT::Other, &Ops[0], Ops.size());
1308    }
1309
1310    // Don't add users to work list.
1311    return CombineTo(N, Result, false);
1312  }
1313
1314  return Result;
1315}
1316
1317/// MERGE_VALUES can always be eliminated.
1318SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1319  WorkListRemover DeadNodes(*this);
1320  // Replacing results may cause a different MERGE_VALUES to suddenly
1321  // be CSE'd with N, and carry its uses with it. Iterate until no
1322  // uses remain, to ensure that the node can be safely deleted.
1323  do {
1324    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1325      DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1326  } while (!N->use_empty());
1327  removeFromWorkList(N);
1328  DAG.DeleteNode(N);
1329  return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1330}
1331
1332static
1333SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1334                              SelectionDAG &DAG) {
1335  EVT VT = N0.getValueType();
1336  SDValue N00 = N0.getOperand(0);
1337  SDValue N01 = N0.getOperand(1);
1338  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1339
1340  if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1341      isa<ConstantSDNode>(N00.getOperand(1))) {
1342    // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1343    N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1344                     DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1345                                 N00.getOperand(0), N01),
1346                     DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1347                                 N00.getOperand(1), N01));
1348    return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1349  }
1350
1351  return SDValue();
1352}
1353
1354SDValue DAGCombiner::visitADD(SDNode *N) {
1355  SDValue N0 = N->getOperand(0);
1356  SDValue N1 = N->getOperand(1);
1357  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1358  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1359  EVT VT = N0.getValueType();
1360
1361  // fold vector ops
1362  if (VT.isVector()) {
1363    SDValue FoldedVOp = SimplifyVBinOp(N);
1364    if (FoldedVOp.getNode()) return FoldedVOp;
1365  }
1366
1367  // fold (add x, undef) -> undef
1368  if (N0.getOpcode() == ISD::UNDEF)
1369    return N0;
1370  if (N1.getOpcode() == ISD::UNDEF)
1371    return N1;
1372  // fold (add c1, c2) -> c1+c2
1373  if (N0C && N1C)
1374    return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1375  // canonicalize constant to RHS
1376  if (N0C && !N1C)
1377    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1378  // fold (add x, 0) -> x
1379  if (N1C && N1C->isNullValue())
1380    return N0;
1381  // fold (add Sym, c) -> Sym+c
1382  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1383    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1384        GA->getOpcode() == ISD::GlobalAddress)
1385      return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1386                                  GA->getOffset() +
1387                                    (uint64_t)N1C->getSExtValue());
1388  // fold ((c1-A)+c2) -> (c1+c2)-A
1389  if (N1C && N0.getOpcode() == ISD::SUB)
1390    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1391      return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1392                         DAG.getConstant(N1C->getAPIntValue()+
1393                                         N0C->getAPIntValue(), VT),
1394                         N0.getOperand(1));
1395  // reassociate add
1396  SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1397  if (RADD.getNode() != 0)
1398    return RADD;
1399  // fold ((0-A) + B) -> B-A
1400  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1401      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1402    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1403  // fold (A + (0-B)) -> A-B
1404  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1405      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1406    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1407  // fold (A+(B-A)) -> B
1408  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1409    return N1.getOperand(0);
1410  // fold ((B-A)+A) -> B
1411  if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1412    return N0.getOperand(0);
1413  // fold (A+(B-(A+C))) to (B-C)
1414  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1415      N0 == N1.getOperand(1).getOperand(0))
1416    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1417                       N1.getOperand(1).getOperand(1));
1418  // fold (A+(B-(C+A))) to (B-C)
1419  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1420      N0 == N1.getOperand(1).getOperand(1))
1421    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1422                       N1.getOperand(1).getOperand(0));
1423  // fold (A+((B-A)+or-C)) to (B+or-C)
1424  if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1425      N1.getOperand(0).getOpcode() == ISD::SUB &&
1426      N0 == N1.getOperand(0).getOperand(1))
1427    return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1428                       N1.getOperand(0).getOperand(0), N1.getOperand(1));
1429
1430  // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1431  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1432    SDValue N00 = N0.getOperand(0);
1433    SDValue N01 = N0.getOperand(1);
1434    SDValue N10 = N1.getOperand(0);
1435    SDValue N11 = N1.getOperand(1);
1436
1437    if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1438      return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1439                         DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1440                         DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1441  }
1442
1443  if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1444    return SDValue(N, 0);
1445
1446  // fold (a+b) -> (a|b) iff a and b share no bits.
1447  if (VT.isInteger() && !VT.isVector()) {
1448    APInt LHSZero, LHSOne;
1449    APInt RHSZero, RHSOne;
1450    DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1451
1452    if (LHSZero.getBoolValue()) {
1453      DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1454
1455      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1456      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1457      if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1458        return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1459    }
1460  }
1461
1462  // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1463  if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1464    SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1465    if (Result.getNode()) return Result;
1466  }
1467  if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1468    SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1469    if (Result.getNode()) return Result;
1470  }
1471
1472  // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1473  if (N1.getOpcode() == ISD::SHL &&
1474      N1.getOperand(0).getOpcode() == ISD::SUB)
1475    if (ConstantSDNode *C =
1476          dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1477      if (C->getAPIntValue() == 0)
1478        return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1479                           DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1480                                       N1.getOperand(0).getOperand(1),
1481                                       N1.getOperand(1)));
1482  if (N0.getOpcode() == ISD::SHL &&
1483      N0.getOperand(0).getOpcode() == ISD::SUB)
1484    if (ConstantSDNode *C =
1485          dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1486      if (C->getAPIntValue() == 0)
1487        return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1488                           DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1489                                       N0.getOperand(0).getOperand(1),
1490                                       N0.getOperand(1)));
1491
1492  if (N1.getOpcode() == ISD::AND) {
1493    SDValue AndOp0 = N1.getOperand(0);
1494    ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1495    unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1496    unsigned DestBits = VT.getScalarType().getSizeInBits();
1497
1498    // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1499    // and similar xforms where the inner op is either ~0 or 0.
1500    if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1501      DebugLoc DL = N->getDebugLoc();
1502      return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1503    }
1504  }
1505
1506  // add (sext i1), X -> sub X, (zext i1)
1507  if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1508      N0.getOperand(0).getValueType() == MVT::i1 &&
1509      !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1510    DebugLoc DL = N->getDebugLoc();
1511    SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1512    return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1513  }
1514
1515  return SDValue();
1516}
1517
1518SDValue DAGCombiner::visitADDC(SDNode *N) {
1519  SDValue N0 = N->getOperand(0);
1520  SDValue N1 = N->getOperand(1);
1521  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1522  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1523  EVT VT = N0.getValueType();
1524
1525  // If the flag result is dead, turn this into an ADD.
1526  if (!N->hasAnyUseOfValue(1))
1527    return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1528                     DAG.getNode(ISD::CARRY_FALSE,
1529                                 N->getDebugLoc(), MVT::Glue));
1530
1531  // canonicalize constant to RHS.
1532  if (N0C && !N1C)
1533    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1534
1535  // fold (addc x, 0) -> x + no carry out
1536  if (N1C && N1C->isNullValue())
1537    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1538                                        N->getDebugLoc(), MVT::Glue));
1539
1540  // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1541  APInt LHSZero, LHSOne;
1542  APInt RHSZero, RHSOne;
1543  DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1544
1545  if (LHSZero.getBoolValue()) {
1546    DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1547
1548    // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1549    // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1550    if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1551      return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1552                       DAG.getNode(ISD::CARRY_FALSE,
1553                                   N->getDebugLoc(), MVT::Glue));
1554  }
1555
1556  return SDValue();
1557}
1558
1559SDValue DAGCombiner::visitADDE(SDNode *N) {
1560  SDValue N0 = N->getOperand(0);
1561  SDValue N1 = N->getOperand(1);
1562  SDValue CarryIn = N->getOperand(2);
1563  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1564  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1565
1566  // canonicalize constant to RHS
1567  if (N0C && !N1C)
1568    return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1569                       N1, N0, CarryIn);
1570
1571  // fold (adde x, y, false) -> (addc x, y)
1572  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1573    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1574
1575  return SDValue();
1576}
1577
1578// Since it may not be valid to emit a fold to zero for vector initializers
1579// check if we can before folding.
1580static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1581                             SelectionDAG &DAG, bool LegalOperations) {
1582  if (!VT.isVector()) {
1583    return DAG.getConstant(0, VT);
1584  }
1585  if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1586    // Produce a vector of zeros.
1587    SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1588    std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1589    return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1590      &Ops[0], Ops.size());
1591  }
1592  return SDValue();
1593}
1594
1595SDValue DAGCombiner::visitSUB(SDNode *N) {
1596  SDValue N0 = N->getOperand(0);
1597  SDValue N1 = N->getOperand(1);
1598  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1599  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1600  ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1601    dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1602  EVT VT = N0.getValueType();
1603
1604  // fold vector ops
1605  if (VT.isVector()) {
1606    SDValue FoldedVOp = SimplifyVBinOp(N);
1607    if (FoldedVOp.getNode()) return FoldedVOp;
1608  }
1609
1610  // fold (sub x, x) -> 0
1611  // FIXME: Refactor this and xor and other similar operations together.
1612  if (N0 == N1)
1613    return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1614  // fold (sub c1, c2) -> c1-c2
1615  if (N0C && N1C)
1616    return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1617  // fold (sub x, c) -> (add x, -c)
1618  if (N1C)
1619    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1620                       DAG.getConstant(-N1C->getAPIntValue(), VT));
1621  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1622  if (N0C && N0C->isAllOnesValue())
1623    return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1624  // fold A-(A-B) -> B
1625  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1626    return N1.getOperand(1);
1627  // fold (A+B)-A -> B
1628  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1629    return N0.getOperand(1);
1630  // fold (A+B)-B -> A
1631  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1632    return N0.getOperand(0);
1633  // fold C2-(A+C1) -> (C2-C1)-A
1634  if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1635    SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
1636    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1637		       N1.getOperand(0));
1638  }
1639  // fold ((A+(B+or-C))-B) -> A+or-C
1640  if (N0.getOpcode() == ISD::ADD &&
1641      (N0.getOperand(1).getOpcode() == ISD::SUB ||
1642       N0.getOperand(1).getOpcode() == ISD::ADD) &&
1643      N0.getOperand(1).getOperand(0) == N1)
1644    return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1645                       N0.getOperand(0), N0.getOperand(1).getOperand(1));
1646  // fold ((A+(C+B))-B) -> A+C
1647  if (N0.getOpcode() == ISD::ADD &&
1648      N0.getOperand(1).getOpcode() == ISD::ADD &&
1649      N0.getOperand(1).getOperand(1) == N1)
1650    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1651                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1652  // fold ((A-(B-C))-C) -> A-B
1653  if (N0.getOpcode() == ISD::SUB &&
1654      N0.getOperand(1).getOpcode() == ISD::SUB &&
1655      N0.getOperand(1).getOperand(1) == N1)
1656    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1657                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1658
1659  // If either operand of a sub is undef, the result is undef
1660  if (N0.getOpcode() == ISD::UNDEF)
1661    return N0;
1662  if (N1.getOpcode() == ISD::UNDEF)
1663    return N1;
1664
1665  // If the relocation model supports it, consider symbol offsets.
1666  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1667    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1668      // fold (sub Sym, c) -> Sym-c
1669      if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1670        return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1671                                    GA->getOffset() -
1672                                      (uint64_t)N1C->getSExtValue());
1673      // fold (sub Sym+c1, Sym+c2) -> c1-c2
1674      if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1675        if (GA->getGlobal() == GB->getGlobal())
1676          return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1677                                 VT);
1678    }
1679
1680  return SDValue();
1681}
1682
1683SDValue DAGCombiner::visitSUBC(SDNode *N) {
1684  SDValue N0 = N->getOperand(0);
1685  SDValue N1 = N->getOperand(1);
1686  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1687  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1688  EVT VT = N0.getValueType();
1689
1690  // If the flag result is dead, turn this into an SUB.
1691  if (!N->hasAnyUseOfValue(1))
1692    return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1693                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1694                                 MVT::Glue));
1695
1696  // fold (subc x, x) -> 0 + no borrow
1697  if (N0 == N1)
1698    return CombineTo(N, DAG.getConstant(0, VT),
1699                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1700                                 MVT::Glue));
1701
1702  // fold (subc x, 0) -> x + no borrow
1703  if (N1C && N1C->isNullValue())
1704    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1705                                        MVT::Glue));
1706
1707  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1708  if (N0C && N0C->isAllOnesValue())
1709    return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1710                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1711                                 MVT::Glue));
1712
1713  return SDValue();
1714}
1715
1716SDValue DAGCombiner::visitSUBE(SDNode *N) {
1717  SDValue N0 = N->getOperand(0);
1718  SDValue N1 = N->getOperand(1);
1719  SDValue CarryIn = N->getOperand(2);
1720
1721  // fold (sube x, y, false) -> (subc x, y)
1722  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1723    return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1724
1725  return SDValue();
1726}
1727
1728SDValue DAGCombiner::visitMUL(SDNode *N) {
1729  SDValue N0 = N->getOperand(0);
1730  SDValue N1 = N->getOperand(1);
1731  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1732  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1733  EVT VT = N0.getValueType();
1734
1735  // fold vector ops
1736  if (VT.isVector()) {
1737    SDValue FoldedVOp = SimplifyVBinOp(N);
1738    if (FoldedVOp.getNode()) return FoldedVOp;
1739  }
1740
1741  // fold (mul x, undef) -> 0
1742  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1743    return DAG.getConstant(0, VT);
1744  // fold (mul c1, c2) -> c1*c2
1745  if (N0C && N1C)
1746    return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1747  // canonicalize constant to RHS
1748  if (N0C && !N1C)
1749    return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1750  // fold (mul x, 0) -> 0
1751  if (N1C && N1C->isNullValue())
1752    return N1;
1753  // fold (mul x, -1) -> 0-x
1754  if (N1C && N1C->isAllOnesValue())
1755    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1756                       DAG.getConstant(0, VT), N0);
1757  // fold (mul x, (1 << c)) -> x << c
1758  if (N1C && N1C->getAPIntValue().isPowerOf2())
1759    return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1760                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
1761                                       getShiftAmountTy(N0.getValueType())));
1762  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1763  if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1764    unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1765    // FIXME: If the input is something that is easily negated (e.g. a
1766    // single-use add), we should put the negate there.
1767    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1768                       DAG.getConstant(0, VT),
1769                       DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1770                            DAG.getConstant(Log2Val,
1771                                      getShiftAmountTy(N0.getValueType()))));
1772  }
1773  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1774  if (N1C && N0.getOpcode() == ISD::SHL &&
1775      isa<ConstantSDNode>(N0.getOperand(1))) {
1776    SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1777                             N1, N0.getOperand(1));
1778    AddToWorkList(C3.getNode());
1779    return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1780                       N0.getOperand(0), C3);
1781  }
1782
1783  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1784  // use.
1785  {
1786    SDValue Sh(0,0), Y(0,0);
1787    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1788    if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1789        N0.getNode()->hasOneUse()) {
1790      Sh = N0; Y = N1;
1791    } else if (N1.getOpcode() == ISD::SHL &&
1792               isa<ConstantSDNode>(N1.getOperand(1)) &&
1793               N1.getNode()->hasOneUse()) {
1794      Sh = N1; Y = N0;
1795    }
1796
1797    if (Sh.getNode()) {
1798      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1799                                Sh.getOperand(0), Y);
1800      return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1801                         Mul, Sh.getOperand(1));
1802    }
1803  }
1804
1805  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1806  if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1807      isa<ConstantSDNode>(N0.getOperand(1)))
1808    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1809                       DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1810                                   N0.getOperand(0), N1),
1811                       DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1812                                   N0.getOperand(1), N1));
1813
1814  // reassociate mul
1815  SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1816  if (RMUL.getNode() != 0)
1817    return RMUL;
1818
1819  return SDValue();
1820}
1821
1822SDValue DAGCombiner::visitSDIV(SDNode *N) {
1823  SDValue N0 = N->getOperand(0);
1824  SDValue N1 = N->getOperand(1);
1825  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1826  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1827  EVT VT = N->getValueType(0);
1828
1829  // fold vector ops
1830  if (VT.isVector()) {
1831    SDValue FoldedVOp = SimplifyVBinOp(N);
1832    if (FoldedVOp.getNode()) return FoldedVOp;
1833  }
1834
1835  // fold (sdiv c1, c2) -> c1/c2
1836  if (N0C && N1C && !N1C->isNullValue())
1837    return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1838  // fold (sdiv X, 1) -> X
1839  if (N1C && N1C->getAPIntValue() == 1LL)
1840    return N0;
1841  // fold (sdiv X, -1) -> 0-X
1842  if (N1C && N1C->isAllOnesValue())
1843    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1844                       DAG.getConstant(0, VT), N0);
1845  // If we know the sign bits of both operands are zero, strength reduce to a
1846  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1847  if (!VT.isVector()) {
1848    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1849      return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1850                         N0, N1);
1851  }
1852  // fold (sdiv X, pow2) -> simple ops after legalize
1853  if (N1C && !N1C->isNullValue() &&
1854      (N1C->getAPIntValue().isPowerOf2() ||
1855       (-N1C->getAPIntValue()).isPowerOf2())) {
1856    // If dividing by powers of two is cheap, then don't perform the following
1857    // fold.
1858    if (TLI.isPow2DivCheap())
1859      return SDValue();
1860
1861    unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1862
1863    // Splat the sign bit into the register
1864    SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1865                              DAG.getConstant(VT.getSizeInBits()-1,
1866                                       getShiftAmountTy(N0.getValueType())));
1867    AddToWorkList(SGN.getNode());
1868
1869    // Add (N0 < 0) ? abs2 - 1 : 0;
1870    SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1871                              DAG.getConstant(VT.getSizeInBits() - lg2,
1872                                       getShiftAmountTy(SGN.getValueType())));
1873    SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1874    AddToWorkList(SRL.getNode());
1875    AddToWorkList(ADD.getNode());    // Divide by pow2
1876    SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1877                  DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1878
1879    // If we're dividing by a positive value, we're done.  Otherwise, we must
1880    // negate the result.
1881    if (N1C->getAPIntValue().isNonNegative())
1882      return SRA;
1883
1884    AddToWorkList(SRA.getNode());
1885    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1886                       DAG.getConstant(0, VT), SRA);
1887  }
1888
1889  // if integer divide is expensive and we satisfy the requirements, emit an
1890  // alternate sequence.
1891  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1892    SDValue Op = BuildSDIV(N);
1893    if (Op.getNode()) return Op;
1894  }
1895
1896  // undef / X -> 0
1897  if (N0.getOpcode() == ISD::UNDEF)
1898    return DAG.getConstant(0, VT);
1899  // X / undef -> undef
1900  if (N1.getOpcode() == ISD::UNDEF)
1901    return N1;
1902
1903  return SDValue();
1904}
1905
1906SDValue DAGCombiner::visitUDIV(SDNode *N) {
1907  SDValue N0 = N->getOperand(0);
1908  SDValue N1 = N->getOperand(1);
1909  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1910  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1911  EVT VT = N->getValueType(0);
1912
1913  // fold vector ops
1914  if (VT.isVector()) {
1915    SDValue FoldedVOp = SimplifyVBinOp(N);
1916    if (FoldedVOp.getNode()) return FoldedVOp;
1917  }
1918
1919  // fold (udiv c1, c2) -> c1/c2
1920  if (N0C && N1C && !N1C->isNullValue())
1921    return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1922  // fold (udiv x, (1 << c)) -> x >>u c
1923  if (N1C && N1C->getAPIntValue().isPowerOf2())
1924    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1925                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
1926                                       getShiftAmountTy(N0.getValueType())));
1927  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1928  if (N1.getOpcode() == ISD::SHL) {
1929    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1930      if (SHC->getAPIntValue().isPowerOf2()) {
1931        EVT ADDVT = N1.getOperand(1).getValueType();
1932        SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1933                                  N1.getOperand(1),
1934                                  DAG.getConstant(SHC->getAPIntValue()
1935                                                                  .logBase2(),
1936                                                  ADDVT));
1937        AddToWorkList(Add.getNode());
1938        return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1939      }
1940    }
1941  }
1942  // fold (udiv x, c) -> alternate
1943  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1944    SDValue Op = BuildUDIV(N);
1945    if (Op.getNode()) return Op;
1946  }
1947
1948  // undef / X -> 0
1949  if (N0.getOpcode() == ISD::UNDEF)
1950    return DAG.getConstant(0, VT);
1951  // X / undef -> undef
1952  if (N1.getOpcode() == ISD::UNDEF)
1953    return N1;
1954
1955  return SDValue();
1956}
1957
1958SDValue DAGCombiner::visitSREM(SDNode *N) {
1959  SDValue N0 = N->getOperand(0);
1960  SDValue N1 = N->getOperand(1);
1961  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1962  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1963  EVT VT = N->getValueType(0);
1964
1965  // fold (srem c1, c2) -> c1%c2
1966  if (N0C && N1C && !N1C->isNullValue())
1967    return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1968  // If we know the sign bits of both operands are zero, strength reduce to a
1969  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1970  if (!VT.isVector()) {
1971    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1972      return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1973  }
1974
1975  // If X/C can be simplified by the division-by-constant logic, lower
1976  // X%C to the equivalent of X-X/C*C.
1977  if (N1C && !N1C->isNullValue()) {
1978    SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1979    AddToWorkList(Div.getNode());
1980    SDValue OptimizedDiv = combine(Div.getNode());
1981    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1982      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1983                                OptimizedDiv, N1);
1984      SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1985      AddToWorkList(Mul.getNode());
1986      return Sub;
1987    }
1988  }
1989
1990  // undef % X -> 0
1991  if (N0.getOpcode() == ISD::UNDEF)
1992    return DAG.getConstant(0, VT);
1993  // X % undef -> undef
1994  if (N1.getOpcode() == ISD::UNDEF)
1995    return N1;
1996
1997  return SDValue();
1998}
1999
2000SDValue DAGCombiner::visitUREM(SDNode *N) {
2001  SDValue N0 = N->getOperand(0);
2002  SDValue N1 = N->getOperand(1);
2003  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2004  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2005  EVT VT = N->getValueType(0);
2006
2007  // fold (urem c1, c2) -> c1%c2
2008  if (N0C && N1C && !N1C->isNullValue())
2009    return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2010  // fold (urem x, pow2) -> (and x, pow2-1)
2011  if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2012    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2013                       DAG.getConstant(N1C->getAPIntValue()-1,VT));
2014  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2015  if (N1.getOpcode() == ISD::SHL) {
2016    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2017      if (SHC->getAPIntValue().isPowerOf2()) {
2018        SDValue Add =
2019          DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2020                 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2021                                 VT));
2022        AddToWorkList(Add.getNode());
2023        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2024      }
2025    }
2026  }
2027
2028  // If X/C can be simplified by the division-by-constant logic, lower
2029  // X%C to the equivalent of X-X/C*C.
2030  if (N1C && !N1C->isNullValue()) {
2031    SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2032    AddToWorkList(Div.getNode());
2033    SDValue OptimizedDiv = combine(Div.getNode());
2034    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2035      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2036                                OptimizedDiv, N1);
2037      SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2038      AddToWorkList(Mul.getNode());
2039      return Sub;
2040    }
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::visitMULHS(SDNode *N) {
2054  SDValue N0 = N->getOperand(0);
2055  SDValue N1 = N->getOperand(1);
2056  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2057  EVT VT = N->getValueType(0);
2058  DebugLoc DL = N->getDebugLoc();
2059
2060  // fold (mulhs x, 0) -> 0
2061  if (N1C && N1C->isNullValue())
2062    return N1;
2063  // fold (mulhs x, 1) -> (sra x, size(x)-1)
2064  if (N1C && N1C->getAPIntValue() == 1)
2065    return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2066                       DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2067                                       getShiftAmountTy(N0.getValueType())));
2068  // fold (mulhs x, undef) -> 0
2069  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2070    return DAG.getConstant(0, VT);
2071
2072  // If the type twice as wide is legal, transform the mulhs to a wider multiply
2073  // plus a shift.
2074  if (VT.isSimple() && !VT.isVector()) {
2075    MVT Simple = VT.getSimpleVT();
2076    unsigned SimpleSize = Simple.getSizeInBits();
2077    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2078    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2079      N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2080      N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2081      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2082      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2083            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2084      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2085    }
2086  }
2087
2088  return SDValue();
2089}
2090
2091SDValue DAGCombiner::visitMULHU(SDNode *N) {
2092  SDValue N0 = N->getOperand(0);
2093  SDValue N1 = N->getOperand(1);
2094  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2095  EVT VT = N->getValueType(0);
2096  DebugLoc DL = N->getDebugLoc();
2097
2098  // fold (mulhu x, 0) -> 0
2099  if (N1C && N1C->isNullValue())
2100    return N1;
2101  // fold (mulhu x, 1) -> 0
2102  if (N1C && N1C->getAPIntValue() == 1)
2103    return DAG.getConstant(0, N0.getValueType());
2104  // fold (mulhu x, undef) -> 0
2105  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2106    return DAG.getConstant(0, VT);
2107
2108  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2109  // plus a shift.
2110  if (VT.isSimple() && !VT.isVector()) {
2111    MVT Simple = VT.getSimpleVT();
2112    unsigned SimpleSize = Simple.getSizeInBits();
2113    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2114    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2115      N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2116      N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2117      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2118      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2119            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2120      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2121    }
2122  }
2123
2124  return SDValue();
2125}
2126
2127/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2128/// compute two values. LoOp and HiOp give the opcodes for the two computations
2129/// that are being performed. Return true if a simplification was made.
2130///
2131SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2132                                                unsigned HiOp) {
2133  // If the high half is not needed, just compute the low half.
2134  bool HiExists = N->hasAnyUseOfValue(1);
2135  if (!HiExists &&
2136      (!LegalOperations ||
2137       TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2138    SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2139                              N->op_begin(), N->getNumOperands());
2140    return CombineTo(N, Res, Res);
2141  }
2142
2143  // If the low half is not needed, just compute the high half.
2144  bool LoExists = N->hasAnyUseOfValue(0);
2145  if (!LoExists &&
2146      (!LegalOperations ||
2147       TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2148    SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2149                              N->op_begin(), N->getNumOperands());
2150    return CombineTo(N, Res, Res);
2151  }
2152
2153  // If both halves are used, return as it is.
2154  if (LoExists && HiExists)
2155    return SDValue();
2156
2157  // If the two computed results can be simplified separately, separate them.
2158  if (LoExists) {
2159    SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2160                             N->op_begin(), N->getNumOperands());
2161    AddToWorkList(Lo.getNode());
2162    SDValue LoOpt = combine(Lo.getNode());
2163    if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2164        (!LegalOperations ||
2165         TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2166      return CombineTo(N, LoOpt, LoOpt);
2167  }
2168
2169  if (HiExists) {
2170    SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2171                             N->op_begin(), N->getNumOperands());
2172    AddToWorkList(Hi.getNode());
2173    SDValue HiOpt = combine(Hi.getNode());
2174    if (HiOpt.getNode() && HiOpt != Hi &&
2175        (!LegalOperations ||
2176         TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2177      return CombineTo(N, HiOpt, HiOpt);
2178  }
2179
2180  return SDValue();
2181}
2182
2183SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2184  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2185  if (Res.getNode()) return Res;
2186
2187  EVT VT = N->getValueType(0);
2188  DebugLoc DL = N->getDebugLoc();
2189
2190  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2191  // plus a shift.
2192  if (VT.isSimple() && !VT.isVector()) {
2193    MVT Simple = VT.getSimpleVT();
2194    unsigned SimpleSize = Simple.getSizeInBits();
2195    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2196    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2197      SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2198      SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2199      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2200      // Compute the high part as N1.
2201      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2202            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2203      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2204      // Compute the low part as N0.
2205      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2206      return CombineTo(N, Lo, Hi);
2207    }
2208  }
2209
2210  return SDValue();
2211}
2212
2213SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2214  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2215  if (Res.getNode()) return Res;
2216
2217  EVT VT = N->getValueType(0);
2218  DebugLoc DL = N->getDebugLoc();
2219
2220  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2221  // plus a shift.
2222  if (VT.isSimple() && !VT.isVector()) {
2223    MVT Simple = VT.getSimpleVT();
2224    unsigned SimpleSize = Simple.getSizeInBits();
2225    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2226    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2227      SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2228      SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2229      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2230      // Compute the high part as N1.
2231      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2232            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2233      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2234      // Compute the low part as N0.
2235      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2236      return CombineTo(N, Lo, Hi);
2237    }
2238  }
2239
2240  return SDValue();
2241}
2242
2243SDValue DAGCombiner::visitSMULO(SDNode *N) {
2244  // (smulo x, 2) -> (saddo x, x)
2245  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2246    if (C2->getAPIntValue() == 2)
2247      return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2248                         N->getOperand(0), N->getOperand(0));
2249
2250  return SDValue();
2251}
2252
2253SDValue DAGCombiner::visitUMULO(SDNode *N) {
2254  // (umulo x, 2) -> (uaddo x, x)
2255  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2256    if (C2->getAPIntValue() == 2)
2257      return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2258                         N->getOperand(0), N->getOperand(0));
2259
2260  return SDValue();
2261}
2262
2263SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2264  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2265  if (Res.getNode()) return Res;
2266
2267  return SDValue();
2268}
2269
2270SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2271  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2272  if (Res.getNode()) return Res;
2273
2274  return SDValue();
2275}
2276
2277/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2278/// two operands of the same opcode, try to simplify it.
2279SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2280  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2281  EVT VT = N0.getValueType();
2282  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2283
2284  // Bail early if none of these transforms apply.
2285  if (N0.getNode()->getNumOperands() == 0) return SDValue();
2286
2287  // For each of OP in AND/OR/XOR:
2288  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2289  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2290  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2291  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2292  //
2293  // do not sink logical op inside of a vector extend, since it may combine
2294  // into a vsetcc.
2295  EVT Op0VT = N0.getOperand(0).getValueType();
2296  if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2297       N0.getOpcode() == ISD::SIGN_EXTEND ||
2298       // Avoid infinite looping with PromoteIntBinOp.
2299       (N0.getOpcode() == ISD::ANY_EXTEND &&
2300        (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2301       (N0.getOpcode() == ISD::TRUNCATE &&
2302        (!TLI.isZExtFree(VT, Op0VT) ||
2303         !TLI.isTruncateFree(Op0VT, VT)) &&
2304        TLI.isTypeLegal(Op0VT))) &&
2305      !VT.isVector() &&
2306      Op0VT == N1.getOperand(0).getValueType() &&
2307      (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2308    SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2309                                 N0.getOperand(0).getValueType(),
2310                                 N0.getOperand(0), N1.getOperand(0));
2311    AddToWorkList(ORNode.getNode());
2312    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2313  }
2314
2315  // For each of OP in SHL/SRL/SRA/AND...
2316  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2317  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2318  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2319  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2320       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2321      N0.getOperand(1) == N1.getOperand(1)) {
2322    SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2323                                 N0.getOperand(0).getValueType(),
2324                                 N0.getOperand(0), N1.getOperand(0));
2325    AddToWorkList(ORNode.getNode());
2326    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2327                       ORNode, N0.getOperand(1));
2328  }
2329
2330  // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2331  // Only perform this optimization after type legalization and before
2332  // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2333  // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2334  // we don't want to undo this promotion.
2335  // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2336  // on scalars.
2337  if ((N0.getOpcode() == ISD::BITCAST || N0.getOpcode() == ISD::SCALAR_TO_VECTOR)
2338      && Level == AfterLegalizeVectorOps) {
2339    SDValue In0 = N0.getOperand(0);
2340    SDValue In1 = N1.getOperand(0);
2341    EVT In0Ty = In0.getValueType();
2342    EVT In1Ty = In1.getValueType();
2343    // If both incoming values are integers, and the original types are the same.
2344    if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2345      SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), In0Ty, In0, In1);
2346      SDValue BC = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, Op);
2347      AddToWorkList(Op.getNode());
2348      return BC;
2349    }
2350  }
2351
2352  // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2353  // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2354  // If both shuffles use the same mask, and both shuffle within a single
2355  // vector, then it is worthwhile to move the swizzle after the operation.
2356  // The type-legalizer generates this pattern when loading illegal
2357  // vector types from memory. In many cases this allows additional shuffle
2358  // optimizations.
2359  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2360      N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2361      N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2362    ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2363    ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2364
2365    assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2366           "Inputs to shuffles are not the same type");
2367
2368    unsigned NumElts = VT.getVectorNumElements();
2369
2370    // Check that both shuffles use the same mask. The masks are known to be of
2371    // the same length because the result vector type is the same.
2372    bool SameMask = true;
2373    for (unsigned i = 0; i != NumElts; ++i) {
2374      int Idx0 = SVN0->getMaskElt(i);
2375      int Idx1 = SVN1->getMaskElt(i);
2376      if (Idx0 != Idx1) {
2377        SameMask = false;
2378        break;
2379      }
2380    }
2381
2382    if (SameMask) {
2383      SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2384                               N0.getOperand(0), N1.getOperand(0));
2385      AddToWorkList(Op.getNode());
2386      return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2387                                  DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2388    }
2389  }
2390
2391  return SDValue();
2392}
2393
2394SDValue DAGCombiner::visitAND(SDNode *N) {
2395  SDValue N0 = N->getOperand(0);
2396  SDValue N1 = N->getOperand(1);
2397  SDValue LL, LR, RL, RR, CC0, CC1;
2398  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2399  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2400  EVT VT = N1.getValueType();
2401  unsigned BitWidth = VT.getScalarType().getSizeInBits();
2402
2403  // fold vector ops
2404  if (VT.isVector()) {
2405    SDValue FoldedVOp = SimplifyVBinOp(N);
2406    if (FoldedVOp.getNode()) return FoldedVOp;
2407  }
2408
2409  // fold (and x, undef) -> 0
2410  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2411    return DAG.getConstant(0, VT);
2412  // fold (and c1, c2) -> c1&c2
2413  if (N0C && N1C)
2414    return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2415  // canonicalize constant to RHS
2416  if (N0C && !N1C)
2417    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2418  // fold (and x, -1) -> x
2419  if (N1C && N1C->isAllOnesValue())
2420    return N0;
2421  // if (and x, c) is known to be zero, return 0
2422  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2423                                   APInt::getAllOnesValue(BitWidth)))
2424    return DAG.getConstant(0, VT);
2425  // reassociate and
2426  SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2427  if (RAND.getNode() != 0)
2428    return RAND;
2429  // fold (and (or x, C), D) -> D if (C & D) == D
2430  if (N1C && N0.getOpcode() == ISD::OR)
2431    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2432      if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2433        return N1;
2434  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2435  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2436    SDValue N0Op0 = N0.getOperand(0);
2437    APInt Mask = ~N1C->getAPIntValue();
2438    Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2439    if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2440      SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2441                                 N0.getValueType(), N0Op0);
2442
2443      // Replace uses of the AND with uses of the Zero extend node.
2444      CombineTo(N, Zext);
2445
2446      // We actually want to replace all uses of the any_extend with the
2447      // zero_extend, to avoid duplicating things.  This will later cause this
2448      // AND to be folded.
2449      CombineTo(N0.getNode(), Zext);
2450      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2451    }
2452  }
2453  // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2454  // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2455  // already be zero by virtue of the width of the base type of the load.
2456  //
2457  // the 'X' node here can either be nothing or an extract_vector_elt to catch
2458  // more cases.
2459  if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2460       N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2461      N0.getOpcode() == ISD::LOAD) {
2462    LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2463                                         N0 : N0.getOperand(0) );
2464
2465    // Get the constant (if applicable) the zero'th operand is being ANDed with.
2466    // This can be a pure constant or a vector splat, in which case we treat the
2467    // vector as a scalar and use the splat value.
2468    APInt Constant = APInt::getNullValue(1);
2469    if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2470      Constant = C->getAPIntValue();
2471    } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2472      APInt SplatValue, SplatUndef;
2473      unsigned SplatBitSize;
2474      bool HasAnyUndefs;
2475      bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2476                                             SplatBitSize, HasAnyUndefs);
2477      if (IsSplat) {
2478        // Undef bits can contribute to a possible optimisation if set, so
2479        // set them.
2480        SplatValue |= SplatUndef;
2481
2482        // The splat value may be something like "0x00FFFFFF", which means 0 for
2483        // the first vector value and FF for the rest, repeating. We need a mask
2484        // that will apply equally to all members of the vector, so AND all the
2485        // lanes of the constant together.
2486        EVT VT = Vector->getValueType(0);
2487        unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2488        Constant = APInt::getAllOnesValue(BitWidth);
2489        for (unsigned i = 0, n = VT.getVectorNumElements(); i < n; ++i)
2490          Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2491      }
2492    }
2493
2494    // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2495    // actually legal and isn't going to get expanded, else this is a false
2496    // optimisation.
2497    bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2498                                                    Load->getMemoryVT());
2499
2500    // Resize the constant to the same size as the original memory access before
2501    // extension. If it is still the AllOnesValue then this AND is completely
2502    // unneeded.
2503    Constant =
2504      Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2505
2506    bool B;
2507    switch (Load->getExtensionType()) {
2508    default: B = false; break;
2509    case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2510    case ISD::ZEXTLOAD:
2511    case ISD::NON_EXTLOAD: B = true; break;
2512    }
2513
2514    if (B && Constant.isAllOnesValue()) {
2515      // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2516      // preserve semantics once we get rid of the AND.
2517      SDValue NewLoad(Load, 0);
2518      if (Load->getExtensionType() == ISD::EXTLOAD) {
2519        NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2520                              Load->getValueType(0), Load->getDebugLoc(),
2521                              Load->getChain(), Load->getBasePtr(),
2522                              Load->getOffset(), Load->getMemoryVT(),
2523                              Load->getMemOperand());
2524        // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2525        CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2526      }
2527
2528      // Fold the AND away, taking care not to fold to the old load node if we
2529      // replaced it.
2530      CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2531
2532      return SDValue(N, 0); // Return N so it doesn't get rechecked!
2533    }
2534  }
2535  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2536  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2537    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2538    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2539
2540    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2541        LL.getValueType().isInteger()) {
2542      // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2543      if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2544        SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2545                                     LR.getValueType(), LL, RL);
2546        AddToWorkList(ORNode.getNode());
2547        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2548      }
2549      // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2550      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2551        SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2552                                      LR.getValueType(), LL, RL);
2553        AddToWorkList(ANDNode.getNode());
2554        return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2555      }
2556      // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2557      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2558        SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2559                                     LR.getValueType(), LL, RL);
2560        AddToWorkList(ORNode.getNode());
2561        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2562      }
2563    }
2564    // canonicalize equivalent to ll == rl
2565    if (LL == RR && LR == RL) {
2566      Op1 = ISD::getSetCCSwappedOperands(Op1);
2567      std::swap(RL, RR);
2568    }
2569    if (LL == RL && LR == RR) {
2570      bool isInteger = LL.getValueType().isInteger();
2571      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2572      if (Result != ISD::SETCC_INVALID &&
2573          (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2574        return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2575                            LL, LR, Result);
2576    }
2577  }
2578
2579  // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2580  if (N0.getOpcode() == N1.getOpcode()) {
2581    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2582    if (Tmp.getNode()) return Tmp;
2583  }
2584
2585  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2586  // fold (and (sra)) -> (and (srl)) when possible.
2587  if (!VT.isVector() &&
2588      SimplifyDemandedBits(SDValue(N, 0)))
2589    return SDValue(N, 0);
2590
2591  // fold (zext_inreg (extload x)) -> (zextload x)
2592  if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2593    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2594    EVT MemVT = LN0->getMemoryVT();
2595    // If we zero all the possible extended bits, then we can turn this into
2596    // a zextload if we are running before legalize or the operation is legal.
2597    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2598    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2599                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2600        ((!LegalOperations && !LN0->isVolatile()) ||
2601         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2602      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2603                                       LN0->getChain(), LN0->getBasePtr(),
2604                                       LN0->getPointerInfo(), MemVT,
2605                                       LN0->isVolatile(), LN0->isNonTemporal(),
2606                                       LN0->getAlignment());
2607      AddToWorkList(N);
2608      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2609      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2610    }
2611  }
2612  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2613  if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2614      N0.hasOneUse()) {
2615    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2616    EVT MemVT = LN0->getMemoryVT();
2617    // If we zero all the possible extended bits, then we can turn this into
2618    // a zextload if we are running before legalize or the operation is legal.
2619    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2620    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2621                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2622        ((!LegalOperations && !LN0->isVolatile()) ||
2623         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2624      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2625                                       LN0->getChain(),
2626                                       LN0->getBasePtr(), LN0->getPointerInfo(),
2627                                       MemVT,
2628                                       LN0->isVolatile(), LN0->isNonTemporal(),
2629                                       LN0->getAlignment());
2630      AddToWorkList(N);
2631      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2632      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2633    }
2634  }
2635
2636  // fold (and (load x), 255) -> (zextload x, i8)
2637  // fold (and (extload x, i16), 255) -> (zextload x, i8)
2638  // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2639  if (N1C && (N0.getOpcode() == ISD::LOAD ||
2640              (N0.getOpcode() == ISD::ANY_EXTEND &&
2641               N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2642    bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2643    LoadSDNode *LN0 = HasAnyExt
2644      ? cast<LoadSDNode>(N0.getOperand(0))
2645      : cast<LoadSDNode>(N0);
2646    if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2647        LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2648      uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2649      if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2650        EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2651        EVT LoadedVT = LN0->getMemoryVT();
2652
2653        if (ExtVT == LoadedVT &&
2654            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2655          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2656
2657          SDValue NewLoad =
2658            DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2659                           LN0->getChain(), LN0->getBasePtr(),
2660                           LN0->getPointerInfo(),
2661                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2662                           LN0->getAlignment());
2663          AddToWorkList(N);
2664          CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2665          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2666        }
2667
2668        // Do not change the width of a volatile load.
2669        // Do not generate loads of non-round integer types since these can
2670        // be expensive (and would be wrong if the type is not byte sized).
2671        if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2672            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2673          EVT PtrType = LN0->getOperand(1).getValueType();
2674
2675          unsigned Alignment = LN0->getAlignment();
2676          SDValue NewPtr = LN0->getBasePtr();
2677
2678          // For big endian targets, we need to add an offset to the pointer
2679          // to load the correct bytes.  For little endian systems, we merely
2680          // need to read fewer bytes from the same pointer.
2681          if (TLI.isBigEndian()) {
2682            unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2683            unsigned EVTStoreBytes = ExtVT.getStoreSize();
2684            unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2685            NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2686                                 NewPtr, DAG.getConstant(PtrOff, PtrType));
2687            Alignment = MinAlign(Alignment, PtrOff);
2688          }
2689
2690          AddToWorkList(NewPtr.getNode());
2691
2692          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2693          SDValue Load =
2694            DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2695                           LN0->getChain(), NewPtr,
2696                           LN0->getPointerInfo(),
2697                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2698                           Alignment);
2699          AddToWorkList(N);
2700          CombineTo(LN0, Load, Load.getValue(1));
2701          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2702        }
2703      }
2704    }
2705  }
2706
2707  return SDValue();
2708}
2709
2710/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2711///
2712SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2713                                        bool DemandHighBits) {
2714  if (!LegalOperations)
2715    return SDValue();
2716
2717  EVT VT = N->getValueType(0);
2718  if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2719    return SDValue();
2720  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2721    return SDValue();
2722
2723  // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2724  bool LookPassAnd0 = false;
2725  bool LookPassAnd1 = false;
2726  if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2727      std::swap(N0, N1);
2728  if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2729      std::swap(N0, N1);
2730  if (N0.getOpcode() == ISD::AND) {
2731    if (!N0.getNode()->hasOneUse())
2732      return SDValue();
2733    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2734    if (!N01C || N01C->getZExtValue() != 0xFF00)
2735      return SDValue();
2736    N0 = N0.getOperand(0);
2737    LookPassAnd0 = true;
2738  }
2739
2740  if (N1.getOpcode() == ISD::AND) {
2741    if (!N1.getNode()->hasOneUse())
2742      return SDValue();
2743    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2744    if (!N11C || N11C->getZExtValue() != 0xFF)
2745      return SDValue();
2746    N1 = N1.getOperand(0);
2747    LookPassAnd1 = true;
2748  }
2749
2750  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2751    std::swap(N0, N1);
2752  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2753    return SDValue();
2754  if (!N0.getNode()->hasOneUse() ||
2755      !N1.getNode()->hasOneUse())
2756    return SDValue();
2757
2758  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2759  ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2760  if (!N01C || !N11C)
2761    return SDValue();
2762  if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2763    return SDValue();
2764
2765  // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2766  SDValue N00 = N0->getOperand(0);
2767  if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2768    if (!N00.getNode()->hasOneUse())
2769      return SDValue();
2770    ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2771    if (!N001C || N001C->getZExtValue() != 0xFF)
2772      return SDValue();
2773    N00 = N00.getOperand(0);
2774    LookPassAnd0 = true;
2775  }
2776
2777  SDValue N10 = N1->getOperand(0);
2778  if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2779    if (!N10.getNode()->hasOneUse())
2780      return SDValue();
2781    ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2782    if (!N101C || N101C->getZExtValue() != 0xFF00)
2783      return SDValue();
2784    N10 = N10.getOperand(0);
2785    LookPassAnd1 = true;
2786  }
2787
2788  if (N00 != N10)
2789    return SDValue();
2790
2791  // Make sure everything beyond the low halfword is zero since the SRL 16
2792  // will clear the top bits.
2793  unsigned OpSizeInBits = VT.getSizeInBits();
2794  if (DemandHighBits && OpSizeInBits > 16 &&
2795      (!LookPassAnd0 || !LookPassAnd1) &&
2796      !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2797    return SDValue();
2798
2799  SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2800  if (OpSizeInBits > 16)
2801    Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2802                      DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2803  return Res;
2804}
2805
2806/// isBSwapHWordElement - Return true if the specified node is an element
2807/// that makes up a 32-bit packed halfword byteswap. i.e.
2808/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2809static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2810  if (!N.getNode()->hasOneUse())
2811    return false;
2812
2813  unsigned Opc = N.getOpcode();
2814  if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2815    return false;
2816
2817  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2818  if (!N1C)
2819    return false;
2820
2821  unsigned Num;
2822  switch (N1C->getZExtValue()) {
2823  default:
2824    return false;
2825  case 0xFF:       Num = 0; break;
2826  case 0xFF00:     Num = 1; break;
2827  case 0xFF0000:   Num = 2; break;
2828  case 0xFF000000: Num = 3; break;
2829  }
2830
2831  // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2832  SDValue N0 = N.getOperand(0);
2833  if (Opc == ISD::AND) {
2834    if (Num == 0 || Num == 2) {
2835      // (x >> 8) & 0xff
2836      // (x >> 8) & 0xff0000
2837      if (N0.getOpcode() != ISD::SRL)
2838        return false;
2839      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2840      if (!C || C->getZExtValue() != 8)
2841        return false;
2842    } else {
2843      // (x << 8) & 0xff00
2844      // (x << 8) & 0xff000000
2845      if (N0.getOpcode() != ISD::SHL)
2846        return false;
2847      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2848      if (!C || C->getZExtValue() != 8)
2849        return false;
2850    }
2851  } else if (Opc == ISD::SHL) {
2852    // (x & 0xff) << 8
2853    // (x & 0xff0000) << 8
2854    if (Num != 0 && Num != 2)
2855      return false;
2856    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2857    if (!C || C->getZExtValue() != 8)
2858      return false;
2859  } else { // Opc == ISD::SRL
2860    // (x & 0xff00) >> 8
2861    // (x & 0xff000000) >> 8
2862    if (Num != 1 && Num != 3)
2863      return false;
2864    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2865    if (!C || C->getZExtValue() != 8)
2866      return false;
2867  }
2868
2869  if (Parts[Num])
2870    return false;
2871
2872  Parts[Num] = N0.getOperand(0).getNode();
2873  return true;
2874}
2875
2876/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2877/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2878/// => (rotl (bswap x), 16)
2879SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2880  if (!LegalOperations)
2881    return SDValue();
2882
2883  EVT VT = N->getValueType(0);
2884  if (VT != MVT::i32)
2885    return SDValue();
2886  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2887    return SDValue();
2888
2889  SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2890  // Look for either
2891  // (or (or (and), (and)), (or (and), (and)))
2892  // (or (or (or (and), (and)), (and)), (and))
2893  if (N0.getOpcode() != ISD::OR)
2894    return SDValue();
2895  SDValue N00 = N0.getOperand(0);
2896  SDValue N01 = N0.getOperand(1);
2897
2898  if (N1.getOpcode() == ISD::OR) {
2899    // (or (or (and), (and)), (or (and), (and)))
2900    SDValue N000 = N00.getOperand(0);
2901    if (!isBSwapHWordElement(N000, Parts))
2902      return SDValue();
2903
2904    SDValue N001 = N00.getOperand(1);
2905    if (!isBSwapHWordElement(N001, Parts))
2906      return SDValue();
2907    SDValue N010 = N01.getOperand(0);
2908    if (!isBSwapHWordElement(N010, Parts))
2909      return SDValue();
2910    SDValue N011 = N01.getOperand(1);
2911    if (!isBSwapHWordElement(N011, Parts))
2912      return SDValue();
2913  } else {
2914    // (or (or (or (and), (and)), (and)), (and))
2915    if (!isBSwapHWordElement(N1, Parts))
2916      return SDValue();
2917    if (!isBSwapHWordElement(N01, Parts))
2918      return SDValue();
2919    if (N00.getOpcode() != ISD::OR)
2920      return SDValue();
2921    SDValue N000 = N00.getOperand(0);
2922    if (!isBSwapHWordElement(N000, Parts))
2923      return SDValue();
2924    SDValue N001 = N00.getOperand(1);
2925    if (!isBSwapHWordElement(N001, Parts))
2926      return SDValue();
2927  }
2928
2929  // Make sure the parts are all coming from the same node.
2930  if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
2931    return SDValue();
2932
2933  SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
2934                              SDValue(Parts[0],0));
2935
2936  // Result of the bswap should be rotated by 16. If it's not legal, than
2937  // do  (x << 16) | (x >> 16).
2938  SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
2939  if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
2940    return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
2941  else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
2942    return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
2943  return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
2944                     DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
2945                     DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
2946}
2947
2948SDValue DAGCombiner::visitOR(SDNode *N) {
2949  SDValue N0 = N->getOperand(0);
2950  SDValue N1 = N->getOperand(1);
2951  SDValue LL, LR, RL, RR, CC0, CC1;
2952  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2953  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2954  EVT VT = N1.getValueType();
2955
2956  // fold vector ops
2957  if (VT.isVector()) {
2958    SDValue FoldedVOp = SimplifyVBinOp(N);
2959    if (FoldedVOp.getNode()) return FoldedVOp;
2960  }
2961
2962  // fold (or x, undef) -> -1
2963  if (!LegalOperations &&
2964      (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2965    EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2966    return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2967  }
2968  // fold (or c1, c2) -> c1|c2
2969  if (N0C && N1C)
2970    return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2971  // canonicalize constant to RHS
2972  if (N0C && !N1C)
2973    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2974  // fold (or x, 0) -> x
2975  if (N1C && N1C->isNullValue())
2976    return N0;
2977  // fold (or x, -1) -> -1
2978  if (N1C && N1C->isAllOnesValue())
2979    return N1;
2980  // fold (or x, c) -> c iff (x & ~c) == 0
2981  if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2982    return N1;
2983
2984  // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
2985  SDValue BSwap = MatchBSwapHWord(N, N0, N1);
2986  if (BSwap.getNode() != 0)
2987    return BSwap;
2988  BSwap = MatchBSwapHWordLow(N, N0, N1);
2989  if (BSwap.getNode() != 0)
2990    return BSwap;
2991
2992  // reassociate or
2993  SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2994  if (ROR.getNode() != 0)
2995    return ROR;
2996  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2997  // iff (c1 & c2) == 0.
2998  if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2999             isa<ConstantSDNode>(N0.getOperand(1))) {
3000    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3001    if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3002      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3003                         DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3004                                     N0.getOperand(0), N1),
3005                         DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3006  }
3007  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3008  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3009    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3010    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3011
3012    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3013        LL.getValueType().isInteger()) {
3014      // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3015      // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3016      if (cast<ConstantSDNode>(LR)->isNullValue() &&
3017          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3018        SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3019                                     LR.getValueType(), LL, RL);
3020        AddToWorkList(ORNode.getNode());
3021        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3022      }
3023      // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3024      // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3025      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3026          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3027        SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3028                                      LR.getValueType(), LL, RL);
3029        AddToWorkList(ANDNode.getNode());
3030        return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3031      }
3032    }
3033    // canonicalize equivalent to ll == rl
3034    if (LL == RR && LR == RL) {
3035      Op1 = ISD::getSetCCSwappedOperands(Op1);
3036      std::swap(RL, RR);
3037    }
3038    if (LL == RL && LR == RR) {
3039      bool isInteger = LL.getValueType().isInteger();
3040      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3041      if (Result != ISD::SETCC_INVALID &&
3042          (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
3043        return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3044                            LL, LR, Result);
3045    }
3046  }
3047
3048  // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3049  if (N0.getOpcode() == N1.getOpcode()) {
3050    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3051    if (Tmp.getNode()) return Tmp;
3052  }
3053
3054  // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3055  if (N0.getOpcode() == ISD::AND &&
3056      N1.getOpcode() == ISD::AND &&
3057      N0.getOperand(1).getOpcode() == ISD::Constant &&
3058      N1.getOperand(1).getOpcode() == ISD::Constant &&
3059      // Don't increase # computations.
3060      (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3061    // We can only do this xform if we know that bits from X that are set in C2
3062    // but not in C1 are already zero.  Likewise for Y.
3063    const APInt &LHSMask =
3064      cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3065    const APInt &RHSMask =
3066      cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3067
3068    if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3069        DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3070      SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3071                              N0.getOperand(0), N1.getOperand(0));
3072      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3073                         DAG.getConstant(LHSMask | RHSMask, VT));
3074    }
3075  }
3076
3077  // See if this is some rotate idiom.
3078  if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3079    return SDValue(Rot, 0);
3080
3081  // Simplify the operands using demanded-bits information.
3082  if (!VT.isVector() &&
3083      SimplifyDemandedBits(SDValue(N, 0)))
3084    return SDValue(N, 0);
3085
3086  return SDValue();
3087}
3088
3089/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3090static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3091  if (Op.getOpcode() == ISD::AND) {
3092    if (isa<ConstantSDNode>(Op.getOperand(1))) {
3093      Mask = Op.getOperand(1);
3094      Op = Op.getOperand(0);
3095    } else {
3096      return false;
3097    }
3098  }
3099
3100  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3101    Shift = Op;
3102    return true;
3103  }
3104
3105  return false;
3106}
3107
3108// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3109// idioms for rotate, and if the target supports rotation instructions, generate
3110// a rot[lr].
3111SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3112  // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3113  EVT VT = LHS.getValueType();
3114  if (!TLI.isTypeLegal(VT)) return 0;
3115
3116  // The target must have at least one rotate flavor.
3117  bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3118  bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3119  if (!HasROTL && !HasROTR) return 0;
3120
3121  // Match "(X shl/srl V1) & V2" where V2 may not be present.
3122  SDValue LHSShift;   // The shift.
3123  SDValue LHSMask;    // AND value if any.
3124  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3125    return 0; // Not part of a rotate.
3126
3127  SDValue RHSShift;   // The shift.
3128  SDValue RHSMask;    // AND value if any.
3129  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3130    return 0; // Not part of a rotate.
3131
3132  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3133    return 0;   // Not shifting the same value.
3134
3135  if (LHSShift.getOpcode() == RHSShift.getOpcode())
3136    return 0;   // Shifts must disagree.
3137
3138  // Canonicalize shl to left side in a shl/srl pair.
3139  if (RHSShift.getOpcode() == ISD::SHL) {
3140    std::swap(LHS, RHS);
3141    std::swap(LHSShift, RHSShift);
3142    std::swap(LHSMask , RHSMask );
3143  }
3144
3145  unsigned OpSizeInBits = VT.getSizeInBits();
3146  SDValue LHSShiftArg = LHSShift.getOperand(0);
3147  SDValue LHSShiftAmt = LHSShift.getOperand(1);
3148  SDValue RHSShiftAmt = RHSShift.getOperand(1);
3149
3150  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3151  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3152  if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3153      RHSShiftAmt.getOpcode() == ISD::Constant) {
3154    uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3155    uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3156    if ((LShVal + RShVal) != OpSizeInBits)
3157      return 0;
3158
3159    SDValue Rot;
3160    if (HasROTL)
3161      Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
3162    else
3163      Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
3164
3165    // If there is an AND of either shifted operand, apply it to the result.
3166    if (LHSMask.getNode() || RHSMask.getNode()) {
3167      APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3168
3169      if (LHSMask.getNode()) {
3170        APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3171        Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3172      }
3173      if (RHSMask.getNode()) {
3174        APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3175        Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3176      }
3177
3178      Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3179    }
3180
3181    return Rot.getNode();
3182  }
3183
3184  // If there is a mask here, and we have a variable shift, we can't be sure
3185  // that we're masking out the right stuff.
3186  if (LHSMask.getNode() || RHSMask.getNode())
3187    return 0;
3188
3189  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3190  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3191  if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3192      LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3193    if (ConstantSDNode *SUBC =
3194          dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3195      if (SUBC->getAPIntValue() == OpSizeInBits) {
3196        if (HasROTL)
3197          return DAG.getNode(ISD::ROTL, DL, VT,
3198                             LHSShiftArg, LHSShiftAmt).getNode();
3199        else
3200          return DAG.getNode(ISD::ROTR, DL, VT,
3201                             LHSShiftArg, RHSShiftAmt).getNode();
3202      }
3203    }
3204  }
3205
3206  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3207  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3208  if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3209      RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3210    if (ConstantSDNode *SUBC =
3211          dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3212      if (SUBC->getAPIntValue() == OpSizeInBits) {
3213        if (HasROTR)
3214          return DAG.getNode(ISD::ROTR, DL, VT,
3215                             LHSShiftArg, RHSShiftAmt).getNode();
3216        else
3217          return DAG.getNode(ISD::ROTL, DL, VT,
3218                             LHSShiftArg, LHSShiftAmt).getNode();
3219      }
3220    }
3221  }
3222
3223  // Look for sign/zext/any-extended or truncate cases:
3224  if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3225       || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3226       || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3227       || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3228      (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
3229       || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
3230       || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
3231       || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3232    SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3233    SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3234    if (RExtOp0.getOpcode() == ISD::SUB &&
3235        RExtOp0.getOperand(1) == LExtOp0) {
3236      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3237      //   (rotl x, y)
3238      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3239      //   (rotr x, (sub 32, y))
3240      if (ConstantSDNode *SUBC =
3241            dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3242        if (SUBC->getAPIntValue() == OpSizeInBits) {
3243          return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3244                             LHSShiftArg,
3245                             HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3246        }
3247      }
3248    } else if (LExtOp0.getOpcode() == ISD::SUB &&
3249               RExtOp0 == LExtOp0.getOperand(1)) {
3250      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3251      //   (rotr x, y)
3252      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3253      //   (rotl x, (sub 32, y))
3254      if (ConstantSDNode *SUBC =
3255            dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3256        if (SUBC->getAPIntValue() == OpSizeInBits) {
3257          return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3258                             LHSShiftArg,
3259                             HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3260        }
3261      }
3262    }
3263  }
3264
3265  return 0;
3266}
3267
3268SDValue DAGCombiner::visitXOR(SDNode *N) {
3269  SDValue N0 = N->getOperand(0);
3270  SDValue N1 = N->getOperand(1);
3271  SDValue LHS, RHS, CC;
3272  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3273  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3274  EVT VT = N0.getValueType();
3275
3276  // fold vector ops
3277  if (VT.isVector()) {
3278    SDValue FoldedVOp = SimplifyVBinOp(N);
3279    if (FoldedVOp.getNode()) return FoldedVOp;
3280  }
3281
3282  // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3283  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3284    return DAG.getConstant(0, VT);
3285  // fold (xor x, undef) -> undef
3286  if (N0.getOpcode() == ISD::UNDEF)
3287    return N0;
3288  if (N1.getOpcode() == ISD::UNDEF)
3289    return N1;
3290  // fold (xor c1, c2) -> c1^c2
3291  if (N0C && N1C)
3292    return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3293  // canonicalize constant to RHS
3294  if (N0C && !N1C)
3295    return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3296  // fold (xor x, 0) -> x
3297  if (N1C && N1C->isNullValue())
3298    return N0;
3299  // reassociate xor
3300  SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3301  if (RXOR.getNode() != 0)
3302    return RXOR;
3303
3304  // fold !(x cc y) -> (x !cc y)
3305  if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3306    bool isInt = LHS.getValueType().isInteger();
3307    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3308                                               isInt);
3309
3310    if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
3311      switch (N0.getOpcode()) {
3312      default:
3313        llvm_unreachable("Unhandled SetCC Equivalent!");
3314      case ISD::SETCC:
3315        return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3316      case ISD::SELECT_CC:
3317        return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3318                               N0.getOperand(3), NotCC);
3319      }
3320    }
3321  }
3322
3323  // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3324  if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3325      N0.getNode()->hasOneUse() &&
3326      isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3327    SDValue V = N0.getOperand(0);
3328    V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3329                    DAG.getConstant(1, V.getValueType()));
3330    AddToWorkList(V.getNode());
3331    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3332  }
3333
3334  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3335  if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3336      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3337    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3338    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3339      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3340      LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3341      RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3342      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3343      return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3344    }
3345  }
3346  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3347  if (N1C && N1C->isAllOnesValue() &&
3348      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3349    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3350    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3351      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3352      LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3353      RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3354      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3355      return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3356    }
3357  }
3358  // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3359  if (N1C && N0.getOpcode() == ISD::XOR) {
3360    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3361    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3362    if (N00C)
3363      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3364                         DAG.getConstant(N1C->getAPIntValue() ^
3365                                         N00C->getAPIntValue(), VT));
3366    if (N01C)
3367      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3368                         DAG.getConstant(N1C->getAPIntValue() ^
3369                                         N01C->getAPIntValue(), VT));
3370  }
3371  // fold (xor x, x) -> 0
3372  if (N0 == N1)
3373    return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3374
3375  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3376  if (N0.getOpcode() == N1.getOpcode()) {
3377    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3378    if (Tmp.getNode()) return Tmp;
3379  }
3380
3381  // Simplify the expression using non-local knowledge.
3382  if (!VT.isVector() &&
3383      SimplifyDemandedBits(SDValue(N, 0)))
3384    return SDValue(N, 0);
3385
3386  return SDValue();
3387}
3388
3389/// visitShiftByConstant - Handle transforms common to the three shifts, when
3390/// the shift amount is a constant.
3391SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3392  SDNode *LHS = N->getOperand(0).getNode();
3393  if (!LHS->hasOneUse()) return SDValue();
3394
3395  // We want to pull some binops through shifts, so that we have (and (shift))
3396  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3397  // thing happens with address calculations, so it's important to canonicalize
3398  // it.
3399  bool HighBitSet = false;  // Can we transform this if the high bit is set?
3400
3401  switch (LHS->getOpcode()) {
3402  default: return SDValue();
3403  case ISD::OR:
3404  case ISD::XOR:
3405    HighBitSet = false; // We can only transform sra if the high bit is clear.
3406    break;
3407  case ISD::AND:
3408    HighBitSet = true;  // We can only transform sra if the high bit is set.
3409    break;
3410  case ISD::ADD:
3411    if (N->getOpcode() != ISD::SHL)
3412      return SDValue(); // only shl(add) not sr[al](add).
3413    HighBitSet = false; // We can only transform sra if the high bit is clear.
3414    break;
3415  }
3416
3417  // We require the RHS of the binop to be a constant as well.
3418  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3419  if (!BinOpCst) return SDValue();
3420
3421  // FIXME: disable this unless the input to the binop is a shift by a constant.
3422  // If it is not a shift, it pessimizes some common cases like:
3423  //
3424  //    void foo(int *X, int i) { X[i & 1235] = 1; }
3425  //    int bar(int *X, int i) { return X[i & 255]; }
3426  SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3427  if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3428       BinOpLHSVal->getOpcode() != ISD::SRA &&
3429       BinOpLHSVal->getOpcode() != ISD::SRL) ||
3430      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3431    return SDValue();
3432
3433  EVT VT = N->getValueType(0);
3434
3435  // If this is a signed shift right, and the high bit is modified by the
3436  // logical operation, do not perform the transformation. The highBitSet
3437  // boolean indicates the value of the high bit of the constant which would
3438  // cause it to be modified for this operation.
3439  if (N->getOpcode() == ISD::SRA) {
3440    bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3441    if (BinOpRHSSignSet != HighBitSet)
3442      return SDValue();
3443  }
3444
3445  // Fold the constants, shifting the binop RHS by the shift amount.
3446  SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3447                               N->getValueType(0),
3448                               LHS->getOperand(1), N->getOperand(1));
3449
3450  // Create the new shift.
3451  SDValue NewShift = DAG.getNode(N->getOpcode(),
3452                                 LHS->getOperand(0).getDebugLoc(),
3453                                 VT, LHS->getOperand(0), N->getOperand(1));
3454
3455  // Create the new binop.
3456  return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3457}
3458
3459SDValue DAGCombiner::visitSHL(SDNode *N) {
3460  SDValue N0 = N->getOperand(0);
3461  SDValue N1 = N->getOperand(1);
3462  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3463  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3464  EVT VT = N0.getValueType();
3465  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3466
3467  // fold (shl c1, c2) -> c1<<c2
3468  if (N0C && N1C)
3469    return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3470  // fold (shl 0, x) -> 0
3471  if (N0C && N0C->isNullValue())
3472    return N0;
3473  // fold (shl x, c >= size(x)) -> undef
3474  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3475    return DAG.getUNDEF(VT);
3476  // fold (shl x, 0) -> x
3477  if (N1C && N1C->isNullValue())
3478    return N0;
3479  // fold (shl undef, x) -> 0
3480  if (N0.getOpcode() == ISD::UNDEF)
3481    return DAG.getConstant(0, VT);
3482  // if (shl x, c) is known to be zero, return 0
3483  if (DAG.MaskedValueIsZero(SDValue(N, 0),
3484                            APInt::getAllOnesValue(OpSizeInBits)))
3485    return DAG.getConstant(0, VT);
3486  // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3487  if (N1.getOpcode() == ISD::TRUNCATE &&
3488      N1.getOperand(0).getOpcode() == ISD::AND &&
3489      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3490    SDValue N101 = N1.getOperand(0).getOperand(1);
3491    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3492      EVT TruncVT = N1.getValueType();
3493      SDValue N100 = N1.getOperand(0).getOperand(0);
3494      APInt TruncC = N101C->getAPIntValue();
3495      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3496      return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3497                         DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3498                                     DAG.getNode(ISD::TRUNCATE,
3499                                                 N->getDebugLoc(),
3500                                                 TruncVT, N100),
3501                                     DAG.getConstant(TruncC, TruncVT)));
3502    }
3503  }
3504
3505  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3506    return SDValue(N, 0);
3507
3508  // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3509  if (N1C && N0.getOpcode() == ISD::SHL &&
3510      N0.getOperand(1).getOpcode() == ISD::Constant) {
3511    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3512    uint64_t c2 = N1C->getZExtValue();
3513    if (c1 + c2 >= OpSizeInBits)
3514      return DAG.getConstant(0, VT);
3515    return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3516                       DAG.getConstant(c1 + c2, N1.getValueType()));
3517  }
3518
3519  // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3520  // For this to be valid, the second form must not preserve any of the bits
3521  // that are shifted out by the inner shift in the first form.  This means
3522  // the outer shift size must be >= the number of bits added by the ext.
3523  // As a corollary, we don't care what kind of ext it is.
3524  if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3525              N0.getOpcode() == ISD::ANY_EXTEND ||
3526              N0.getOpcode() == ISD::SIGN_EXTEND) &&
3527      N0.getOperand(0).getOpcode() == ISD::SHL &&
3528      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3529    uint64_t c1 =
3530      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3531    uint64_t c2 = N1C->getZExtValue();
3532    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3533    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3534    if (c2 >= OpSizeInBits - InnerShiftSize) {
3535      if (c1 + c2 >= OpSizeInBits)
3536        return DAG.getConstant(0, VT);
3537      return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3538                         DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3539                                     N0.getOperand(0)->getOperand(0)),
3540                         DAG.getConstant(c1 + c2, N1.getValueType()));
3541    }
3542  }
3543
3544  // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3545  //                               (and (srl x, (sub c1, c2), MASK)
3546  // Only fold this if the inner shift has no other uses -- if it does, folding
3547  // this will increase the total number of instructions.
3548  if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3549      N0.getOperand(1).getOpcode() == ISD::Constant) {
3550    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3551    if (c1 < VT.getSizeInBits()) {
3552      uint64_t c2 = N1C->getZExtValue();
3553      APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3554                                         VT.getSizeInBits() - c1);
3555      SDValue Shift;
3556      if (c2 > c1) {
3557        Mask = Mask.shl(c2-c1);
3558        Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3559                            DAG.getConstant(c2-c1, N1.getValueType()));
3560      } else {
3561        Mask = Mask.lshr(c1-c2);
3562        Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3563                            DAG.getConstant(c1-c2, N1.getValueType()));
3564      }
3565      return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3566                         DAG.getConstant(Mask, VT));
3567    }
3568  }
3569  // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3570  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3571    SDValue HiBitsMask =
3572      DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3573                                            VT.getSizeInBits() -
3574                                              N1C->getZExtValue()),
3575                      VT);
3576    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3577                       HiBitsMask);
3578  }
3579
3580  if (N1C) {
3581    SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3582    if (NewSHL.getNode())
3583      return NewSHL;
3584  }
3585
3586  return SDValue();
3587}
3588
3589SDValue DAGCombiner::visitSRA(SDNode *N) {
3590  SDValue N0 = N->getOperand(0);
3591  SDValue N1 = N->getOperand(1);
3592  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3593  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3594  EVT VT = N0.getValueType();
3595  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3596
3597  // fold (sra c1, c2) -> (sra c1, c2)
3598  if (N0C && N1C)
3599    return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3600  // fold (sra 0, x) -> 0
3601  if (N0C && N0C->isNullValue())
3602    return N0;
3603  // fold (sra -1, x) -> -1
3604  if (N0C && N0C->isAllOnesValue())
3605    return N0;
3606  // fold (sra x, (setge c, size(x))) -> undef
3607  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3608    return DAG.getUNDEF(VT);
3609  // fold (sra x, 0) -> x
3610  if (N1C && N1C->isNullValue())
3611    return N0;
3612  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3613  // sext_inreg.
3614  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3615    unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3616    EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3617    if (VT.isVector())
3618      ExtVT = EVT::getVectorVT(*DAG.getContext(),
3619                               ExtVT, VT.getVectorNumElements());
3620    if ((!LegalOperations ||
3621         TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3622      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3623                         N0.getOperand(0), DAG.getValueType(ExtVT));
3624  }
3625
3626  // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3627  if (N1C && N0.getOpcode() == ISD::SRA) {
3628    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3629      unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3630      if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3631      return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3632                         DAG.getConstant(Sum, N1C->getValueType(0)));
3633    }
3634  }
3635
3636  // fold (sra (shl X, m), (sub result_size, n))
3637  // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3638  // result_size - n != m.
3639  // If truncate is free for the target sext(shl) is likely to result in better
3640  // code.
3641  if (N0.getOpcode() == ISD::SHL) {
3642    // Get the two constanst of the shifts, CN0 = m, CN = n.
3643    const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3644    if (N01C && N1C) {
3645      // Determine what the truncate's result bitsize and type would be.
3646      EVT TruncVT =
3647        EVT::getIntegerVT(*DAG.getContext(),
3648                          OpSizeInBits - N1C->getZExtValue());
3649      // Determine the residual right-shift amount.
3650      signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3651
3652      // If the shift is not a no-op (in which case this should be just a sign
3653      // extend already), the truncated to type is legal, sign_extend is legal
3654      // on that type, and the truncate to that type is both legal and free,
3655      // perform the transform.
3656      if ((ShiftAmt > 0) &&
3657          TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3658          TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3659          TLI.isTruncateFree(VT, TruncVT)) {
3660
3661          SDValue Amt = DAG.getConstant(ShiftAmt,
3662              getShiftAmountTy(N0.getOperand(0).getValueType()));
3663          SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3664                                      N0.getOperand(0), Amt);
3665          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3666                                      Shift);
3667          return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3668                             N->getValueType(0), Trunc);
3669      }
3670    }
3671  }
3672
3673  // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3674  if (N1.getOpcode() == ISD::TRUNCATE &&
3675      N1.getOperand(0).getOpcode() == ISD::AND &&
3676      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3677    SDValue N101 = N1.getOperand(0).getOperand(1);
3678    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3679      EVT TruncVT = N1.getValueType();
3680      SDValue N100 = N1.getOperand(0).getOperand(0);
3681      APInt TruncC = N101C->getAPIntValue();
3682      TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3683      return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3684                         DAG.getNode(ISD::AND, N->getDebugLoc(),
3685                                     TruncVT,
3686                                     DAG.getNode(ISD::TRUNCATE,
3687                                                 N->getDebugLoc(),
3688                                                 TruncVT, N100),
3689                                     DAG.getConstant(TruncC, TruncVT)));
3690    }
3691  }
3692
3693  // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3694  //      if c1 is equal to the number of bits the trunc removes
3695  if (N0.getOpcode() == ISD::TRUNCATE &&
3696      (N0.getOperand(0).getOpcode() == ISD::SRL ||
3697       N0.getOperand(0).getOpcode() == ISD::SRA) &&
3698      N0.getOperand(0).hasOneUse() &&
3699      N0.getOperand(0).getOperand(1).hasOneUse() &&
3700      N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3701    EVT LargeVT = N0.getOperand(0).getValueType();
3702    ConstantSDNode *LargeShiftAmt =
3703      cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3704
3705    if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3706        LargeShiftAmt->getZExtValue()) {
3707      SDValue Amt =
3708        DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3709              getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3710      SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3711                                N0.getOperand(0).getOperand(0), Amt);
3712      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3713    }
3714  }
3715
3716  // Simplify, based on bits shifted out of the LHS.
3717  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3718    return SDValue(N, 0);
3719
3720
3721  // If the sign bit is known to be zero, switch this to a SRL.
3722  if (DAG.SignBitIsZero(N0))
3723    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3724
3725  if (N1C) {
3726    SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3727    if (NewSRA.getNode())
3728      return NewSRA;
3729  }
3730
3731  return SDValue();
3732}
3733
3734SDValue DAGCombiner::visitSRL(SDNode *N) {
3735  SDValue N0 = N->getOperand(0);
3736  SDValue N1 = N->getOperand(1);
3737  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3738  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3739  EVT VT = N0.getValueType();
3740  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3741
3742  // fold (srl c1, c2) -> c1 >>u c2
3743  if (N0C && N1C)
3744    return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3745  // fold (srl 0, x) -> 0
3746  if (N0C && N0C->isNullValue())
3747    return N0;
3748  // fold (srl x, c >= size(x)) -> undef
3749  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3750    return DAG.getUNDEF(VT);
3751  // fold (srl x, 0) -> x
3752  if (N1C && N1C->isNullValue())
3753    return N0;
3754  // if (srl x, c) is known to be zero, return 0
3755  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3756                                   APInt::getAllOnesValue(OpSizeInBits)))
3757    return DAG.getConstant(0, VT);
3758
3759  // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3760  if (N1C && N0.getOpcode() == ISD::SRL &&
3761      N0.getOperand(1).getOpcode() == ISD::Constant) {
3762    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3763    uint64_t c2 = N1C->getZExtValue();
3764    if (c1 + c2 >= OpSizeInBits)
3765      return DAG.getConstant(0, VT);
3766    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3767                       DAG.getConstant(c1 + c2, N1.getValueType()));
3768  }
3769
3770  // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3771  if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3772      N0.getOperand(0).getOpcode() == ISD::SRL &&
3773      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3774    uint64_t c1 =
3775      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3776    uint64_t c2 = N1C->getZExtValue();
3777    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3778    EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3779    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3780    // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3781    if (c1 + OpSizeInBits == InnerShiftSize) {
3782      if (c1 + c2 >= InnerShiftSize)
3783        return DAG.getConstant(0, VT);
3784      return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3785                         DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3786                                     N0.getOperand(0)->getOperand(0),
3787                                     DAG.getConstant(c1 + c2, ShiftCountVT)));
3788    }
3789  }
3790
3791  // fold (srl (shl x, c), c) -> (and x, cst2)
3792  if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3793      N0.getValueSizeInBits() <= 64) {
3794    uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3795    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3796                       DAG.getConstant(~0ULL >> ShAmt, VT));
3797  }
3798
3799
3800  // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3801  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3802    // Shifting in all undef bits?
3803    EVT SmallVT = N0.getOperand(0).getValueType();
3804    if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3805      return DAG.getUNDEF(VT);
3806
3807    if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3808      uint64_t ShiftAmt = N1C->getZExtValue();
3809      SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3810                                       N0.getOperand(0),
3811                          DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3812      AddToWorkList(SmallShift.getNode());
3813      return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3814    }
3815  }
3816
3817  // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3818  // bit, which is unmodified by sra.
3819  if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3820    if (N0.getOpcode() == ISD::SRA)
3821      return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3822  }
3823
3824  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3825  if (N1C && N0.getOpcode() == ISD::CTLZ &&
3826      N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3827    APInt KnownZero, KnownOne;
3828    DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3829
3830    // If any of the input bits are KnownOne, then the input couldn't be all
3831    // zeros, thus the result of the srl will always be zero.
3832    if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3833
3834    // If all of the bits input the to ctlz node are known to be zero, then
3835    // the result of the ctlz is "32" and the result of the shift is one.
3836    APInt UnknownBits = ~KnownZero;
3837    if (UnknownBits == 0) return DAG.getConstant(1, VT);
3838
3839    // Otherwise, check to see if there is exactly one bit input to the ctlz.
3840    if ((UnknownBits & (UnknownBits - 1)) == 0) {
3841      // Okay, we know that only that the single bit specified by UnknownBits
3842      // could be set on input to the CTLZ node. If this bit is set, the SRL
3843      // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3844      // to an SRL/XOR pair, which is likely to simplify more.
3845      unsigned ShAmt = UnknownBits.countTrailingZeros();
3846      SDValue Op = N0.getOperand(0);
3847
3848      if (ShAmt) {
3849        Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3850                  DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3851        AddToWorkList(Op.getNode());
3852      }
3853
3854      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3855                         Op, DAG.getConstant(1, VT));
3856    }
3857  }
3858
3859  // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3860  if (N1.getOpcode() == ISD::TRUNCATE &&
3861      N1.getOperand(0).getOpcode() == ISD::AND &&
3862      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3863    SDValue N101 = N1.getOperand(0).getOperand(1);
3864    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3865      EVT TruncVT = N1.getValueType();
3866      SDValue N100 = N1.getOperand(0).getOperand(0);
3867      APInt TruncC = N101C->getAPIntValue();
3868      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3869      return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3870                         DAG.getNode(ISD::AND, N->getDebugLoc(),
3871                                     TruncVT,
3872                                     DAG.getNode(ISD::TRUNCATE,
3873                                                 N->getDebugLoc(),
3874                                                 TruncVT, N100),
3875                                     DAG.getConstant(TruncC, TruncVT)));
3876    }
3877  }
3878
3879  // fold operands of srl based on knowledge that the low bits are not
3880  // demanded.
3881  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3882    return SDValue(N, 0);
3883
3884  if (N1C) {
3885    SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3886    if (NewSRL.getNode())
3887      return NewSRL;
3888  }
3889
3890  // Attempt to convert a srl of a load into a narrower zero-extending load.
3891  SDValue NarrowLoad = ReduceLoadWidth(N);
3892  if (NarrowLoad.getNode())
3893    return NarrowLoad;
3894
3895  // Here is a common situation. We want to optimize:
3896  //
3897  //   %a = ...
3898  //   %b = and i32 %a, 2
3899  //   %c = srl i32 %b, 1
3900  //   brcond i32 %c ...
3901  //
3902  // into
3903  //
3904  //   %a = ...
3905  //   %b = and %a, 2
3906  //   %c = setcc eq %b, 0
3907  //   brcond %c ...
3908  //
3909  // However when after the source operand of SRL is optimized into AND, the SRL
3910  // itself may not be optimized further. Look for it and add the BRCOND into
3911  // the worklist.
3912  if (N->hasOneUse()) {
3913    SDNode *Use = *N->use_begin();
3914    if (Use->getOpcode() == ISD::BRCOND)
3915      AddToWorkList(Use);
3916    else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3917      // Also look pass the truncate.
3918      Use = *Use->use_begin();
3919      if (Use->getOpcode() == ISD::BRCOND)
3920        AddToWorkList(Use);
3921    }
3922  }
3923
3924  return SDValue();
3925}
3926
3927SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3928  SDValue N0 = N->getOperand(0);
3929  EVT VT = N->getValueType(0);
3930
3931  // fold (ctlz c1) -> c2
3932  if (isa<ConstantSDNode>(N0))
3933    return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3934  return SDValue();
3935}
3936
3937SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
3938  SDValue N0 = N->getOperand(0);
3939  EVT VT = N->getValueType(0);
3940
3941  // fold (ctlz_zero_undef c1) -> c2
3942  if (isa<ConstantSDNode>(N0))
3943    return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3944  return SDValue();
3945}
3946
3947SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3948  SDValue N0 = N->getOperand(0);
3949  EVT VT = N->getValueType(0);
3950
3951  // fold (cttz c1) -> c2
3952  if (isa<ConstantSDNode>(N0))
3953    return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3954  return SDValue();
3955}
3956
3957SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
3958  SDValue N0 = N->getOperand(0);
3959  EVT VT = N->getValueType(0);
3960
3961  // fold (cttz_zero_undef c1) -> c2
3962  if (isa<ConstantSDNode>(N0))
3963    return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
3964  return SDValue();
3965}
3966
3967SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3968  SDValue N0 = N->getOperand(0);
3969  EVT VT = N->getValueType(0);
3970
3971  // fold (ctpop c1) -> c2
3972  if (isa<ConstantSDNode>(N0))
3973    return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3974  return SDValue();
3975}
3976
3977SDValue DAGCombiner::visitSELECT(SDNode *N) {
3978  SDValue N0 = N->getOperand(0);
3979  SDValue N1 = N->getOperand(1);
3980  SDValue N2 = N->getOperand(2);
3981  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3982  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3983  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3984  EVT VT = N->getValueType(0);
3985  EVT VT0 = N0.getValueType();
3986
3987  // fold (select C, X, X) -> X
3988  if (N1 == N2)
3989    return N1;
3990  // fold (select true, X, Y) -> X
3991  if (N0C && !N0C->isNullValue())
3992    return N1;
3993  // fold (select false, X, Y) -> Y
3994  if (N0C && N0C->isNullValue())
3995    return N2;
3996  // fold (select C, 1, X) -> (or C, X)
3997  if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3998    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3999  // fold (select C, 0, 1) -> (xor C, 1)
4000  if (VT.isInteger() &&
4001      (VT0 == MVT::i1 ||
4002       (VT0.isInteger() &&
4003        TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
4004      N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4005    SDValue XORNode;
4006    if (VT == VT0)
4007      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4008                         N0, DAG.getConstant(1, VT0));
4009    XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4010                          N0, DAG.getConstant(1, VT0));
4011    AddToWorkList(XORNode.getNode());
4012    if (VT.bitsGT(VT0))
4013      return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4014    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4015  }
4016  // fold (select C, 0, X) -> (and (not C), X)
4017  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4018    SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4019    AddToWorkList(NOTNode.getNode());
4020    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4021  }
4022  // fold (select C, X, 1) -> (or (not C), X)
4023  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4024    SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4025    AddToWorkList(NOTNode.getNode());
4026    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4027  }
4028  // fold (select C, X, 0) -> (and C, X)
4029  if (VT == MVT::i1 && N2C && N2C->isNullValue())
4030    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4031  // fold (select X, X, Y) -> (or X, Y)
4032  // fold (select X, 1, Y) -> (or X, Y)
4033  if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4034    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4035  // fold (select X, Y, X) -> (and X, Y)
4036  // fold (select X, Y, 0) -> (and X, Y)
4037  if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4038    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4039
4040  // If we can fold this based on the true/false value, do so.
4041  if (SimplifySelectOps(N, N1, N2))
4042    return SDValue(N, 0);  // Don't revisit N.
4043
4044  // fold selects based on a setcc into other things, such as min/max/abs
4045  if (N0.getOpcode() == ISD::SETCC) {
4046    // FIXME:
4047    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4048    // having to say they don't support SELECT_CC on every type the DAG knows
4049    // about, since there is no way to mark an opcode illegal at all value types
4050    if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4051        TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4052      return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4053                         N0.getOperand(0), N0.getOperand(1),
4054                         N1, N2, N0.getOperand(2));
4055    return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4056  }
4057
4058  return SDValue();
4059}
4060
4061SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4062  SDValue N0 = N->getOperand(0);
4063  SDValue N1 = N->getOperand(1);
4064  SDValue N2 = N->getOperand(2);
4065  SDValue N3 = N->getOperand(3);
4066  SDValue N4 = N->getOperand(4);
4067  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4068
4069  // fold select_cc lhs, rhs, x, x, cc -> x
4070  if (N2 == N3)
4071    return N2;
4072
4073  // Determine if the condition we're dealing with is constant
4074  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4075                              N0, N1, CC, N->getDebugLoc(), false);
4076  if (SCC.getNode()) AddToWorkList(SCC.getNode());
4077
4078  if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4079    if (!SCCC->isNullValue())
4080      return N2;    // cond always true -> true val
4081    else
4082      return N3;    // cond always false -> false val
4083  }
4084
4085  // Fold to a simpler select_cc
4086  if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4087    return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4088                       SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4089                       SCC.getOperand(2));
4090
4091  // If we can fold this based on the true/false value, do so.
4092  if (SimplifySelectOps(N, N2, N3))
4093    return SDValue(N, 0);  // Don't revisit N.
4094
4095  // fold select_cc into other things, such as min/max/abs
4096  return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4097}
4098
4099SDValue DAGCombiner::visitSETCC(SDNode *N) {
4100  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4101                       cast<CondCodeSDNode>(N->getOperand(2))->get(),
4102                       N->getDebugLoc());
4103}
4104
4105// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4106// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4107// transformation. Returns true if extension are possible and the above
4108// mentioned transformation is profitable.
4109static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4110                                    unsigned ExtOpc,
4111                                    SmallVector<SDNode*, 4> &ExtendNodes,
4112                                    const TargetLowering &TLI) {
4113  bool HasCopyToRegUses = false;
4114  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4115  for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4116                            UE = N0.getNode()->use_end();
4117       UI != UE; ++UI) {
4118    SDNode *User = *UI;
4119    if (User == N)
4120      continue;
4121    if (UI.getUse().getResNo() != N0.getResNo())
4122      continue;
4123    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4124    if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4125      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4126      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4127        // Sign bits will be lost after a zext.
4128        return false;
4129      bool Add = false;
4130      for (unsigned i = 0; i != 2; ++i) {
4131        SDValue UseOp = User->getOperand(i);
4132        if (UseOp == N0)
4133          continue;
4134        if (!isa<ConstantSDNode>(UseOp))
4135          return false;
4136        Add = true;
4137      }
4138      if (Add)
4139        ExtendNodes.push_back(User);
4140      continue;
4141    }
4142    // If truncates aren't free and there are users we can't
4143    // extend, it isn't worthwhile.
4144    if (!isTruncFree)
4145      return false;
4146    // Remember if this value is live-out.
4147    if (User->getOpcode() == ISD::CopyToReg)
4148      HasCopyToRegUses = true;
4149  }
4150
4151  if (HasCopyToRegUses) {
4152    bool BothLiveOut = false;
4153    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4154         UI != UE; ++UI) {
4155      SDUse &Use = UI.getUse();
4156      if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4157        BothLiveOut = true;
4158        break;
4159      }
4160    }
4161    if (BothLiveOut)
4162      // Both unextended and extended values are live out. There had better be
4163      // a good reason for the transformation.
4164      return ExtendNodes.size();
4165  }
4166  return true;
4167}
4168
4169void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4170                                  SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4171                                  ISD::NodeType ExtType) {
4172  // Extend SetCC uses if necessary.
4173  for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4174    SDNode *SetCC = SetCCs[i];
4175    SmallVector<SDValue, 4> Ops;
4176
4177    for (unsigned j = 0; j != 2; ++j) {
4178      SDValue SOp = SetCC->getOperand(j);
4179      if (SOp == Trunc)
4180        Ops.push_back(ExtLoad);
4181      else
4182        Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4183    }
4184
4185    Ops.push_back(SetCC->getOperand(2));
4186    CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4187                                 &Ops[0], Ops.size()));
4188  }
4189}
4190
4191SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4192  SDValue N0 = N->getOperand(0);
4193  EVT VT = N->getValueType(0);
4194
4195  // fold (sext c1) -> c1
4196  if (isa<ConstantSDNode>(N0))
4197    return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4198
4199  // fold (sext (sext x)) -> (sext x)
4200  // fold (sext (aext x)) -> (sext x)
4201  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4202    return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4203                       N0.getOperand(0));
4204
4205  if (N0.getOpcode() == ISD::TRUNCATE) {
4206    // fold (sext (truncate (load x))) -> (sext (smaller load x))
4207    // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4208    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4209    if (NarrowLoad.getNode()) {
4210      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4211      if (NarrowLoad.getNode() != N0.getNode()) {
4212        CombineTo(N0.getNode(), NarrowLoad);
4213        // CombineTo deleted the truncate, if needed, but not what's under it.
4214        AddToWorkList(oye);
4215      }
4216      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4217    }
4218
4219    // See if the value being truncated is already sign extended.  If so, just
4220    // eliminate the trunc/sext pair.
4221    SDValue Op = N0.getOperand(0);
4222    unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4223    unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4224    unsigned DestBits = VT.getScalarType().getSizeInBits();
4225    unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4226
4227    if (OpBits == DestBits) {
4228      // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4229      // bits, it is already ready.
4230      if (NumSignBits > DestBits-MidBits)
4231        return Op;
4232    } else if (OpBits < DestBits) {
4233      // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4234      // bits, just sext from i32.
4235      if (NumSignBits > OpBits-MidBits)
4236        return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4237    } else {
4238      // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4239      // bits, just truncate to i32.
4240      if (NumSignBits > OpBits-MidBits)
4241        return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4242    }
4243
4244    // fold (sext (truncate x)) -> (sextinreg x).
4245    if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4246                                                 N0.getValueType())) {
4247      if (OpBits < DestBits)
4248        Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4249      else if (OpBits > DestBits)
4250        Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4251      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4252                         DAG.getValueType(N0.getValueType()));
4253    }
4254  }
4255
4256  // fold (sext (load x)) -> (sext (truncate (sextload x)))
4257  // None of the supported targets knows how to perform load and sign extend
4258  // on vectors in one instruction.  We only perform this transformation on
4259  // scalars.
4260  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4261      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4262       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4263    bool DoXform = true;
4264    SmallVector<SDNode*, 4> SetCCs;
4265    if (!N0.hasOneUse())
4266      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4267    if (DoXform) {
4268      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4269      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4270                                       LN0->getChain(),
4271                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4272                                       N0.getValueType(),
4273                                       LN0->isVolatile(), LN0->isNonTemporal(),
4274                                       LN0->getAlignment());
4275      CombineTo(N, ExtLoad);
4276      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4277                                  N0.getValueType(), ExtLoad);
4278      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4279      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4280                      ISD::SIGN_EXTEND);
4281      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4282    }
4283  }
4284
4285  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4286  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4287  if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4288      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4289    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4290    EVT MemVT = LN0->getMemoryVT();
4291    if ((!LegalOperations && !LN0->isVolatile()) ||
4292        TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4293      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4294                                       LN0->getChain(),
4295                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4296                                       MemVT,
4297                                       LN0->isVolatile(), LN0->isNonTemporal(),
4298                                       LN0->getAlignment());
4299      CombineTo(N, ExtLoad);
4300      CombineTo(N0.getNode(),
4301                DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4302                            N0.getValueType(), ExtLoad),
4303                ExtLoad.getValue(1));
4304      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4305    }
4306  }
4307
4308  // fold (sext (and/or/xor (load x), cst)) ->
4309  //      (and/or/xor (sextload x), (sext cst))
4310  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4311       N0.getOpcode() == ISD::XOR) &&
4312      isa<LoadSDNode>(N0.getOperand(0)) &&
4313      N0.getOperand(1).getOpcode() == ISD::Constant &&
4314      TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4315      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4316    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4317    if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4318      bool DoXform = true;
4319      SmallVector<SDNode*, 4> SetCCs;
4320      if (!N0.hasOneUse())
4321        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4322                                          SetCCs, TLI);
4323      if (DoXform) {
4324        SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4325                                         LN0->getChain(), LN0->getBasePtr(),
4326                                         LN0->getPointerInfo(),
4327                                         LN0->getMemoryVT(),
4328                                         LN0->isVolatile(),
4329                                         LN0->isNonTemporal(),
4330                                         LN0->getAlignment());
4331        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4332        Mask = Mask.sext(VT.getSizeInBits());
4333        SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4334                                  ExtLoad, DAG.getConstant(Mask, VT));
4335        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4336                                    N0.getOperand(0).getDebugLoc(),
4337                                    N0.getOperand(0).getValueType(), ExtLoad);
4338        CombineTo(N, And);
4339        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4340        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4341                        ISD::SIGN_EXTEND);
4342        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4343      }
4344    }
4345  }
4346
4347  if (N0.getOpcode() == ISD::SETCC) {
4348    // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4349    // Only do this before legalize for now.
4350    if (VT.isVector() && !LegalOperations) {
4351      EVT N0VT = N0.getOperand(0).getValueType();
4352      // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4353      // of the same size as the compared operands. Only optimize sext(setcc())
4354      // if this is the case.
4355      EVT SVT = TLI.getSetCCResultType(N0VT);
4356
4357      // We know that the # elements of the results is the same as the
4358      // # elements of the compare (and the # elements of the compare result
4359      // for that matter).  Check to see that they are the same size.  If so,
4360      // we know that the element size of the sext'd result matches the
4361      // element size of the compare operands.
4362      if (VT.getSizeInBits() == SVT.getSizeInBits())
4363        return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4364                             N0.getOperand(1),
4365                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
4366      // If the desired elements are smaller or larger than the source
4367      // elements we can use a matching integer vector type and then
4368      // truncate/sign extend
4369      else {
4370        EVT MatchingElementType =
4371          EVT::getIntegerVT(*DAG.getContext(),
4372                            N0VT.getScalarType().getSizeInBits());
4373        EVT MatchingVectorType =
4374          EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4375                           N0VT.getVectorNumElements());
4376
4377        if (SVT == MatchingVectorType) {
4378          SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4379                                 N0.getOperand(0), N0.getOperand(1),
4380                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4381          return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4382        }
4383      }
4384    }
4385
4386    // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4387    unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4388    SDValue NegOne =
4389      DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4390    SDValue SCC =
4391      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4392                       NegOne, DAG.getConstant(0, VT),
4393                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4394    if (SCC.getNode()) return SCC;
4395    if (!LegalOperations ||
4396        TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4397      return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4398                         DAG.getSetCC(N->getDebugLoc(),
4399                                      TLI.getSetCCResultType(VT),
4400                                      N0.getOperand(0), N0.getOperand(1),
4401                                 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4402                         NegOne, DAG.getConstant(0, VT));
4403  }
4404
4405  // fold (sext x) -> (zext x) if the sign bit is known zero.
4406  if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4407      DAG.SignBitIsZero(N0))
4408    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4409
4410  return SDValue();
4411}
4412
4413// isTruncateOf - If N is a truncate of some other value, return true, record
4414// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4415// This function computes KnownZero to avoid a duplicated call to
4416// ComputeMaskedBits in the caller.
4417static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4418                         APInt &KnownZero) {
4419  APInt KnownOne;
4420  if (N->getOpcode() == ISD::TRUNCATE) {
4421    Op = N->getOperand(0);
4422    DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4423    return true;
4424  }
4425
4426  if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4427      cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4428    return false;
4429
4430  SDValue Op0 = N->getOperand(0);
4431  SDValue Op1 = N->getOperand(1);
4432  assert(Op0.getValueType() == Op1.getValueType());
4433
4434  ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4435  ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4436  if (COp0 && COp0->isNullValue())
4437    Op = Op1;
4438  else if (COp1 && COp1->isNullValue())
4439    Op = Op0;
4440  else
4441    return false;
4442
4443  DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4444
4445  if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4446    return false;
4447
4448  return true;
4449}
4450
4451SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4452  SDValue N0 = N->getOperand(0);
4453  EVT VT = N->getValueType(0);
4454
4455  // fold (zext c1) -> c1
4456  if (isa<ConstantSDNode>(N0))
4457    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4458  // fold (zext (zext x)) -> (zext x)
4459  // fold (zext (aext x)) -> (zext x)
4460  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4461    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4462                       N0.getOperand(0));
4463
4464  // fold (zext (truncate x)) -> (zext x) or
4465  //      (zext (truncate x)) -> (truncate x)
4466  // This is valid when the truncated bits of x are already zero.
4467  // FIXME: We should extend this to work for vectors too.
4468  SDValue Op;
4469  APInt KnownZero;
4470  if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4471    APInt TruncatedBits =
4472      (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4473      APInt(Op.getValueSizeInBits(), 0) :
4474      APInt::getBitsSet(Op.getValueSizeInBits(),
4475                        N0.getValueSizeInBits(),
4476                        std::min(Op.getValueSizeInBits(),
4477                                 VT.getSizeInBits()));
4478    if (TruncatedBits == (KnownZero & TruncatedBits)) {
4479      if (VT.bitsGT(Op.getValueType()))
4480        return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4481      if (VT.bitsLT(Op.getValueType()))
4482        return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4483
4484      return Op;
4485    }
4486  }
4487
4488  // fold (zext (truncate (load x))) -> (zext (smaller load x))
4489  // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4490  if (N0.getOpcode() == ISD::TRUNCATE) {
4491    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4492    if (NarrowLoad.getNode()) {
4493      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4494      if (NarrowLoad.getNode() != N0.getNode()) {
4495        CombineTo(N0.getNode(), NarrowLoad);
4496        // CombineTo deleted the truncate, if needed, but not what's under it.
4497        AddToWorkList(oye);
4498      }
4499      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4500    }
4501  }
4502
4503  // fold (zext (truncate x)) -> (and x, mask)
4504  if (N0.getOpcode() == ISD::TRUNCATE &&
4505      (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4506
4507    // fold (zext (truncate (load x))) -> (zext (smaller load x))
4508    // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4509    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4510    if (NarrowLoad.getNode()) {
4511      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4512      if (NarrowLoad.getNode() != N0.getNode()) {
4513        CombineTo(N0.getNode(), NarrowLoad);
4514        // CombineTo deleted the truncate, if needed, but not what's under it.
4515        AddToWorkList(oye);
4516      }
4517      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4518    }
4519
4520    SDValue Op = N0.getOperand(0);
4521    if (Op.getValueType().bitsLT(VT)) {
4522      Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4523    } else if (Op.getValueType().bitsGT(VT)) {
4524      Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4525    }
4526    return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4527                                  N0.getValueType().getScalarType());
4528  }
4529
4530  // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4531  // if either of the casts is not free.
4532  if (N0.getOpcode() == ISD::AND &&
4533      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4534      N0.getOperand(1).getOpcode() == ISD::Constant &&
4535      (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4536                           N0.getValueType()) ||
4537       !TLI.isZExtFree(N0.getValueType(), VT))) {
4538    SDValue X = N0.getOperand(0).getOperand(0);
4539    if (X.getValueType().bitsLT(VT)) {
4540      X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4541    } else if (X.getValueType().bitsGT(VT)) {
4542      X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4543    }
4544    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4545    Mask = Mask.zext(VT.getSizeInBits());
4546    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4547                       X, DAG.getConstant(Mask, VT));
4548  }
4549
4550  // fold (zext (load x)) -> (zext (truncate (zextload x)))
4551  // None of the supported targets knows how to perform load and vector_zext
4552  // on vectors in one instruction.  We only perform this transformation on
4553  // scalars.
4554  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4555      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4556       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4557    bool DoXform = true;
4558    SmallVector<SDNode*, 4> SetCCs;
4559    if (!N0.hasOneUse())
4560      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4561    if (DoXform) {
4562      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4563      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4564                                       LN0->getChain(),
4565                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4566                                       N0.getValueType(),
4567                                       LN0->isVolatile(), LN0->isNonTemporal(),
4568                                       LN0->getAlignment());
4569      CombineTo(N, ExtLoad);
4570      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4571                                  N0.getValueType(), ExtLoad);
4572      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4573
4574      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4575                      ISD::ZERO_EXTEND);
4576      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4577    }
4578  }
4579
4580  // fold (zext (and/or/xor (load x), cst)) ->
4581  //      (and/or/xor (zextload x), (zext cst))
4582  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4583       N0.getOpcode() == ISD::XOR) &&
4584      isa<LoadSDNode>(N0.getOperand(0)) &&
4585      N0.getOperand(1).getOpcode() == ISD::Constant &&
4586      TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4587      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4588    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4589    if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4590      bool DoXform = true;
4591      SmallVector<SDNode*, 4> SetCCs;
4592      if (!N0.hasOneUse())
4593        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4594                                          SetCCs, TLI);
4595      if (DoXform) {
4596        SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4597                                         LN0->getChain(), LN0->getBasePtr(),
4598                                         LN0->getPointerInfo(),
4599                                         LN0->getMemoryVT(),
4600                                         LN0->isVolatile(),
4601                                         LN0->isNonTemporal(),
4602                                         LN0->getAlignment());
4603        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4604        Mask = Mask.zext(VT.getSizeInBits());
4605        SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4606                                  ExtLoad, DAG.getConstant(Mask, VT));
4607        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4608                                    N0.getOperand(0).getDebugLoc(),
4609                                    N0.getOperand(0).getValueType(), ExtLoad);
4610        CombineTo(N, And);
4611        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4612        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4613                        ISD::ZERO_EXTEND);
4614        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4615      }
4616    }
4617  }
4618
4619  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4620  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4621  if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4622      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4623    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4624    EVT MemVT = LN0->getMemoryVT();
4625    if ((!LegalOperations && !LN0->isVolatile()) ||
4626        TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4627      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4628                                       LN0->getChain(),
4629                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4630                                       MemVT,
4631                                       LN0->isVolatile(), LN0->isNonTemporal(),
4632                                       LN0->getAlignment());
4633      CombineTo(N, ExtLoad);
4634      CombineTo(N0.getNode(),
4635                DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4636                            ExtLoad),
4637                ExtLoad.getValue(1));
4638      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4639    }
4640  }
4641
4642  if (N0.getOpcode() == ISD::SETCC) {
4643    if (!LegalOperations && VT.isVector()) {
4644      // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4645      // Only do this before legalize for now.
4646      EVT N0VT = N0.getOperand(0).getValueType();
4647      EVT EltVT = VT.getVectorElementType();
4648      SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4649                                    DAG.getConstant(1, EltVT));
4650      if (VT.getSizeInBits() == N0VT.getSizeInBits())
4651        // We know that the # elements of the results is the same as the
4652        // # elements of the compare (and the # elements of the compare result
4653        // for that matter).  Check to see that they are the same size.  If so,
4654        // we know that the element size of the sext'd result matches the
4655        // element size of the compare operands.
4656        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4657                           DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4658                                         N0.getOperand(1),
4659                                 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4660                           DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4661                                       &OneOps[0], OneOps.size()));
4662
4663      // If the desired elements are smaller or larger than the source
4664      // elements we can use a matching integer vector type and then
4665      // truncate/sign extend
4666      EVT MatchingElementType =
4667        EVT::getIntegerVT(*DAG.getContext(),
4668                          N0VT.getScalarType().getSizeInBits());
4669      EVT MatchingVectorType =
4670        EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4671                         N0VT.getVectorNumElements());
4672      SDValue VsetCC =
4673        DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4674                      N0.getOperand(1),
4675                      cast<CondCodeSDNode>(N0.getOperand(2))->get());
4676      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4677                         DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4678                         DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4679                                     &OneOps[0], OneOps.size()));
4680    }
4681
4682    // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4683    SDValue SCC =
4684      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4685                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4686                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4687    if (SCC.getNode()) return SCC;
4688  }
4689
4690  // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4691  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4692      isa<ConstantSDNode>(N0.getOperand(1)) &&
4693      N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4694      N0.hasOneUse()) {
4695    SDValue ShAmt = N0.getOperand(1);
4696    unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4697    if (N0.getOpcode() == ISD::SHL) {
4698      SDValue InnerZExt = N0.getOperand(0);
4699      // If the original shl may be shifting out bits, do not perform this
4700      // transformation.
4701      unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4702        InnerZExt.getOperand(0).getValueType().getSizeInBits();
4703      if (ShAmtVal > KnownZeroBits)
4704        return SDValue();
4705    }
4706
4707    DebugLoc DL = N->getDebugLoc();
4708
4709    // Ensure that the shift amount is wide enough for the shifted value.
4710    if (VT.getSizeInBits() >= 256)
4711      ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4712
4713    return DAG.getNode(N0.getOpcode(), DL, VT,
4714                       DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4715                       ShAmt);
4716  }
4717
4718  return SDValue();
4719}
4720
4721SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4722  SDValue N0 = N->getOperand(0);
4723  EVT VT = N->getValueType(0);
4724
4725  // fold (aext c1) -> c1
4726  if (isa<ConstantSDNode>(N0))
4727    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4728  // fold (aext (aext x)) -> (aext x)
4729  // fold (aext (zext x)) -> (zext x)
4730  // fold (aext (sext x)) -> (sext x)
4731  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4732      N0.getOpcode() == ISD::ZERO_EXTEND ||
4733      N0.getOpcode() == ISD::SIGN_EXTEND)
4734    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4735
4736  // fold (aext (truncate (load x))) -> (aext (smaller load x))
4737  // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4738  if (N0.getOpcode() == ISD::TRUNCATE) {
4739    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4740    if (NarrowLoad.getNode()) {
4741      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4742      if (NarrowLoad.getNode() != N0.getNode()) {
4743        CombineTo(N0.getNode(), NarrowLoad);
4744        // CombineTo deleted the truncate, if needed, but not what's under it.
4745        AddToWorkList(oye);
4746      }
4747      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4748    }
4749  }
4750
4751  // fold (aext (truncate x))
4752  if (N0.getOpcode() == ISD::TRUNCATE) {
4753    SDValue TruncOp = N0.getOperand(0);
4754    if (TruncOp.getValueType() == VT)
4755      return TruncOp; // x iff x size == zext size.
4756    if (TruncOp.getValueType().bitsGT(VT))
4757      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4758    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4759  }
4760
4761  // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4762  // if the trunc is not free.
4763  if (N0.getOpcode() == ISD::AND &&
4764      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4765      N0.getOperand(1).getOpcode() == ISD::Constant &&
4766      !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4767                          N0.getValueType())) {
4768    SDValue X = N0.getOperand(0).getOperand(0);
4769    if (X.getValueType().bitsLT(VT)) {
4770      X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4771    } else if (X.getValueType().bitsGT(VT)) {
4772      X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4773    }
4774    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4775    Mask = Mask.zext(VT.getSizeInBits());
4776    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4777                       X, DAG.getConstant(Mask, VT));
4778  }
4779
4780  // fold (aext (load x)) -> (aext (truncate (extload x)))
4781  // None of the supported targets knows how to perform load and any_ext
4782  // on vectors in one instruction.  We only perform this transformation on
4783  // scalars.
4784  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4785      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4786       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4787    bool DoXform = true;
4788    SmallVector<SDNode*, 4> SetCCs;
4789    if (!N0.hasOneUse())
4790      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4791    if (DoXform) {
4792      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4793      SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4794                                       LN0->getChain(),
4795                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4796                                       N0.getValueType(),
4797                                       LN0->isVolatile(), LN0->isNonTemporal(),
4798                                       LN0->getAlignment());
4799      CombineTo(N, ExtLoad);
4800      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4801                                  N0.getValueType(), ExtLoad);
4802      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4803      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4804                      ISD::ANY_EXTEND);
4805      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4806    }
4807  }
4808
4809  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4810  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4811  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4812  if (N0.getOpcode() == ISD::LOAD &&
4813      !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4814      N0.hasOneUse()) {
4815    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4816    EVT MemVT = LN0->getMemoryVT();
4817    SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4818                                     VT, LN0->getChain(), LN0->getBasePtr(),
4819                                     LN0->getPointerInfo(), MemVT,
4820                                     LN0->isVolatile(), LN0->isNonTemporal(),
4821                                     LN0->getAlignment());
4822    CombineTo(N, ExtLoad);
4823    CombineTo(N0.getNode(),
4824              DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4825                          N0.getValueType(), ExtLoad),
4826              ExtLoad.getValue(1));
4827    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4828  }
4829
4830  if (N0.getOpcode() == ISD::SETCC) {
4831    // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4832    // Only do this before legalize for now.
4833    if (VT.isVector() && !LegalOperations) {
4834      EVT N0VT = N0.getOperand(0).getValueType();
4835        // We know that the # elements of the results is the same as the
4836        // # elements of the compare (and the # elements of the compare result
4837        // for that matter).  Check to see that they are the same size.  If so,
4838        // we know that the element size of the sext'd result matches the
4839        // element size of the compare operands.
4840      if (VT.getSizeInBits() == N0VT.getSizeInBits())
4841        return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4842                             N0.getOperand(1),
4843                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
4844      // If the desired elements are smaller or larger than the source
4845      // elements we can use a matching integer vector type and then
4846      // truncate/sign extend
4847      else {
4848        EVT MatchingElementType =
4849          EVT::getIntegerVT(*DAG.getContext(),
4850                            N0VT.getScalarType().getSizeInBits());
4851        EVT MatchingVectorType =
4852          EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4853                           N0VT.getVectorNumElements());
4854        SDValue VsetCC =
4855          DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4856                        N0.getOperand(1),
4857                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
4858        return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4859      }
4860    }
4861
4862    // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4863    SDValue SCC =
4864      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4865                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4866                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4867    if (SCC.getNode())
4868      return SCC;
4869  }
4870
4871  return SDValue();
4872}
4873
4874/// GetDemandedBits - See if the specified operand can be simplified with the
4875/// knowledge that only the bits specified by Mask are used.  If so, return the
4876/// simpler operand, otherwise return a null SDValue.
4877SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4878  switch (V.getOpcode()) {
4879  default: break;
4880  case ISD::Constant: {
4881    const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4882    assert(CV != 0 && "Const value should be ConstSDNode.");
4883    const APInt &CVal = CV->getAPIntValue();
4884    APInt NewVal = CVal & Mask;
4885    if (NewVal != CVal) {
4886      return DAG.getConstant(NewVal, V.getValueType());
4887    }
4888    break;
4889  }
4890  case ISD::OR:
4891  case ISD::XOR:
4892    // If the LHS or RHS don't contribute bits to the or, drop them.
4893    if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4894      return V.getOperand(1);
4895    if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4896      return V.getOperand(0);
4897    break;
4898  case ISD::SRL:
4899    // Only look at single-use SRLs.
4900    if (!V.getNode()->hasOneUse())
4901      break;
4902    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4903      // See if we can recursively simplify the LHS.
4904      unsigned Amt = RHSC->getZExtValue();
4905
4906      // Watch out for shift count overflow though.
4907      if (Amt >= Mask.getBitWidth()) break;
4908      APInt NewMask = Mask << Amt;
4909      SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4910      if (SimplifyLHS.getNode())
4911        return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4912                           SimplifyLHS, V.getOperand(1));
4913    }
4914  }
4915  return SDValue();
4916}
4917
4918/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4919/// bits and then truncated to a narrower type and where N is a multiple
4920/// of number of bits of the narrower type, transform it to a narrower load
4921/// from address + N / num of bits of new type. If the result is to be
4922/// extended, also fold the extension to form a extending load.
4923SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4924  unsigned Opc = N->getOpcode();
4925
4926  ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4927  SDValue N0 = N->getOperand(0);
4928  EVT VT = N->getValueType(0);
4929  EVT ExtVT = VT;
4930
4931  // This transformation isn't valid for vector loads.
4932  if (VT.isVector())
4933    return SDValue();
4934
4935  // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4936  // extended to VT.
4937  if (Opc == ISD::SIGN_EXTEND_INREG) {
4938    ExtType = ISD::SEXTLOAD;
4939    ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4940  } else if (Opc == ISD::SRL) {
4941    // Another special-case: SRL is basically zero-extending a narrower value.
4942    ExtType = ISD::ZEXTLOAD;
4943    N0 = SDValue(N, 0);
4944    ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4945    if (!N01) return SDValue();
4946    ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4947                              VT.getSizeInBits() - N01->getZExtValue());
4948  }
4949  if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4950    return SDValue();
4951
4952  unsigned EVTBits = ExtVT.getSizeInBits();
4953
4954  // Do not generate loads of non-round integer types since these can
4955  // be expensive (and would be wrong if the type is not byte sized).
4956  if (!ExtVT.isRound())
4957    return SDValue();
4958
4959  unsigned ShAmt = 0;
4960  if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4961    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4962      ShAmt = N01->getZExtValue();
4963      // Is the shift amount a multiple of size of VT?
4964      if ((ShAmt & (EVTBits-1)) == 0) {
4965        N0 = N0.getOperand(0);
4966        // Is the load width a multiple of size of VT?
4967        if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4968          return SDValue();
4969      }
4970
4971      // At this point, we must have a load or else we can't do the transform.
4972      if (!isa<LoadSDNode>(N0)) return SDValue();
4973
4974      // If the shift amount is larger than the input type then we're not
4975      // accessing any of the loaded bytes.  If the load was a zextload/extload
4976      // then the result of the shift+trunc is zero/undef (handled elsewhere).
4977      // If the load was a sextload then the result is a splat of the sign bit
4978      // of the extended byte.  This is not worth optimizing for.
4979      if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4980        return SDValue();
4981    }
4982  }
4983
4984  // If the load is shifted left (and the result isn't shifted back right),
4985  // we can fold the truncate through the shift.
4986  unsigned ShLeftAmt = 0;
4987  if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4988      ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4989    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4990      ShLeftAmt = N01->getZExtValue();
4991      N0 = N0.getOperand(0);
4992    }
4993  }
4994
4995  // If we haven't found a load, we can't narrow it.  Don't transform one with
4996  // multiple uses, this would require adding a new load.
4997  if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4998      // Don't change the width of a volatile load.
4999      cast<LoadSDNode>(N0)->isVolatile())
5000    return SDValue();
5001
5002  // Verify that we are actually reducing a load width here.
5003  if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
5004    return SDValue();
5005
5006  LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5007  EVT PtrType = N0.getOperand(1).getValueType();
5008
5009  // For big endian targets, we need to adjust the offset to the pointer to
5010  // load the correct bytes.
5011  if (TLI.isBigEndian()) {
5012    unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5013    unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5014    ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5015  }
5016
5017  uint64_t PtrOff = ShAmt / 8;
5018  unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5019  SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5020                               PtrType, LN0->getBasePtr(),
5021                               DAG.getConstant(PtrOff, PtrType));
5022  AddToWorkList(NewPtr.getNode());
5023
5024  SDValue Load;
5025  if (ExtType == ISD::NON_EXTLOAD)
5026    Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5027                        LN0->getPointerInfo().getWithOffset(PtrOff),
5028                        LN0->isVolatile(), LN0->isNonTemporal(),
5029                        LN0->isInvariant(), NewAlign);
5030  else
5031    Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5032                          LN0->getPointerInfo().getWithOffset(PtrOff),
5033                          ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5034                          NewAlign);
5035
5036  // Replace the old load's chain with the new load's chain.
5037  WorkListRemover DeadNodes(*this);
5038  DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5039
5040  // Shift the result left, if we've swallowed a left shift.
5041  SDValue Result = Load;
5042  if (ShLeftAmt != 0) {
5043    EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5044    if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5045      ShImmTy = VT;
5046    Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5047                         Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5048  }
5049
5050  // Return the new loaded value.
5051  return Result;
5052}
5053
5054SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5055  SDValue N0 = N->getOperand(0);
5056  SDValue N1 = N->getOperand(1);
5057  EVT VT = N->getValueType(0);
5058  EVT EVT = cast<VTSDNode>(N1)->getVT();
5059  unsigned VTBits = VT.getScalarType().getSizeInBits();
5060  unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5061
5062  // fold (sext_in_reg c1) -> c1
5063  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5064    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5065
5066  // If the input is already sign extended, just drop the extension.
5067  if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5068    return N0;
5069
5070  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5071  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5072      EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5073    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5074                       N0.getOperand(0), N1);
5075  }
5076
5077  // fold (sext_in_reg (sext x)) -> (sext x)
5078  // fold (sext_in_reg (aext x)) -> (sext x)
5079  // if x is small enough.
5080  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5081    SDValue N00 = N0.getOperand(0);
5082    if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5083        (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5084      return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5085  }
5086
5087  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5088  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5089    return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5090
5091  // fold operands of sext_in_reg based on knowledge that the top bits are not
5092  // demanded.
5093  if (SimplifyDemandedBits(SDValue(N, 0)))
5094    return SDValue(N, 0);
5095
5096  // fold (sext_in_reg (load x)) -> (smaller sextload x)
5097  // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5098  SDValue NarrowLoad = ReduceLoadWidth(N);
5099  if (NarrowLoad.getNode())
5100    return NarrowLoad;
5101
5102  // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5103  // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5104  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5105  if (N0.getOpcode() == ISD::SRL) {
5106    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5107      if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5108        // We can turn this into an SRA iff the input to the SRL is already sign
5109        // extended enough.
5110        unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5111        if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5112          return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5113                             N0.getOperand(0), N0.getOperand(1));
5114      }
5115  }
5116
5117  // fold (sext_inreg (extload x)) -> (sextload x)
5118  if (ISD::isEXTLoad(N0.getNode()) &&
5119      ISD::isUNINDEXEDLoad(N0.getNode()) &&
5120      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5121      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5122       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5123    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5124    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5125                                     LN0->getChain(),
5126                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5127                                     EVT,
5128                                     LN0->isVolatile(), LN0->isNonTemporal(),
5129                                     LN0->getAlignment());
5130    CombineTo(N, ExtLoad);
5131    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5132    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5133  }
5134  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5135  if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5136      N0.hasOneUse() &&
5137      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5138      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5139       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5140    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5141    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5142                                     LN0->getChain(),
5143                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5144                                     EVT,
5145                                     LN0->isVolatile(), LN0->isNonTemporal(),
5146                                     LN0->getAlignment());
5147    CombineTo(N, ExtLoad);
5148    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5149    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5150  }
5151
5152  // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5153  if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5154    SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5155                                       N0.getOperand(1), false);
5156    if (BSwap.getNode() != 0)
5157      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5158                         BSwap, N1);
5159  }
5160
5161  return SDValue();
5162}
5163
5164SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5165  SDValue N0 = N->getOperand(0);
5166  EVT VT = N->getValueType(0);
5167  bool isLE = TLI.isLittleEndian();
5168
5169  // noop truncate
5170  if (N0.getValueType() == N->getValueType(0))
5171    return N0;
5172  // fold (truncate c1) -> c1
5173  if (isa<ConstantSDNode>(N0))
5174    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5175  // fold (truncate (truncate x)) -> (truncate x)
5176  if (N0.getOpcode() == ISD::TRUNCATE)
5177    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5178  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5179  if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5180      N0.getOpcode() == ISD::SIGN_EXTEND ||
5181      N0.getOpcode() == ISD::ANY_EXTEND) {
5182    if (N0.getOperand(0).getValueType().bitsLT(VT))
5183      // if the source is smaller than the dest, we still need an extend
5184      return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5185                         N0.getOperand(0));
5186    else if (N0.getOperand(0).getValueType().bitsGT(VT))
5187      // if the source is larger than the dest, than we just need the truncate
5188      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5189    else
5190      // if the source and dest are the same type, we can drop both the extend
5191      // and the truncate.
5192      return N0.getOperand(0);
5193  }
5194
5195  // Fold extract-and-trunc into a narrow extract. For example:
5196  //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5197  //   i32 y = TRUNCATE(i64 x)
5198  //        -- becomes --
5199  //   v16i8 b = BITCAST (v2i64 val)
5200  //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5201  //
5202  // Note: We only run this optimization after type legalization (which often
5203  // creates this pattern) and before operation legalization after which
5204  // we need to be more careful about the vector instructions that we generate.
5205  if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5206      LegalTypes && !LegalOperations && N0->hasOneUse()) {
5207
5208    EVT VecTy = N0.getOperand(0).getValueType();
5209    EVT ExTy = N0.getValueType();
5210    EVT TrTy = N->getValueType(0);
5211
5212    unsigned NumElem = VecTy.getVectorNumElements();
5213    unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5214
5215    EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5216    assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5217
5218    SDValue EltNo = N0->getOperand(1);
5219    if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5220      int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5221
5222      int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5223
5224      SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5225                              NVT, N0.getOperand(0));
5226
5227      return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5228                         N->getDebugLoc(), TrTy, V,
5229                         DAG.getConstant(Index, MVT::i32));
5230    }
5231  }
5232
5233  // See if we can simplify the input to this truncate through knowledge that
5234  // only the low bits are being used.
5235  // For example "trunc (or (shl x, 8), y)" // -> trunc y
5236  // Currently we only perform this optimization on scalars because vectors
5237  // may have different active low bits.
5238  if (!VT.isVector()) {
5239    SDValue Shorter =
5240      GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5241                                               VT.getSizeInBits()));
5242    if (Shorter.getNode())
5243      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5244  }
5245  // fold (truncate (load x)) -> (smaller load x)
5246  // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5247  if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5248    SDValue Reduced = ReduceLoadWidth(N);
5249    if (Reduced.getNode())
5250      return Reduced;
5251  }
5252
5253  // Simplify the operands using demanded-bits information.
5254  if (!VT.isVector() &&
5255      SimplifyDemandedBits(SDValue(N, 0)))
5256    return SDValue(N, 0);
5257
5258  return SDValue();
5259}
5260
5261static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5262  SDValue Elt = N->getOperand(i);
5263  if (Elt.getOpcode() != ISD::MERGE_VALUES)
5264    return Elt.getNode();
5265  return Elt.getOperand(Elt.getResNo()).getNode();
5266}
5267
5268/// CombineConsecutiveLoads - build_pair (load, load) -> load
5269/// if load locations are consecutive.
5270SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5271  assert(N->getOpcode() == ISD::BUILD_PAIR);
5272
5273  LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5274  LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5275  if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5276      LD1->getPointerInfo().getAddrSpace() !=
5277         LD2->getPointerInfo().getAddrSpace())
5278    return SDValue();
5279  EVT LD1VT = LD1->getValueType(0);
5280
5281  if (ISD::isNON_EXTLoad(LD2) &&
5282      LD2->hasOneUse() &&
5283      // If both are volatile this would reduce the number of volatile loads.
5284      // If one is volatile it might be ok, but play conservative and bail out.
5285      !LD1->isVolatile() &&
5286      !LD2->isVolatile() &&
5287      DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5288    unsigned Align = LD1->getAlignment();
5289    unsigned NewAlign = TLI.getTargetData()->
5290      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5291
5292    if (NewAlign <= Align &&
5293        (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5294      return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5295                         LD1->getBasePtr(), LD1->getPointerInfo(),
5296                         false, false, false, Align);
5297  }
5298
5299  return SDValue();
5300}
5301
5302SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5303  SDValue N0 = N->getOperand(0);
5304  EVT VT = N->getValueType(0);
5305
5306  // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5307  // Only do this before legalize, since afterward the target may be depending
5308  // on the bitconvert.
5309  // First check to see if this is all constant.
5310  if (!LegalTypes &&
5311      N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5312      VT.isVector()) {
5313    bool isSimple = true;
5314    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5315      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5316          N0.getOperand(i).getOpcode() != ISD::Constant &&
5317          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5318        isSimple = false;
5319        break;
5320      }
5321
5322    EVT DestEltVT = N->getValueType(0).getVectorElementType();
5323    assert(!DestEltVT.isVector() &&
5324           "Element type of vector ValueType must not be vector!");
5325    if (isSimple)
5326      return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5327  }
5328
5329  // If the input is a constant, let getNode fold it.
5330  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5331    SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5332    if (Res.getNode() != N) {
5333      if (!LegalOperations ||
5334          TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5335        return Res;
5336
5337      // Folding it resulted in an illegal node, and it's too late to
5338      // do that. Clean up the old node and forego the transformation.
5339      // Ideally this won't happen very often, because instcombine
5340      // and the earlier dagcombine runs (where illegal nodes are
5341      // permitted) should have folded most of them already.
5342      DAG.DeleteNode(Res.getNode());
5343    }
5344  }
5345
5346  // (conv (conv x, t1), t2) -> (conv x, t2)
5347  if (N0.getOpcode() == ISD::BITCAST)
5348    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5349                       N0.getOperand(0));
5350
5351  // fold (conv (load x)) -> (load (conv*)x)
5352  // If the resultant load doesn't need a higher alignment than the original!
5353  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5354      // Do not change the width of a volatile load.
5355      !cast<LoadSDNode>(N0)->isVolatile() &&
5356      (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5357    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5358    unsigned Align = TLI.getTargetData()->
5359      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5360    unsigned OrigAlign = LN0->getAlignment();
5361
5362    if (Align <= OrigAlign) {
5363      SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5364                                 LN0->getBasePtr(), LN0->getPointerInfo(),
5365                                 LN0->isVolatile(), LN0->isNonTemporal(),
5366                                 LN0->isInvariant(), OrigAlign);
5367      AddToWorkList(N);
5368      CombineTo(N0.getNode(),
5369                DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5370                            N0.getValueType(), Load),
5371                Load.getValue(1));
5372      return Load;
5373    }
5374  }
5375
5376  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5377  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5378  // This often reduces constant pool loads.
5379  if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5380       (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5381      N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
5382    SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5383                                  N0.getOperand(0));
5384    AddToWorkList(NewConv.getNode());
5385
5386    APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5387    if (N0.getOpcode() == ISD::FNEG)
5388      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5389                         NewConv, DAG.getConstant(SignBit, VT));
5390    assert(N0.getOpcode() == ISD::FABS);
5391    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5392                       NewConv, DAG.getConstant(~SignBit, VT));
5393  }
5394
5395  // fold (bitconvert (fcopysign cst, x)) ->
5396  //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5397  // Note that we don't handle (copysign x, cst) because this can always be
5398  // folded to an fneg or fabs.
5399  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5400      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5401      VT.isInteger() && !VT.isVector()) {
5402    unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5403    EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5404    if (isTypeLegal(IntXVT)) {
5405      SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5406                              IntXVT, N0.getOperand(1));
5407      AddToWorkList(X.getNode());
5408
5409      // If X has a different width than the result/lhs, sext it or truncate it.
5410      unsigned VTWidth = VT.getSizeInBits();
5411      if (OrigXWidth < VTWidth) {
5412        X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5413        AddToWorkList(X.getNode());
5414      } else if (OrigXWidth > VTWidth) {
5415        // To get the sign bit in the right place, we have to shift it right
5416        // before truncating.
5417        X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5418                        X.getValueType(), X,
5419                        DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5420        AddToWorkList(X.getNode());
5421        X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5422        AddToWorkList(X.getNode());
5423      }
5424
5425      APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5426      X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5427                      X, DAG.getConstant(SignBit, VT));
5428      AddToWorkList(X.getNode());
5429
5430      SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5431                                VT, N0.getOperand(0));
5432      Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5433                        Cst, DAG.getConstant(~SignBit, VT));
5434      AddToWorkList(Cst.getNode());
5435
5436      return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5437    }
5438  }
5439
5440  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5441  if (N0.getOpcode() == ISD::BUILD_PAIR) {
5442    SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5443    if (CombineLD.getNode())
5444      return CombineLD;
5445  }
5446
5447  return SDValue();
5448}
5449
5450SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5451  EVT VT = N->getValueType(0);
5452  return CombineConsecutiveLoads(N, VT);
5453}
5454
5455/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5456/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5457/// destination element value type.
5458SDValue DAGCombiner::
5459ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5460  EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5461
5462  // If this is already the right type, we're done.
5463  if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5464
5465  unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5466  unsigned DstBitSize = DstEltVT.getSizeInBits();
5467
5468  // If this is a conversion of N elements of one type to N elements of another
5469  // type, convert each element.  This handles FP<->INT cases.
5470  if (SrcBitSize == DstBitSize) {
5471    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5472                              BV->getValueType(0).getVectorNumElements());
5473
5474    // Due to the FP element handling below calling this routine recursively,
5475    // we can end up with a scalar-to-vector node here.
5476    if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5477      return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5478                         DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5479                                     DstEltVT, BV->getOperand(0)));
5480
5481    SmallVector<SDValue, 8> Ops;
5482    for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5483      SDValue Op = BV->getOperand(i);
5484      // If the vector element type is not legal, the BUILD_VECTOR operands
5485      // are promoted and implicitly truncated.  Make that explicit here.
5486      if (Op.getValueType() != SrcEltVT)
5487        Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5488      Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5489                                DstEltVT, Op));
5490      AddToWorkList(Ops.back().getNode());
5491    }
5492    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5493                       &Ops[0], Ops.size());
5494  }
5495
5496  // Otherwise, we're growing or shrinking the elements.  To avoid having to
5497  // handle annoying details of growing/shrinking FP values, we convert them to
5498  // int first.
5499  if (SrcEltVT.isFloatingPoint()) {
5500    // Convert the input float vector to a int vector where the elements are the
5501    // same sizes.
5502    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5503    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5504    BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5505    SrcEltVT = IntVT;
5506  }
5507
5508  // Now we know the input is an integer vector.  If the output is a FP type,
5509  // convert to integer first, then to FP of the right size.
5510  if (DstEltVT.isFloatingPoint()) {
5511    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5512    EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5513    SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5514
5515    // Next, convert to FP elements of the same size.
5516    return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5517  }
5518
5519  // Okay, we know the src/dst types are both integers of differing types.
5520  // Handling growing first.
5521  assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5522  if (SrcBitSize < DstBitSize) {
5523    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5524
5525    SmallVector<SDValue, 8> Ops;
5526    for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5527         i += NumInputsPerOutput) {
5528      bool isLE = TLI.isLittleEndian();
5529      APInt NewBits = APInt(DstBitSize, 0);
5530      bool EltIsUndef = true;
5531      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5532        // Shift the previously computed bits over.
5533        NewBits <<= SrcBitSize;
5534        SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5535        if (Op.getOpcode() == ISD::UNDEF) continue;
5536        EltIsUndef = false;
5537
5538        NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5539                   zextOrTrunc(SrcBitSize).zext(DstBitSize);
5540      }
5541
5542      if (EltIsUndef)
5543        Ops.push_back(DAG.getUNDEF(DstEltVT));
5544      else
5545        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5546    }
5547
5548    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5549    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5550                       &Ops[0], Ops.size());
5551  }
5552
5553  // Finally, this must be the case where we are shrinking elements: each input
5554  // turns into multiple outputs.
5555  bool isS2V = ISD::isScalarToVector(BV);
5556  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5557  EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5558                            NumOutputsPerInput*BV->getNumOperands());
5559  SmallVector<SDValue, 8> Ops;
5560
5561  for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5562    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5563      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5564        Ops.push_back(DAG.getUNDEF(DstEltVT));
5565      continue;
5566    }
5567
5568    APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5569                  getAPIntValue().zextOrTrunc(SrcBitSize);
5570
5571    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5572      APInt ThisVal = OpVal.trunc(DstBitSize);
5573      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5574      if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5575        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5576        return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5577                           Ops[0]);
5578      OpVal = OpVal.lshr(DstBitSize);
5579    }
5580
5581    // For big endian targets, swap the order of the pieces of each element.
5582    if (TLI.isBigEndian())
5583      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5584  }
5585
5586  return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5587                     &Ops[0], Ops.size());
5588}
5589
5590SDValue DAGCombiner::visitFADD(SDNode *N) {
5591  SDValue N0 = N->getOperand(0);
5592  SDValue N1 = N->getOperand(1);
5593  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5594  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5595  EVT VT = N->getValueType(0);
5596
5597  // fold vector ops
5598  if (VT.isVector()) {
5599    SDValue FoldedVOp = SimplifyVBinOp(N);
5600    if (FoldedVOp.getNode()) return FoldedVOp;
5601  }
5602
5603  // fold (fadd c1, c2) -> (fadd c1, c2)
5604  if (N0CFP && N1CFP && VT != MVT::ppcf128)
5605    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5606  // canonicalize constant to RHS
5607  if (N0CFP && !N1CFP)
5608    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5609  // fold (fadd A, 0) -> A
5610  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5611      N1CFP->getValueAPF().isZero())
5612    return N0;
5613  // fold (fadd A, (fneg B)) -> (fsub A, B)
5614  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5615      isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5616    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5617                       GetNegatedExpression(N1, DAG, LegalOperations));
5618  // fold (fadd (fneg A), B) -> (fsub B, A)
5619  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5620      isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5621    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5622                       GetNegatedExpression(N0, DAG, LegalOperations));
5623
5624  // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5625  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5626      N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5627      isa<ConstantFPSDNode>(N0.getOperand(1)))
5628    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5629                       DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5630                                   N0.getOperand(1), N1));
5631
5632  return SDValue();
5633}
5634
5635SDValue DAGCombiner::visitFSUB(SDNode *N) {
5636  SDValue N0 = N->getOperand(0);
5637  SDValue N1 = N->getOperand(1);
5638  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5639  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5640  EVT VT = N->getValueType(0);
5641
5642  // fold vector ops
5643  if (VT.isVector()) {
5644    SDValue FoldedVOp = SimplifyVBinOp(N);
5645    if (FoldedVOp.getNode()) return FoldedVOp;
5646  }
5647
5648  // fold (fsub c1, c2) -> c1-c2
5649  if (N0CFP && N1CFP && VT != MVT::ppcf128)
5650    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5651  // fold (fsub A, 0) -> A
5652  if (DAG.getTarget().Options.UnsafeFPMath &&
5653      N1CFP && N1CFP->getValueAPF().isZero())
5654    return N0;
5655  // fold (fsub 0, B) -> -B
5656  if (DAG.getTarget().Options.UnsafeFPMath &&
5657      N0CFP && N0CFP->getValueAPF().isZero()) {
5658    if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5659      return GetNegatedExpression(N1, DAG, LegalOperations);
5660    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5661      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
5662  }
5663  // fold (fsub A, (fneg B)) -> (fadd A, B)
5664  if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5665    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
5666                       GetNegatedExpression(N1, DAG, LegalOperations));
5667
5668  // If 'unsafe math' is enabled, fold
5669  //    (fsub x, (fadd x, y)) -> (fneg y) &
5670  //    (fsub x, (fadd y, x)) -> (fneg y)
5671  if (DAG.getTarget().Options.UnsafeFPMath) {
5672    if (N1.getOpcode() == ISD::FADD) {
5673      SDValue N10 = N1->getOperand(0);
5674      SDValue N11 = N1->getOperand(1);
5675
5676      if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5677                                          &DAG.getTarget().Options))
5678        return GetNegatedExpression(N11, DAG, LegalOperations);
5679      else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
5680                                               &DAG.getTarget().Options))
5681        return GetNegatedExpression(N10, DAG, LegalOperations);
5682    }
5683  }
5684
5685  return SDValue();
5686}
5687
5688SDValue DAGCombiner::visitFMUL(SDNode *N) {
5689  SDValue N0 = N->getOperand(0);
5690  SDValue N1 = N->getOperand(1);
5691  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5692  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5693  EVT VT = N->getValueType(0);
5694  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5695
5696  // fold vector ops
5697  if (VT.isVector()) {
5698    SDValue FoldedVOp = SimplifyVBinOp(N);
5699    if (FoldedVOp.getNode()) return FoldedVOp;
5700  }
5701
5702  // fold (fmul c1, c2) -> c1*c2
5703  if (N0CFP && N1CFP && VT != MVT::ppcf128)
5704    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5705  // canonicalize constant to RHS
5706  if (N0CFP && !N1CFP)
5707    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5708  // fold (fmul A, 0) -> 0
5709  if (DAG.getTarget().Options.UnsafeFPMath &&
5710      N1CFP && N1CFP->getValueAPF().isZero())
5711    return N1;
5712  // fold (fmul A, 0) -> 0, vector edition.
5713  if (DAG.getTarget().Options.UnsafeFPMath &&
5714      ISD::isBuildVectorAllZeros(N1.getNode()))
5715    return N1;
5716  // fold (fmul X, 2.0) -> (fadd X, X)
5717  if (N1CFP && N1CFP->isExactlyValue(+2.0))
5718    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5719  // fold (fmul X, -1.0) -> (fneg X)
5720  if (N1CFP && N1CFP->isExactlyValue(-1.0))
5721    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5722      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5723
5724  // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5725  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5726                                       &DAG.getTarget().Options)) {
5727    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5728                                         &DAG.getTarget().Options)) {
5729      // Both can be negated for free, check to see if at least one is cheaper
5730      // negated.
5731      if (LHSNeg == 2 || RHSNeg == 2)
5732        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5733                           GetNegatedExpression(N0, DAG, LegalOperations),
5734                           GetNegatedExpression(N1, DAG, LegalOperations));
5735    }
5736  }
5737
5738  // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5739  if (DAG.getTarget().Options.UnsafeFPMath &&
5740      N1CFP && N0.getOpcode() == ISD::FMUL &&
5741      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5742    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5743                       DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5744                                   N0.getOperand(1), N1));
5745
5746  return SDValue();
5747}
5748
5749SDValue DAGCombiner::visitFDIV(SDNode *N) {
5750  SDValue N0 = N->getOperand(0);
5751  SDValue N1 = N->getOperand(1);
5752  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5753  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5754  EVT VT = N->getValueType(0);
5755  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5756
5757  // fold vector ops
5758  if (VT.isVector()) {
5759    SDValue FoldedVOp = SimplifyVBinOp(N);
5760    if (FoldedVOp.getNode()) return FoldedVOp;
5761  }
5762
5763  // fold (fdiv c1, c2) -> c1/c2
5764  if (N0CFP && N1CFP && VT != MVT::ppcf128)
5765    return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5766
5767  // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
5768  if (N1CFP && VT != MVT::ppcf128 && DAG.getTarget().Options.UnsafeFPMath) {
5769    // Compute the reciprocal 1.0 / c2.
5770    APFloat N1APF = N1CFP->getValueAPF();
5771    APFloat Recip(N1APF.getSemantics(), 1); // 1.0
5772    APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
5773    // Only do the transform if the reciprocal is a legal fp immediate that
5774    // isn't too nasty (eg NaN, denormal, ...).
5775    if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
5776        (!LegalOperations ||
5777         // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
5778         // backend)... we should handle this gracefully after Legalize.
5779         // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
5780         TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
5781         TLI.isFPImmLegal(Recip, VT)))
5782      return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
5783                         DAG.getConstantFP(Recip, VT));
5784  }
5785
5786  // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5787  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
5788                                       &DAG.getTarget().Options)) {
5789    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
5790                                         &DAG.getTarget().Options)) {
5791      // Both can be negated for free, check to see if at least one is cheaper
5792      // negated.
5793      if (LHSNeg == 2 || RHSNeg == 2)
5794        return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5795                           GetNegatedExpression(N0, DAG, LegalOperations),
5796                           GetNegatedExpression(N1, DAG, LegalOperations));
5797    }
5798  }
5799
5800  return SDValue();
5801}
5802
5803SDValue DAGCombiner::visitFREM(SDNode *N) {
5804  SDValue N0 = N->getOperand(0);
5805  SDValue N1 = N->getOperand(1);
5806  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5807  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5808  EVT VT = N->getValueType(0);
5809
5810  // fold (frem c1, c2) -> fmod(c1,c2)
5811  if (N0CFP && N1CFP && VT != MVT::ppcf128)
5812    return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5813
5814  return SDValue();
5815}
5816
5817SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5818  SDValue N0 = N->getOperand(0);
5819  SDValue N1 = N->getOperand(1);
5820  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5821  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5822  EVT VT = N->getValueType(0);
5823
5824  if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
5825    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5826
5827  if (N1CFP) {
5828    const APFloat& V = N1CFP->getValueAPF();
5829    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
5830    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5831    if (!V.isNegative()) {
5832      if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5833        return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5834    } else {
5835      if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5836        return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5837                           DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5838    }
5839  }
5840
5841  // copysign(fabs(x), y) -> copysign(x, y)
5842  // copysign(fneg(x), y) -> copysign(x, y)
5843  // copysign(copysign(x,z), y) -> copysign(x, y)
5844  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5845      N0.getOpcode() == ISD::FCOPYSIGN)
5846    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5847                       N0.getOperand(0), N1);
5848
5849  // copysign(x, abs(y)) -> abs(x)
5850  if (N1.getOpcode() == ISD::FABS)
5851    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5852
5853  // copysign(x, copysign(y,z)) -> copysign(x, z)
5854  if (N1.getOpcode() == ISD::FCOPYSIGN)
5855    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5856                       N0, N1.getOperand(1));
5857
5858  // copysign(x, fp_extend(y)) -> copysign(x, y)
5859  // copysign(x, fp_round(y)) -> copysign(x, y)
5860  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5861    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5862                       N0, N1.getOperand(0));
5863
5864  return SDValue();
5865}
5866
5867SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5868  SDValue N0 = N->getOperand(0);
5869  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5870  EVT VT = N->getValueType(0);
5871  EVT OpVT = N0.getValueType();
5872
5873  // fold (sint_to_fp c1) -> c1fp
5874  if (N0C && OpVT != MVT::ppcf128 &&
5875      // ...but only if the target supports immediate floating-point values
5876      (!LegalOperations ||
5877       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5878    return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5879
5880  // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5881  // but UINT_TO_FP is legal on this target, try to convert.
5882  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5883      TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5884    // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5885    if (DAG.SignBitIsZero(N0))
5886      return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5887  }
5888
5889  return SDValue();
5890}
5891
5892SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5893  SDValue N0 = N->getOperand(0);
5894  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5895  EVT VT = N->getValueType(0);
5896  EVT OpVT = N0.getValueType();
5897
5898  // fold (uint_to_fp c1) -> c1fp
5899  if (N0C && OpVT != MVT::ppcf128 &&
5900      // ...but only if the target supports immediate floating-point values
5901      (!LegalOperations ||
5902       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5903    return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5904
5905  // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5906  // but SINT_TO_FP is legal on this target, try to convert.
5907  if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5908      TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5909    // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5910    if (DAG.SignBitIsZero(N0))
5911      return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5912  }
5913
5914  return SDValue();
5915}
5916
5917SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5918  SDValue N0 = N->getOperand(0);
5919  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5920  EVT VT = N->getValueType(0);
5921
5922  // fold (fp_to_sint c1fp) -> c1
5923  if (N0CFP)
5924    return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5925
5926  return SDValue();
5927}
5928
5929SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5930  SDValue N0 = N->getOperand(0);
5931  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5932  EVT VT = N->getValueType(0);
5933
5934  // fold (fp_to_uint c1fp) -> c1
5935  if (N0CFP && VT != MVT::ppcf128)
5936    return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5937
5938  return SDValue();
5939}
5940
5941SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5942  SDValue N0 = N->getOperand(0);
5943  SDValue N1 = N->getOperand(1);
5944  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5945  EVT VT = N->getValueType(0);
5946
5947  // fold (fp_round c1fp) -> c1fp
5948  if (N0CFP && N0.getValueType() != MVT::ppcf128)
5949    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5950
5951  // fold (fp_round (fp_extend x)) -> x
5952  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5953    return N0.getOperand(0);
5954
5955  // fold (fp_round (fp_round x)) -> (fp_round x)
5956  if (N0.getOpcode() == ISD::FP_ROUND) {
5957    // This is a value preserving truncation if both round's are.
5958    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5959                   N0.getNode()->getConstantOperandVal(1) == 1;
5960    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5961                       DAG.getIntPtrConstant(IsTrunc));
5962  }
5963
5964  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5965  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5966    SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5967                              N0.getOperand(0), N1);
5968    AddToWorkList(Tmp.getNode());
5969    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5970                       Tmp, N0.getOperand(1));
5971  }
5972
5973  return SDValue();
5974}
5975
5976SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5977  SDValue N0 = N->getOperand(0);
5978  EVT VT = N->getValueType(0);
5979  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5980  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5981
5982  // fold (fp_round_inreg c1fp) -> c1fp
5983  if (N0CFP && isTypeLegal(EVT)) {
5984    SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5985    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5986  }
5987
5988  return SDValue();
5989}
5990
5991SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5992  SDValue N0 = N->getOperand(0);
5993  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5994  EVT VT = N->getValueType(0);
5995
5996  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5997  if (N->hasOneUse() &&
5998      N->use_begin()->getOpcode() == ISD::FP_ROUND)
5999    return SDValue();
6000
6001  // fold (fp_extend c1fp) -> c1fp
6002  if (N0CFP && VT != MVT::ppcf128)
6003    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6004
6005  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6006  // value of X.
6007  if (N0.getOpcode() == ISD::FP_ROUND
6008      && N0.getNode()->getConstantOperandVal(1) == 1) {
6009    SDValue In = N0.getOperand(0);
6010    if (In.getValueType() == VT) return In;
6011    if (VT.bitsLT(In.getValueType()))
6012      return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6013                         In, N0.getOperand(1));
6014    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6015  }
6016
6017  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6018  if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6019      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6020       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6021    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6022    SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6023                                     LN0->getChain(),
6024                                     LN0->getBasePtr(), LN0->getPointerInfo(),
6025                                     N0.getValueType(),
6026                                     LN0->isVolatile(), LN0->isNonTemporal(),
6027                                     LN0->getAlignment());
6028    CombineTo(N, ExtLoad);
6029    CombineTo(N0.getNode(),
6030              DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6031                          N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6032              ExtLoad.getValue(1));
6033    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6034  }
6035
6036  return SDValue();
6037}
6038
6039SDValue DAGCombiner::visitFNEG(SDNode *N) {
6040  SDValue N0 = N->getOperand(0);
6041  EVT VT = N->getValueType(0);
6042
6043  if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6044                         &DAG.getTarget().Options))
6045    return GetNegatedExpression(N0, DAG, LegalOperations);
6046
6047  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6048  // constant pool values.
6049  if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6050      !VT.isVector() &&
6051      N0.getNode()->hasOneUse() &&
6052      N0.getOperand(0).getValueType().isInteger()) {
6053    SDValue Int = N0.getOperand(0);
6054    EVT IntVT = Int.getValueType();
6055    if (IntVT.isInteger() && !IntVT.isVector()) {
6056      Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6057              DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6058      AddToWorkList(Int.getNode());
6059      return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6060                         VT, Int);
6061    }
6062  }
6063
6064  return SDValue();
6065}
6066
6067SDValue DAGCombiner::visitFABS(SDNode *N) {
6068  SDValue N0 = N->getOperand(0);
6069  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6070  EVT VT = N->getValueType(0);
6071
6072  // fold (fabs c1) -> fabs(c1)
6073  if (N0CFP && VT != MVT::ppcf128)
6074    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6075  // fold (fabs (fabs x)) -> (fabs x)
6076  if (N0.getOpcode() == ISD::FABS)
6077    return N->getOperand(0);
6078  // fold (fabs (fneg x)) -> (fabs x)
6079  // fold (fabs (fcopysign x, y)) -> (fabs x)
6080  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6081    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6082
6083  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6084  // constant pool values.
6085  if (!TLI.isFAbsFree(VT) &&
6086      N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6087      N0.getOperand(0).getValueType().isInteger() &&
6088      !N0.getOperand(0).getValueType().isVector()) {
6089    SDValue Int = N0.getOperand(0);
6090    EVT IntVT = Int.getValueType();
6091    if (IntVT.isInteger() && !IntVT.isVector()) {
6092      Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6093             DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6094      AddToWorkList(Int.getNode());
6095      return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6096                         N->getValueType(0), Int);
6097    }
6098  }
6099
6100  return SDValue();
6101}
6102
6103SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6104  SDValue Chain = N->getOperand(0);
6105  SDValue N1 = N->getOperand(1);
6106  SDValue N2 = N->getOperand(2);
6107
6108  // If N is a constant we could fold this into a fallthrough or unconditional
6109  // branch. However that doesn't happen very often in normal code, because
6110  // Instcombine/SimplifyCFG should have handled the available opportunities.
6111  // If we did this folding here, it would be necessary to update the
6112  // MachineBasicBlock CFG, which is awkward.
6113
6114  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6115  // on the target.
6116  if (N1.getOpcode() == ISD::SETCC &&
6117      TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6118    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6119                       Chain, N1.getOperand(2),
6120                       N1.getOperand(0), N1.getOperand(1), N2);
6121  }
6122
6123  if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6124      ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6125       (N1.getOperand(0).hasOneUse() &&
6126        N1.getOperand(0).getOpcode() == ISD::SRL))) {
6127    SDNode *Trunc = 0;
6128    if (N1.getOpcode() == ISD::TRUNCATE) {
6129      // Look pass the truncate.
6130      Trunc = N1.getNode();
6131      N1 = N1.getOperand(0);
6132    }
6133
6134    // Match this pattern so that we can generate simpler code:
6135    //
6136    //   %a = ...
6137    //   %b = and i32 %a, 2
6138    //   %c = srl i32 %b, 1
6139    //   brcond i32 %c ...
6140    //
6141    // into
6142    //
6143    //   %a = ...
6144    //   %b = and i32 %a, 2
6145    //   %c = setcc eq %b, 0
6146    //   brcond %c ...
6147    //
6148    // This applies only when the AND constant value has one bit set and the
6149    // SRL constant is equal to the log2 of the AND constant. The back-end is
6150    // smart enough to convert the result into a TEST/JMP sequence.
6151    SDValue Op0 = N1.getOperand(0);
6152    SDValue Op1 = N1.getOperand(1);
6153
6154    if (Op0.getOpcode() == ISD::AND &&
6155        Op1.getOpcode() == ISD::Constant) {
6156      SDValue AndOp1 = Op0.getOperand(1);
6157
6158      if (AndOp1.getOpcode() == ISD::Constant) {
6159        const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6160
6161        if (AndConst.isPowerOf2() &&
6162            cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6163          SDValue SetCC =
6164            DAG.getSetCC(N->getDebugLoc(),
6165                         TLI.getSetCCResultType(Op0.getValueType()),
6166                         Op0, DAG.getConstant(0, Op0.getValueType()),
6167                         ISD::SETNE);
6168
6169          SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6170                                          MVT::Other, Chain, SetCC, N2);
6171          // Don't add the new BRCond into the worklist or else SimplifySelectCC
6172          // will convert it back to (X & C1) >> C2.
6173          CombineTo(N, NewBRCond, false);
6174          // Truncate is dead.
6175          if (Trunc) {
6176            removeFromWorkList(Trunc);
6177            DAG.DeleteNode(Trunc);
6178          }
6179          // Replace the uses of SRL with SETCC
6180          WorkListRemover DeadNodes(*this);
6181          DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6182          removeFromWorkList(N1.getNode());
6183          DAG.DeleteNode(N1.getNode());
6184          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6185        }
6186      }
6187    }
6188
6189    if (Trunc)
6190      // Restore N1 if the above transformation doesn't match.
6191      N1 = N->getOperand(1);
6192  }
6193
6194  // Transform br(xor(x, y)) -> br(x != y)
6195  // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6196  if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6197    SDNode *TheXor = N1.getNode();
6198    SDValue Op0 = TheXor->getOperand(0);
6199    SDValue Op1 = TheXor->getOperand(1);
6200    if (Op0.getOpcode() == Op1.getOpcode()) {
6201      // Avoid missing important xor optimizations.
6202      SDValue Tmp = visitXOR(TheXor);
6203      if (Tmp.getNode() && Tmp.getNode() != TheXor) {
6204        DEBUG(dbgs() << "\nReplacing.8 ";
6205              TheXor->dump(&DAG);
6206              dbgs() << "\nWith: ";
6207              Tmp.getNode()->dump(&DAG);
6208              dbgs() << '\n');
6209        WorkListRemover DeadNodes(*this);
6210        DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6211        removeFromWorkList(TheXor);
6212        DAG.DeleteNode(TheXor);
6213        return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6214                           MVT::Other, Chain, Tmp, N2);
6215      }
6216    }
6217
6218    if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6219      bool Equal = false;
6220      if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6221        if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6222            Op0.getOpcode() == ISD::XOR) {
6223          TheXor = Op0.getNode();
6224          Equal = true;
6225        }
6226
6227      EVT SetCCVT = N1.getValueType();
6228      if (LegalTypes)
6229        SetCCVT = TLI.getSetCCResultType(SetCCVT);
6230      SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6231                                   SetCCVT,
6232                                   Op0, Op1,
6233                                   Equal ? ISD::SETEQ : ISD::SETNE);
6234      // Replace the uses of XOR with SETCC
6235      WorkListRemover DeadNodes(*this);
6236      DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6237      removeFromWorkList(N1.getNode());
6238      DAG.DeleteNode(N1.getNode());
6239      return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6240                         MVT::Other, Chain, SetCC, N2);
6241    }
6242  }
6243
6244  return SDValue();
6245}
6246
6247// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6248//
6249SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6250  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6251  SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6252
6253  // If N is a constant we could fold this into a fallthrough or unconditional
6254  // branch. However that doesn't happen very often in normal code, because
6255  // Instcombine/SimplifyCFG should have handled the available opportunities.
6256  // If we did this folding here, it would be necessary to update the
6257  // MachineBasicBlock CFG, which is awkward.
6258
6259  // Use SimplifySetCC to simplify SETCC's.
6260  SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6261                               CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6262                               false);
6263  if (Simp.getNode()) AddToWorkList(Simp.getNode());
6264
6265  // fold to a simpler setcc
6266  if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6267    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6268                       N->getOperand(0), Simp.getOperand(2),
6269                       Simp.getOperand(0), Simp.getOperand(1),
6270                       N->getOperand(4));
6271
6272  return SDValue();
6273}
6274
6275/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6276/// uses N as its base pointer and that N may be folded in the load / store
6277/// addressing mode.
6278static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6279                                    SelectionDAG &DAG,
6280                                    const TargetLowering &TLI) {
6281  EVT VT;
6282  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6283    if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6284      return false;
6285    VT = Use->getValueType(0);
6286  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6287    if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6288      return false;
6289    VT = ST->getValue().getValueType();
6290  } else
6291    return false;
6292
6293  TargetLowering::AddrMode AM;
6294  if (N->getOpcode() == ISD::ADD) {
6295    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6296    if (Offset)
6297      // [reg +/- imm]
6298      AM.BaseOffs = Offset->getSExtValue();
6299    else
6300      // [reg +/- reg]
6301      AM.Scale = 1;
6302  } else if (N->getOpcode() == ISD::SUB) {
6303    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6304    if (Offset)
6305      // [reg +/- imm]
6306      AM.BaseOffs = -Offset->getSExtValue();
6307    else
6308      // [reg +/- reg]
6309      AM.Scale = 1;
6310  } else
6311    return false;
6312
6313  return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6314}
6315
6316/// CombineToPreIndexedLoadStore - Try turning a load / store into a
6317/// pre-indexed load / store when the base pointer is an add or subtract
6318/// and it has other uses besides the load / store. After the
6319/// transformation, the new indexed load / store has effectively folded
6320/// the add / subtract in and all of its other uses are redirected to the
6321/// new load / store.
6322bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6323  if (Level < AfterLegalizeDAG)
6324    return false;
6325
6326  bool isLoad = true;
6327  SDValue Ptr;
6328  EVT VT;
6329  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6330    if (LD->isIndexed())
6331      return false;
6332    VT = LD->getMemoryVT();
6333    if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6334        !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6335      return false;
6336    Ptr = LD->getBasePtr();
6337  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6338    if (ST->isIndexed())
6339      return false;
6340    VT = ST->getMemoryVT();
6341    if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6342        !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6343      return false;
6344    Ptr = ST->getBasePtr();
6345    isLoad = false;
6346  } else {
6347    return false;
6348  }
6349
6350  // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6351  // out.  There is no reason to make this a preinc/predec.
6352  if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6353      Ptr.getNode()->hasOneUse())
6354    return false;
6355
6356  // Ask the target to do addressing mode selection.
6357  SDValue BasePtr;
6358  SDValue Offset;
6359  ISD::MemIndexedMode AM = ISD::UNINDEXED;
6360  if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6361    return false;
6362  // Don't create a indexed load / store with zero offset.
6363  if (isa<ConstantSDNode>(Offset) &&
6364      cast<ConstantSDNode>(Offset)->isNullValue())
6365    return false;
6366
6367  // Try turning it into a pre-indexed load / store except when:
6368  // 1) The new base ptr is a frame index.
6369  // 2) If N is a store and the new base ptr is either the same as or is a
6370  //    predecessor of the value being stored.
6371  // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6372  //    that would create a cycle.
6373  // 4) All uses are load / store ops that use it as old base ptr.
6374
6375  // Check #1.  Preinc'ing a frame index would require copying the stack pointer
6376  // (plus the implicit offset) to a register to preinc anyway.
6377  if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6378    return false;
6379
6380  // Check #2.
6381  if (!isLoad) {
6382    SDValue Val = cast<StoreSDNode>(N)->getValue();
6383    if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6384      return false;
6385  }
6386
6387  // Now check for #3 and #4.
6388  bool RealUse = false;
6389
6390  // Caches for hasPredecessorHelper
6391  SmallPtrSet<const SDNode *, 32> Visited;
6392  SmallVector<const SDNode *, 16> Worklist;
6393
6394  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6395         E = Ptr.getNode()->use_end(); I != E; ++I) {
6396    SDNode *Use = *I;
6397    if (Use == N)
6398      continue;
6399    if (N->hasPredecessorHelper(Use, Visited, Worklist))
6400      return false;
6401
6402    // If Ptr may be folded in addressing mode of other use, then it's
6403    // not profitable to do this transformation.
6404    if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6405      RealUse = true;
6406  }
6407
6408  if (!RealUse)
6409    return false;
6410
6411  SDValue Result;
6412  if (isLoad)
6413    Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6414                                BasePtr, Offset, AM);
6415  else
6416    Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6417                                 BasePtr, Offset, AM);
6418  ++PreIndexedNodes;
6419  ++NodesCombined;
6420  DEBUG(dbgs() << "\nReplacing.4 ";
6421        N->dump(&DAG);
6422        dbgs() << "\nWith: ";
6423        Result.getNode()->dump(&DAG);
6424        dbgs() << '\n');
6425  WorkListRemover DeadNodes(*this);
6426  if (isLoad) {
6427    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6428    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6429  } else {
6430    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6431  }
6432
6433  // Finally, since the node is now dead, remove it from the graph.
6434  DAG.DeleteNode(N);
6435
6436  // Replace the uses of Ptr with uses of the updated base value.
6437  DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6438  removeFromWorkList(Ptr.getNode());
6439  DAG.DeleteNode(Ptr.getNode());
6440
6441  return true;
6442}
6443
6444/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6445/// add / sub of the base pointer node into a post-indexed load / store.
6446/// The transformation folded the add / subtract into the new indexed
6447/// load / store effectively and all of its uses are redirected to the
6448/// new load / store.
6449bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
6450  if (Level < AfterLegalizeDAG)
6451    return false;
6452
6453  bool isLoad = true;
6454  SDValue Ptr;
6455  EVT VT;
6456  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6457    if (LD->isIndexed())
6458      return false;
6459    VT = LD->getMemoryVT();
6460    if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
6461        !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
6462      return false;
6463    Ptr = LD->getBasePtr();
6464  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6465    if (ST->isIndexed())
6466      return false;
6467    VT = ST->getMemoryVT();
6468    if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
6469        !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
6470      return false;
6471    Ptr = ST->getBasePtr();
6472    isLoad = false;
6473  } else {
6474    return false;
6475  }
6476
6477  if (Ptr.getNode()->hasOneUse())
6478    return false;
6479
6480  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6481         E = Ptr.getNode()->use_end(); I != E; ++I) {
6482    SDNode *Op = *I;
6483    if (Op == N ||
6484        (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
6485      continue;
6486
6487    SDValue BasePtr;
6488    SDValue Offset;
6489    ISD::MemIndexedMode AM = ISD::UNINDEXED;
6490    if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
6491      // Don't create a indexed load / store with zero offset.
6492      if (isa<ConstantSDNode>(Offset) &&
6493          cast<ConstantSDNode>(Offset)->isNullValue())
6494        continue;
6495
6496      // Try turning it into a post-indexed load / store except when
6497      // 1) All uses are load / store ops that use it as base ptr (and
6498      //    it may be folded as addressing mmode).
6499      // 2) Op must be independent of N, i.e. Op is neither a predecessor
6500      //    nor a successor of N. Otherwise, if Op is folded that would
6501      //    create a cycle.
6502
6503      if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6504        continue;
6505
6506      // Check for #1.
6507      bool TryNext = false;
6508      for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
6509             EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
6510        SDNode *Use = *II;
6511        if (Use == Ptr.getNode())
6512          continue;
6513
6514        // If all the uses are load / store addresses, then don't do the
6515        // transformation.
6516        if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
6517          bool RealUse = false;
6518          for (SDNode::use_iterator III = Use->use_begin(),
6519                 EEE = Use->use_end(); III != EEE; ++III) {
6520            SDNode *UseUse = *III;
6521            if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
6522              RealUse = true;
6523          }
6524
6525          if (!RealUse) {
6526            TryNext = true;
6527            break;
6528          }
6529        }
6530      }
6531
6532      if (TryNext)
6533        continue;
6534
6535      // Check for #2
6536      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
6537        SDValue Result = isLoad
6538          ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6539                               BasePtr, Offset, AM)
6540          : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6541                                BasePtr, Offset, AM);
6542        ++PostIndexedNodes;
6543        ++NodesCombined;
6544        DEBUG(dbgs() << "\nReplacing.5 ";
6545              N->dump(&DAG);
6546              dbgs() << "\nWith: ";
6547              Result.getNode()->dump(&DAG);
6548              dbgs() << '\n');
6549        WorkListRemover DeadNodes(*this);
6550        if (isLoad) {
6551          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6552          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6553        } else {
6554          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6555        }
6556
6557        // Finally, since the node is now dead, remove it from the graph.
6558        DAG.DeleteNode(N);
6559
6560        // Replace the uses of Use with uses of the updated base value.
6561        DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
6562                                      Result.getValue(isLoad ? 1 : 0));
6563        removeFromWorkList(Op);
6564        DAG.DeleteNode(Op);
6565        return true;
6566      }
6567    }
6568  }
6569
6570  return false;
6571}
6572
6573SDValue DAGCombiner::visitLOAD(SDNode *N) {
6574  LoadSDNode *LD  = cast<LoadSDNode>(N);
6575  SDValue Chain = LD->getChain();
6576  SDValue Ptr   = LD->getBasePtr();
6577
6578  // If load is not volatile and there are no uses of the loaded value (and
6579  // the updated indexed value in case of indexed loads), change uses of the
6580  // chain value into uses of the chain input (i.e. delete the dead load).
6581  if (!LD->isVolatile()) {
6582    if (N->getValueType(1) == MVT::Other) {
6583      // Unindexed loads.
6584      if (!N->hasAnyUseOfValue(0)) {
6585        // It's not safe to use the two value CombineTo variant here. e.g.
6586        // v1, chain2 = load chain1, loc
6587        // v2, chain3 = load chain2, loc
6588        // v3         = add v2, c
6589        // Now we replace use of chain2 with chain1.  This makes the second load
6590        // isomorphic to the one we are deleting, and thus makes this load live.
6591        DEBUG(dbgs() << "\nReplacing.6 ";
6592              N->dump(&DAG);
6593              dbgs() << "\nWith chain: ";
6594              Chain.getNode()->dump(&DAG);
6595              dbgs() << "\n");
6596        WorkListRemover DeadNodes(*this);
6597        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
6598
6599        if (N->use_empty()) {
6600          removeFromWorkList(N);
6601          DAG.DeleteNode(N);
6602        }
6603
6604        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6605      }
6606    } else {
6607      // Indexed loads.
6608      assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
6609      if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
6610        SDValue Undef = DAG.getUNDEF(N->getValueType(0));
6611        DEBUG(dbgs() << "\nReplacing.7 ";
6612              N->dump(&DAG);
6613              dbgs() << "\nWith: ";
6614              Undef.getNode()->dump(&DAG);
6615              dbgs() << " and 2 other values\n");
6616        WorkListRemover DeadNodes(*this);
6617        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
6618        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
6619                                      DAG.getUNDEF(N->getValueType(1)));
6620        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
6621        removeFromWorkList(N);
6622        DAG.DeleteNode(N);
6623        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6624      }
6625    }
6626  }
6627
6628  // If this load is directly stored, replace the load value with the stored
6629  // value.
6630  // TODO: Handle store large -> read small portion.
6631  // TODO: Handle TRUNCSTORE/LOADEXT
6632  if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
6633    if (ISD::isNON_TRUNCStore(Chain.getNode())) {
6634      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
6635      if (PrevST->getBasePtr() == Ptr &&
6636          PrevST->getValue().getValueType() == N->getValueType(0))
6637      return CombineTo(N, Chain.getOperand(1), Chain);
6638    }
6639  }
6640
6641  // Try to infer better alignment information than the load already has.
6642  if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
6643    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6644      if (Align > LD->getAlignment())
6645        return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
6646                              LD->getValueType(0),
6647                              Chain, Ptr, LD->getPointerInfo(),
6648                              LD->getMemoryVT(),
6649                              LD->isVolatile(), LD->isNonTemporal(), Align);
6650    }
6651  }
6652
6653  if (CombinerAA) {
6654    // Walk up chain skipping non-aliasing memory nodes.
6655    SDValue BetterChain = FindBetterChain(N, Chain);
6656
6657    // If there is a better chain.
6658    if (Chain != BetterChain) {
6659      SDValue ReplLoad;
6660
6661      // Replace the chain to void dependency.
6662      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
6663        ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
6664                               BetterChain, Ptr, LD->getPointerInfo(),
6665                               LD->isVolatile(), LD->isNonTemporal(),
6666                               LD->isInvariant(), LD->getAlignment());
6667      } else {
6668        ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
6669                                  LD->getValueType(0),
6670                                  BetterChain, Ptr, LD->getPointerInfo(),
6671                                  LD->getMemoryVT(),
6672                                  LD->isVolatile(),
6673                                  LD->isNonTemporal(),
6674                                  LD->getAlignment());
6675      }
6676
6677      // Create token factor to keep old chain connected.
6678      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6679                                  MVT::Other, Chain, ReplLoad.getValue(1));
6680
6681      // Make sure the new and old chains are cleaned up.
6682      AddToWorkList(Token.getNode());
6683
6684      // Replace uses with load result and token factor. Don't add users
6685      // to work list.
6686      return CombineTo(N, ReplLoad.getValue(0), Token, false);
6687    }
6688  }
6689
6690  // Try transforming N to an indexed load.
6691  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6692    return SDValue(N, 0);
6693
6694  return SDValue();
6695}
6696
6697/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
6698/// load is having specific bytes cleared out.  If so, return the byte size
6699/// being masked out and the shift amount.
6700static std::pair<unsigned, unsigned>
6701CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
6702  std::pair<unsigned, unsigned> Result(0, 0);
6703
6704  // Check for the structure we're looking for.
6705  if (V->getOpcode() != ISD::AND ||
6706      !isa<ConstantSDNode>(V->getOperand(1)) ||
6707      !ISD::isNormalLoad(V->getOperand(0).getNode()))
6708    return Result;
6709
6710  // Check the chain and pointer.
6711  LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
6712  if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
6713
6714  // The store should be chained directly to the load or be an operand of a
6715  // tokenfactor.
6716  if (LD == Chain.getNode())
6717    ; // ok.
6718  else if (Chain->getOpcode() != ISD::TokenFactor)
6719    return Result; // Fail.
6720  else {
6721    bool isOk = false;
6722    for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
6723      if (Chain->getOperand(i).getNode() == LD) {
6724        isOk = true;
6725        break;
6726      }
6727    if (!isOk) return Result;
6728  }
6729
6730  // This only handles simple types.
6731  if (V.getValueType() != MVT::i16 &&
6732      V.getValueType() != MVT::i32 &&
6733      V.getValueType() != MVT::i64)
6734    return Result;
6735
6736  // Check the constant mask.  Invert it so that the bits being masked out are
6737  // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
6738  // follow the sign bit for uniformity.
6739  uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
6740  unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
6741  if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
6742  unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
6743  if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
6744  if (NotMaskLZ == 64) return Result;  // All zero mask.
6745
6746  // See if we have a continuous run of bits.  If so, we have 0*1+0*
6747  if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
6748    return Result;
6749
6750  // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
6751  if (V.getValueType() != MVT::i64 && NotMaskLZ)
6752    NotMaskLZ -= 64-V.getValueSizeInBits();
6753
6754  unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
6755  switch (MaskedBytes) {
6756  case 1:
6757  case 2:
6758  case 4: break;
6759  default: return Result; // All one mask, or 5-byte mask.
6760  }
6761
6762  // Verify that the first bit starts at a multiple of mask so that the access
6763  // is aligned the same as the access width.
6764  if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
6765
6766  Result.first = MaskedBytes;
6767  Result.second = NotMaskTZ/8;
6768  return Result;
6769}
6770
6771
6772/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6773/// provides a value as specified by MaskInfo.  If so, replace the specified
6774/// store with a narrower store of truncated IVal.
6775static SDNode *
6776ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6777                                SDValue IVal, StoreSDNode *St,
6778                                DAGCombiner *DC) {
6779  unsigned NumBytes = MaskInfo.first;
6780  unsigned ByteShift = MaskInfo.second;
6781  SelectionDAG &DAG = DC->getDAG();
6782
6783  // Check to see if IVal is all zeros in the part being masked in by the 'or'
6784  // that uses this.  If not, this is not a replacement.
6785  APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6786                                  ByteShift*8, (ByteShift+NumBytes)*8);
6787  if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6788
6789  // Check that it is legal on the target to do this.  It is legal if the new
6790  // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6791  // legalization.
6792  MVT VT = MVT::getIntegerVT(NumBytes*8);
6793  if (!DC->isTypeLegal(VT))
6794    return 0;
6795
6796  // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
6797  // shifted by ByteShift and truncated down to NumBytes.
6798  if (ByteShift)
6799    IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6800                       DAG.getConstant(ByteShift*8,
6801                                    DC->getShiftAmountTy(IVal.getValueType())));
6802
6803  // Figure out the offset for the store and the alignment of the access.
6804  unsigned StOffset;
6805  unsigned NewAlign = St->getAlignment();
6806
6807  if (DAG.getTargetLoweringInfo().isLittleEndian())
6808    StOffset = ByteShift;
6809  else
6810    StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6811
6812  SDValue Ptr = St->getBasePtr();
6813  if (StOffset) {
6814    Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6815                      Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6816    NewAlign = MinAlign(NewAlign, StOffset);
6817  }
6818
6819  // Truncate down to the new size.
6820  IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
6821
6822  ++OpsNarrowed;
6823  return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
6824                      St->getPointerInfo().getWithOffset(StOffset),
6825                      false, false, NewAlign).getNode();
6826}
6827
6828
6829/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
6830/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
6831/// of the loaded bits, try narrowing the load and store if it would end up
6832/// being a win for performance or code size.
6833SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
6834  StoreSDNode *ST  = cast<StoreSDNode>(N);
6835  if (ST->isVolatile())
6836    return SDValue();
6837
6838  SDValue Chain = ST->getChain();
6839  SDValue Value = ST->getValue();
6840  SDValue Ptr   = ST->getBasePtr();
6841  EVT VT = Value.getValueType();
6842
6843  if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6844    return SDValue();
6845
6846  unsigned Opc = Value.getOpcode();
6847
6848  // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6849  // is a byte mask indicating a consecutive number of bytes, check to see if
6850  // Y is known to provide just those bytes.  If so, we try to replace the
6851  // load + replace + store sequence with a single (narrower) store, which makes
6852  // the load dead.
6853  if (Opc == ISD::OR) {
6854    std::pair<unsigned, unsigned> MaskedLoad;
6855    MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6856    if (MaskedLoad.first)
6857      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6858                                                  Value.getOperand(1), ST,this))
6859        return SDValue(NewST, 0);
6860
6861    // Or is commutative, so try swapping X and Y.
6862    MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6863    if (MaskedLoad.first)
6864      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6865                                                  Value.getOperand(0), ST,this))
6866        return SDValue(NewST, 0);
6867  }
6868
6869  if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6870      Value.getOperand(1).getOpcode() != ISD::Constant)
6871    return SDValue();
6872
6873  SDValue N0 = Value.getOperand(0);
6874  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6875      Chain == SDValue(N0.getNode(), 1)) {
6876    LoadSDNode *LD = cast<LoadSDNode>(N0);
6877    if (LD->getBasePtr() != Ptr ||
6878        LD->getPointerInfo().getAddrSpace() !=
6879        ST->getPointerInfo().getAddrSpace())
6880      return SDValue();
6881
6882    // Find the type to narrow it the load / op / store to.
6883    SDValue N1 = Value.getOperand(1);
6884    unsigned BitWidth = N1.getValueSizeInBits();
6885    APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6886    if (Opc == ISD::AND)
6887      Imm ^= APInt::getAllOnesValue(BitWidth);
6888    if (Imm == 0 || Imm.isAllOnesValue())
6889      return SDValue();
6890    unsigned ShAmt = Imm.countTrailingZeros();
6891    unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6892    unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6893    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6894    while (NewBW < BitWidth &&
6895           !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6896             TLI.isNarrowingProfitable(VT, NewVT))) {
6897      NewBW = NextPowerOf2(NewBW);
6898      NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6899    }
6900    if (NewBW >= BitWidth)
6901      return SDValue();
6902
6903    // If the lsb changed does not start at the type bitwidth boundary,
6904    // start at the previous one.
6905    if (ShAmt % NewBW)
6906      ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6907    APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6908    if ((Imm & Mask) == Imm) {
6909      APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6910      if (Opc == ISD::AND)
6911        NewImm ^= APInt::getAllOnesValue(NewBW);
6912      uint64_t PtrOff = ShAmt / 8;
6913      // For big endian targets, we need to adjust the offset to the pointer to
6914      // load the correct bytes.
6915      if (TLI.isBigEndian())
6916        PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6917
6918      unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6919      Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6920      if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6921        return SDValue();
6922
6923      SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6924                                   Ptr.getValueType(), Ptr,
6925                                   DAG.getConstant(PtrOff, Ptr.getValueType()));
6926      SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6927                                  LD->getChain(), NewPtr,
6928                                  LD->getPointerInfo().getWithOffset(PtrOff),
6929                                  LD->isVolatile(), LD->isNonTemporal(),
6930                                  LD->isInvariant(), NewAlign);
6931      SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6932                                   DAG.getConstant(NewImm, NewVT));
6933      SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6934                                   NewVal, NewPtr,
6935                                   ST->getPointerInfo().getWithOffset(PtrOff),
6936                                   false, false, NewAlign);
6937
6938      AddToWorkList(NewPtr.getNode());
6939      AddToWorkList(NewLD.getNode());
6940      AddToWorkList(NewVal.getNode());
6941      WorkListRemover DeadNodes(*this);
6942      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
6943      ++OpsNarrowed;
6944      return NewST;
6945    }
6946  }
6947
6948  return SDValue();
6949}
6950
6951/// TransformFPLoadStorePair - For a given floating point load / store pair,
6952/// if the load value isn't used by any other operations, then consider
6953/// transforming the pair to integer load / store operations if the target
6954/// deems the transformation profitable.
6955SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
6956  StoreSDNode *ST  = cast<StoreSDNode>(N);
6957  SDValue Chain = ST->getChain();
6958  SDValue Value = ST->getValue();
6959  if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
6960      Value.hasOneUse() &&
6961      Chain == SDValue(Value.getNode(), 1)) {
6962    LoadSDNode *LD = cast<LoadSDNode>(Value);
6963    EVT VT = LD->getMemoryVT();
6964    if (!VT.isFloatingPoint() ||
6965        VT != ST->getMemoryVT() ||
6966        LD->isNonTemporal() ||
6967        ST->isNonTemporal() ||
6968        LD->getPointerInfo().getAddrSpace() != 0 ||
6969        ST->getPointerInfo().getAddrSpace() != 0)
6970      return SDValue();
6971
6972    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6973    if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
6974        !TLI.isOperationLegal(ISD::STORE, IntVT) ||
6975        !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
6976        !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
6977      return SDValue();
6978
6979    unsigned LDAlign = LD->getAlignment();
6980    unsigned STAlign = ST->getAlignment();
6981    Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
6982    unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
6983    if (LDAlign < ABIAlign || STAlign < ABIAlign)
6984      return SDValue();
6985
6986    SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
6987                                LD->getChain(), LD->getBasePtr(),
6988                                LD->getPointerInfo(),
6989                                false, false, false, LDAlign);
6990
6991    SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
6992                                 NewLD, ST->getBasePtr(),
6993                                 ST->getPointerInfo(),
6994                                 false, false, STAlign);
6995
6996    AddToWorkList(NewLD.getNode());
6997    AddToWorkList(NewST.getNode());
6998    WorkListRemover DeadNodes(*this);
6999    DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7000    ++LdStFP2Int;
7001    return NewST;
7002  }
7003
7004  return SDValue();
7005}
7006
7007SDValue DAGCombiner::visitSTORE(SDNode *N) {
7008  StoreSDNode *ST  = cast<StoreSDNode>(N);
7009  SDValue Chain = ST->getChain();
7010  SDValue Value = ST->getValue();
7011  SDValue Ptr   = ST->getBasePtr();
7012
7013  // If this is a store of a bit convert, store the input value if the
7014  // resultant store does not need a higher alignment than the original.
7015  if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
7016      ST->isUnindexed()) {
7017    unsigned OrigAlign = ST->getAlignment();
7018    EVT SVT = Value.getOperand(0).getValueType();
7019    unsigned Align = TLI.getTargetData()->
7020      getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
7021    if (Align <= OrigAlign &&
7022        ((!LegalOperations && !ST->isVolatile()) ||
7023         TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
7024      return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7025                          Ptr, ST->getPointerInfo(), ST->isVolatile(),
7026                          ST->isNonTemporal(), OrigAlign);
7027  }
7028
7029  // Turn 'store undef, Ptr' -> nothing.
7030  if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
7031    return Chain;
7032
7033  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
7034  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
7035    // NOTE: If the original store is volatile, this transform must not increase
7036    // the number of stores.  For example, on x86-32 an f64 can be stored in one
7037    // processor operation but an i64 (which is not legal) requires two.  So the
7038    // transform should not be done in this case.
7039    if (Value.getOpcode() != ISD::TargetConstantFP) {
7040      SDValue Tmp;
7041      switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
7042      default: llvm_unreachable("Unknown FP type");
7043      case MVT::f80:    // We don't do this for these yet.
7044      case MVT::f128:
7045      case MVT::ppcf128:
7046        break;
7047      case MVT::f32:
7048        if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
7049            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7050          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
7051                              bitcastToAPInt().getZExtValue(), MVT::i32);
7052          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7053                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
7054                              ST->isNonTemporal(), ST->getAlignment());
7055        }
7056        break;
7057      case MVT::f64:
7058        if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
7059             !ST->isVolatile()) ||
7060            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
7061          Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
7062                                getZExtValue(), MVT::i64);
7063          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
7064                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
7065                              ST->isNonTemporal(), ST->getAlignment());
7066        }
7067
7068        if (!ST->isVolatile() &&
7069            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
7070          // Many FP stores are not made apparent until after legalize, e.g. for
7071          // argument passing.  Since this is so common, custom legalize the
7072          // 64-bit integer store into two 32-bit stores.
7073          uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
7074          SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
7075          SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
7076          if (TLI.isBigEndian()) std::swap(Lo, Hi);
7077
7078          unsigned Alignment = ST->getAlignment();
7079          bool isVolatile = ST->isVolatile();
7080          bool isNonTemporal = ST->isNonTemporal();
7081
7082          SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
7083                                     Ptr, ST->getPointerInfo(),
7084                                     isVolatile, isNonTemporal,
7085                                     ST->getAlignment());
7086          Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
7087                            DAG.getConstant(4, Ptr.getValueType()));
7088          Alignment = MinAlign(Alignment, 4U);
7089          SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
7090                                     Ptr, ST->getPointerInfo().getWithOffset(4),
7091                                     isVolatile, isNonTemporal,
7092                                     Alignment);
7093          return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7094                             St0, St1);
7095        }
7096
7097        break;
7098      }
7099    }
7100  }
7101
7102  // Try to infer better alignment information than the store already has.
7103  if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
7104    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7105      if (Align > ST->getAlignment())
7106        return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
7107                                 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7108                                 ST->isVolatile(), ST->isNonTemporal(), Align);
7109    }
7110  }
7111
7112  // Try transforming a pair floating point load / store ops to integer
7113  // load / store ops.
7114  SDValue NewST = TransformFPLoadStorePair(N);
7115  if (NewST.getNode())
7116    return NewST;
7117
7118  if (CombinerAA) {
7119    // Walk up chain skipping non-aliasing memory nodes.
7120    SDValue BetterChain = FindBetterChain(N, Chain);
7121
7122    // If there is a better chain.
7123    if (Chain != BetterChain) {
7124      SDValue ReplStore;
7125
7126      // Replace the chain to avoid dependency.
7127      if (ST->isTruncatingStore()) {
7128        ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7129                                      ST->getPointerInfo(),
7130                                      ST->getMemoryVT(), ST->isVolatile(),
7131                                      ST->isNonTemporal(), ST->getAlignment());
7132      } else {
7133        ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
7134                                 ST->getPointerInfo(),
7135                                 ST->isVolatile(), ST->isNonTemporal(),
7136                                 ST->getAlignment());
7137      }
7138
7139      // Create token to keep both nodes around.
7140      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7141                                  MVT::Other, Chain, ReplStore);
7142
7143      // Make sure the new and old chains are cleaned up.
7144      AddToWorkList(Token.getNode());
7145
7146      // Don't add users to work list.
7147      return CombineTo(N, Token, false);
7148    }
7149  }
7150
7151  // Try transforming N to an indexed store.
7152  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7153    return SDValue(N, 0);
7154
7155  // FIXME: is there such a thing as a truncating indexed store?
7156  if (ST->isTruncatingStore() && ST->isUnindexed() &&
7157      Value.getValueType().isInteger()) {
7158    // See if we can simplify the input to this truncstore with knowledge that
7159    // only the low bits are being used.  For example:
7160    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
7161    SDValue Shorter =
7162      GetDemandedBits(Value,
7163                      APInt::getLowBitsSet(
7164                        Value.getValueType().getScalarType().getSizeInBits(),
7165                        ST->getMemoryVT().getScalarType().getSizeInBits()));
7166    AddToWorkList(Value.getNode());
7167    if (Shorter.getNode())
7168      return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
7169                               Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7170                               ST->isVolatile(), ST->isNonTemporal(),
7171                               ST->getAlignment());
7172
7173    // Otherwise, see if we can simplify the operation with
7174    // SimplifyDemandedBits, which only works if the value has a single use.
7175    if (SimplifyDemandedBits(Value,
7176                        APInt::getLowBitsSet(
7177                          Value.getValueType().getScalarType().getSizeInBits(),
7178                          ST->getMemoryVT().getScalarType().getSizeInBits())))
7179      return SDValue(N, 0);
7180  }
7181
7182  // If this is a load followed by a store to the same location, then the store
7183  // is dead/noop.
7184  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
7185    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
7186        ST->isUnindexed() && !ST->isVolatile() &&
7187        // There can't be any side effects between the load and store, such as
7188        // a call or store.
7189        Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
7190      // The store is dead, remove it.
7191      return Chain;
7192    }
7193  }
7194
7195  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
7196  // truncating store.  We can do this even if this is already a truncstore.
7197  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
7198      && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
7199      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
7200                            ST->getMemoryVT())) {
7201    return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
7202                             Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
7203                             ST->isVolatile(), ST->isNonTemporal(),
7204                             ST->getAlignment());
7205  }
7206
7207  return ReduceLoadOpStoreWidth(N);
7208}
7209
7210SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
7211  SDValue InVec = N->getOperand(0);
7212  SDValue InVal = N->getOperand(1);
7213  SDValue EltNo = N->getOperand(2);
7214  DebugLoc dl = N->getDebugLoc();
7215
7216  // If the inserted element is an UNDEF, just use the input vector.
7217  if (InVal.getOpcode() == ISD::UNDEF)
7218    return InVec;
7219
7220  EVT VT = InVec.getValueType();
7221
7222  // If we can't generate a legal BUILD_VECTOR, exit
7223  if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
7224    return SDValue();
7225
7226  // Check that we know which element is being inserted
7227  if (!isa<ConstantSDNode>(EltNo))
7228    return SDValue();
7229  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7230
7231  // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
7232  // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
7233  // vector elements.
7234  SmallVector<SDValue, 8> Ops;
7235  if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
7236    Ops.append(InVec.getNode()->op_begin(),
7237               InVec.getNode()->op_end());
7238  } else if (InVec.getOpcode() == ISD::UNDEF) {
7239    unsigned NElts = VT.getVectorNumElements();
7240    Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
7241  } else {
7242    return SDValue();
7243  }
7244
7245  // Insert the element
7246  if (Elt < Ops.size()) {
7247    // All the operands of BUILD_VECTOR must have the same type;
7248    // we enforce that here.
7249    EVT OpVT = Ops[0].getValueType();
7250    if (InVal.getValueType() != OpVT)
7251      InVal = OpVT.bitsGT(InVal.getValueType()) ?
7252                DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
7253                DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
7254    Ops[Elt] = InVal;
7255  }
7256
7257  // Return the new vector
7258  return DAG.getNode(ISD::BUILD_VECTOR, dl,
7259                     VT, &Ops[0], Ops.size());
7260}
7261
7262SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
7263  // (vextract (scalar_to_vector val, 0) -> val
7264  SDValue InVec = N->getOperand(0);
7265  EVT VT = InVec.getValueType();
7266  EVT NVT = N->getValueType(0);
7267
7268  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7269    // Check if the result type doesn't match the inserted element type. A
7270    // SCALAR_TO_VECTOR may truncate the inserted element and the
7271    // EXTRACT_VECTOR_ELT may widen the extracted vector.
7272    SDValue InOp = InVec.getOperand(0);
7273    if (InOp.getValueType() != NVT) {
7274      assert(InOp.getValueType().isInteger() && NVT.isInteger());
7275      return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
7276    }
7277    return InOp;
7278  }
7279
7280  SDValue EltNo = N->getOperand(1);
7281  bool ConstEltNo = isa<ConstantSDNode>(EltNo);
7282
7283  // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
7284  // We only perform this optimization before the op legalization phase because
7285  // we may introduce new vector instructions which are not backed by TD patterns.
7286  // For example on AVX, extracting elements from a wide vector without using
7287  // extract_subvector.
7288  if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
7289      && ConstEltNo && !LegalOperations) {
7290    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7291    int NumElem = VT.getVectorNumElements();
7292    ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
7293    // Find the new index to extract from.
7294    int OrigElt = SVOp->getMaskElt(Elt);
7295
7296    // Extracting an undef index is undef.
7297    if (OrigElt == -1)
7298      return DAG.getUNDEF(NVT);
7299
7300    // Select the right vector half to extract from.
7301    if (OrigElt < NumElem) {
7302      InVec = InVec->getOperand(0);
7303    } else {
7304      InVec = InVec->getOperand(1);
7305      OrigElt -= NumElem;
7306    }
7307
7308    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
7309                       InVec, DAG.getConstant(OrigElt, MVT::i32));
7310  }
7311
7312  // Perform only after legalization to ensure build_vector / vector_shuffle
7313  // optimizations have already been done.
7314  if (!LegalOperations) return SDValue();
7315
7316  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
7317  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
7318  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
7319
7320  if (ConstEltNo) {
7321    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7322    bool NewLoad = false;
7323    bool BCNumEltsChanged = false;
7324    EVT ExtVT = VT.getVectorElementType();
7325    EVT LVT = ExtVT;
7326
7327    // If the result of load has to be truncated, then it's not necessarily
7328    // profitable.
7329    if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
7330      return SDValue();
7331
7332    if (InVec.getOpcode() == ISD::BITCAST) {
7333      // Don't duplicate a load with other uses.
7334      if (!InVec.hasOneUse())
7335        return SDValue();
7336
7337      EVT BCVT = InVec.getOperand(0).getValueType();
7338      if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
7339        return SDValue();
7340      if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
7341        BCNumEltsChanged = true;
7342      InVec = InVec.getOperand(0);
7343      ExtVT = BCVT.getVectorElementType();
7344      NewLoad = true;
7345    }
7346
7347    LoadSDNode *LN0 = NULL;
7348    const ShuffleVectorSDNode *SVN = NULL;
7349    if (ISD::isNormalLoad(InVec.getNode())) {
7350      LN0 = cast<LoadSDNode>(InVec);
7351    } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7352               InVec.getOperand(0).getValueType() == ExtVT &&
7353               ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
7354      // Don't duplicate a load with other uses.
7355      if (!InVec.hasOneUse())
7356        return SDValue();
7357
7358      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
7359    } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
7360      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
7361      // =>
7362      // (load $addr+1*size)
7363
7364      // Don't duplicate a load with other uses.
7365      if (!InVec.hasOneUse())
7366        return SDValue();
7367
7368      // If the bit convert changed the number of elements, it is unsafe
7369      // to examine the mask.
7370      if (BCNumEltsChanged)
7371        return SDValue();
7372
7373      // Select the input vector, guarding against out of range extract vector.
7374      unsigned NumElems = VT.getVectorNumElements();
7375      int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
7376      InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
7377
7378      if (InVec.getOpcode() == ISD::BITCAST) {
7379        // Don't duplicate a load with other uses.
7380        if (!InVec.hasOneUse())
7381          return SDValue();
7382
7383        InVec = InVec.getOperand(0);
7384      }
7385      if (ISD::isNormalLoad(InVec.getNode())) {
7386        LN0 = cast<LoadSDNode>(InVec);
7387        Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
7388      }
7389    }
7390
7391    // Make sure we found a non-volatile load and the extractelement is
7392    // the only use.
7393    if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
7394      return SDValue();
7395
7396    // If Idx was -1 above, Elt is going to be -1, so just return undef.
7397    if (Elt == -1)
7398      return DAG.getUNDEF(LVT);
7399
7400    unsigned Align = LN0->getAlignment();
7401    if (NewLoad) {
7402      // Check the resultant load doesn't need a higher alignment than the
7403      // original load.
7404      unsigned NewAlign =
7405        TLI.getTargetData()
7406            ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
7407
7408      if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
7409        return SDValue();
7410
7411      Align = NewAlign;
7412    }
7413
7414    SDValue NewPtr = LN0->getBasePtr();
7415    unsigned PtrOff = 0;
7416
7417    if (Elt) {
7418      PtrOff = LVT.getSizeInBits() * Elt / 8;
7419      EVT PtrType = NewPtr.getValueType();
7420      if (TLI.isBigEndian())
7421        PtrOff = VT.getSizeInBits() / 8 - PtrOff;
7422      NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
7423                           DAG.getConstant(PtrOff, PtrType));
7424    }
7425
7426    // The replacement we need to do here is a little tricky: we need to
7427    // replace an extractelement of a load with a load.
7428    // Use ReplaceAllUsesOfValuesWith to do the replacement.
7429    // Note that this replacement assumes that the extractvalue is the only
7430    // use of the load; that's okay because we don't want to perform this
7431    // transformation in other cases anyway.
7432    SDValue Load;
7433    SDValue Chain;
7434    if (NVT.bitsGT(LVT)) {
7435      // If the result type of vextract is wider than the load, then issue an
7436      // extending load instead.
7437      ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
7438        ? ISD::ZEXTLOAD : ISD::EXTLOAD;
7439      Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
7440                            NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
7441                            LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
7442      Chain = Load.getValue(1);
7443    } else {
7444      Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
7445                         LN0->getPointerInfo().getWithOffset(PtrOff),
7446                         LN0->isVolatile(), LN0->isNonTemporal(),
7447                         LN0->isInvariant(), Align);
7448      Chain = Load.getValue(1);
7449      if (NVT.bitsLT(LVT))
7450        Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
7451      else
7452        Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
7453    }
7454    WorkListRemover DeadNodes(*this);
7455    SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
7456    SDValue To[] = { Load, Chain };
7457    DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
7458    // Since we're explcitly calling ReplaceAllUses, add the new node to the
7459    // worklist explicitly as well.
7460    AddToWorkList(Load.getNode());
7461    AddUsersToWorkList(Load.getNode()); // Add users too
7462    // Make sure to revisit this node to clean it up; it will usually be dead.
7463    AddToWorkList(N);
7464    return SDValue(N, 0);
7465  }
7466
7467  return SDValue();
7468}
7469
7470SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
7471  unsigned NumInScalars = N->getNumOperands();
7472  DebugLoc dl = N->getDebugLoc();
7473  EVT VT = N->getValueType(0);
7474  // Check to see if this is a BUILD_VECTOR of a bunch of values
7475  // which come from any_extend or zero_extend nodes. If so, we can create
7476  // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
7477  // optimizations. We do not handle sign-extend because we can't fill the sign
7478  // using shuffles.
7479  EVT SourceType = MVT::Other;
7480  bool AllAnyExt = true;
7481  bool AllUndef = true;
7482  for (unsigned i = 0; i != NumInScalars; ++i) {
7483    SDValue In = N->getOperand(i);
7484    // Ignore undef inputs.
7485    if (In.getOpcode() == ISD::UNDEF) continue;
7486    AllUndef = false;
7487
7488    bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
7489    bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
7490
7491    // Abort if the element is not an extension.
7492    if (!ZeroExt && !AnyExt) {
7493      SourceType = MVT::Other;
7494      break;
7495    }
7496
7497    // The input is a ZeroExt or AnyExt. Check the original type.
7498    EVT InTy = In.getOperand(0).getValueType();
7499
7500    // Check that all of the widened source types are the same.
7501    if (SourceType == MVT::Other)
7502      // First time.
7503      SourceType = InTy;
7504    else if (InTy != SourceType) {
7505      // Multiple income types. Abort.
7506      SourceType = MVT::Other;
7507      break;
7508    }
7509
7510    // Check if all of the extends are ANY_EXTENDs.
7511    AllAnyExt &= AnyExt;
7512  }
7513
7514  if (AllUndef)
7515    return DAG.getUNDEF(VT);
7516
7517  // In order to have valid types, all of the inputs must be extended from the
7518  // same source type and all of the inputs must be any or zero extend.
7519  // Scalar sizes must be a power of two.
7520  EVT OutScalarTy = N->getValueType(0).getScalarType();
7521  bool ValidTypes = SourceType != MVT::Other &&
7522                 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
7523                 isPowerOf2_32(SourceType.getSizeInBits());
7524
7525  // We perform this optimization post type-legalization because
7526  // the type-legalizer often scalarizes integer-promoted vectors.
7527  // Performing this optimization before may create bit-casts which
7528  // will be type-legalized to complex code sequences.
7529  // We perform this optimization only before the operation legalizer because we
7530  // may introduce illegal operations.
7531  // Create a new simpler BUILD_VECTOR sequence which other optimizations can
7532  // turn into a single shuffle instruction.
7533  if ((Level == AfterLegalizeVectorOps || Level == AfterLegalizeTypes) &&
7534      ValidTypes) {
7535    bool isLE = TLI.isLittleEndian();
7536    unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
7537    assert(ElemRatio > 1 && "Invalid element size ratio");
7538    SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
7539                                 DAG.getConstant(0, SourceType);
7540
7541    unsigned NewBVElems = ElemRatio * N->getValueType(0).getVectorNumElements();
7542    SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
7543
7544    // Populate the new build_vector
7545    for (unsigned i=0; i < N->getNumOperands(); ++i) {
7546      SDValue Cast = N->getOperand(i);
7547      assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
7548              Cast.getOpcode() == ISD::ZERO_EXTEND ||
7549              Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
7550      SDValue In;
7551      if (Cast.getOpcode() == ISD::UNDEF)
7552        In = DAG.getUNDEF(SourceType);
7553      else
7554        In = Cast->getOperand(0);
7555      unsigned Index = isLE ? (i * ElemRatio) :
7556                              (i * ElemRatio + (ElemRatio - 1));
7557
7558      assert(Index < Ops.size() && "Invalid index");
7559      Ops[Index] = In;
7560    }
7561
7562    // The type of the new BUILD_VECTOR node.
7563    EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
7564    assert(VecVT.getSizeInBits() == N->getValueType(0).getSizeInBits() &&
7565           "Invalid vector size");
7566    // Check if the new vector type is legal.
7567    if (!isTypeLegal(VecVT)) return SDValue();
7568
7569    // Make the new BUILD_VECTOR.
7570    SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7571                                 VecVT, &Ops[0], Ops.size());
7572
7573    // The new BUILD_VECTOR node has the potential to be further optimized.
7574    AddToWorkList(BV.getNode());
7575    // Bitcast to the desired type.
7576    return DAG.getNode(ISD::BITCAST, dl, N->getValueType(0), BV);
7577  }
7578
7579  // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
7580  // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
7581  // at most two distinct vectors, turn this into a shuffle node.
7582
7583  // May only combine to shuffle after legalize if shuffle is legal.
7584  if (LegalOperations &&
7585      !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
7586    return SDValue();
7587
7588  SDValue VecIn1, VecIn2;
7589  for (unsigned i = 0; i != NumInScalars; ++i) {
7590    // Ignore undef inputs.
7591    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
7592
7593    // If this input is something other than a EXTRACT_VECTOR_ELT with a
7594    // constant index, bail out.
7595    if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7596        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
7597      VecIn1 = VecIn2 = SDValue(0, 0);
7598      break;
7599    }
7600
7601    // We allow up to two distinct input vectors.
7602    SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
7603    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
7604      continue;
7605
7606    if (VecIn1.getNode() == 0) {
7607      VecIn1 = ExtractedFromVec;
7608    } else if (VecIn2.getNode() == 0) {
7609      VecIn2 = ExtractedFromVec;
7610    } else {
7611      // Too many inputs.
7612      VecIn1 = VecIn2 = SDValue(0, 0);
7613      break;
7614    }
7615  }
7616
7617    // If everything is good, we can make a shuffle operation.
7618  if (VecIn1.getNode()) {
7619    SmallVector<int, 8> Mask;
7620    for (unsigned i = 0; i != NumInScalars; ++i) {
7621      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
7622        Mask.push_back(-1);
7623        continue;
7624      }
7625
7626      // If extracting from the first vector, just use the index directly.
7627      SDValue Extract = N->getOperand(i);
7628      SDValue ExtVal = Extract.getOperand(1);
7629      if (Extract.getOperand(0) == VecIn1) {
7630        unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7631        if (ExtIndex > VT.getVectorNumElements())
7632          return SDValue();
7633
7634        Mask.push_back(ExtIndex);
7635        continue;
7636      }
7637
7638      // Otherwise, use InIdx + VecSize
7639      unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
7640      Mask.push_back(Idx+NumInScalars);
7641    }
7642
7643    // We can't generate a shuffle node with mismatched input and output types.
7644    // Attempt to transform a single input vector to the correct type.
7645    if ((VT != VecIn1.getValueType())) {
7646      // We don't support shuffeling between TWO values of different types.
7647      if (VecIn2.getNode() != 0)
7648        return SDValue();
7649
7650      // We only support widening of vectors which are half the size of the
7651      // output registers. For example XMM->YMM widening on X86 with AVX.
7652      if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
7653        return SDValue();
7654
7655      // Widen the input vector by adding undef values.
7656      VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7657                           VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
7658    }
7659
7660    // If VecIn2 is unused then change it to undef.
7661    VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7662
7663    // Check that we were able to transform all incoming values to the same type.
7664    if (VecIn2.getValueType() != VecIn1.getValueType() ||
7665        VecIn1.getValueType() != VT)
7666          return SDValue();
7667
7668    // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
7669    if (!isTypeLegal(VT))
7670      return SDValue();
7671
7672    // Return the new VECTOR_SHUFFLE node.
7673    SDValue Ops[2];
7674    Ops[0] = VecIn1;
7675    Ops[1] = VecIn2;
7676    return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
7677  }
7678
7679  return SDValue();
7680}
7681
7682SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
7683  // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
7684  // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
7685  // inputs come from at most two distinct vectors, turn this into a shuffle
7686  // node.
7687
7688  // If we only have one input vector, we don't need to do any concatenation.
7689  if (N->getNumOperands() == 1)
7690    return N->getOperand(0);
7691
7692  return SDValue();
7693}
7694
7695SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
7696  EVT NVT = N->getValueType(0);
7697  SDValue V = N->getOperand(0);
7698
7699  if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
7700    // Handle only simple case where vector being inserted and vector
7701    // being extracted are of same type, and are half size of larger vectors.
7702    EVT BigVT = V->getOperand(0).getValueType();
7703    EVT SmallVT = V->getOperand(1).getValueType();
7704    if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
7705      return SDValue();
7706
7707    // Only handle cases where both indexes are constants with the same type.
7708    ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7709    ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
7710
7711    if (InsIdx && ExtIdx &&
7712        InsIdx->getValueType(0).getSizeInBits() <= 64 &&
7713        ExtIdx->getValueType(0).getSizeInBits() <= 64) {
7714      // Combine:
7715      //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
7716      // Into:
7717      //    indices are equal => V1
7718      //    otherwise => (extract_subvec V1, ExtIdx)
7719      if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
7720        return V->getOperand(1);
7721      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
7722                         V->getOperand(0), N->getOperand(1));
7723    }
7724  }
7725
7726  return SDValue();
7727}
7728
7729SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
7730  EVT VT = N->getValueType(0);
7731  unsigned NumElts = VT.getVectorNumElements();
7732
7733  SDValue N0 = N->getOperand(0);
7734  SDValue N1 = N->getOperand(1);
7735
7736  assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
7737
7738  // Canonicalize shuffle undef, undef -> undef
7739  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
7740    return DAG.getUNDEF(VT);
7741
7742  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7743
7744  // Canonicalize shuffle v, v -> v, undef
7745  if (N0 == N1) {
7746    SmallVector<int, 8> NewMask;
7747    for (unsigned i = 0; i != NumElts; ++i) {
7748      int Idx = SVN->getMaskElt(i);
7749      if (Idx >= (int)NumElts) Idx -= NumElts;
7750      NewMask.push_back(Idx);
7751    }
7752    return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
7753                                &NewMask[0]);
7754  }
7755
7756  // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
7757  if (N0.getOpcode() == ISD::UNDEF) {
7758    SmallVector<int, 8> NewMask;
7759    for (unsigned i = 0; i != NumElts; ++i) {
7760      int Idx = SVN->getMaskElt(i);
7761      if (Idx >= 0) {
7762        if (Idx < (int)NumElts)
7763          Idx += NumElts;
7764        else
7765          Idx -= NumElts;
7766      }
7767      NewMask.push_back(Idx);
7768    }
7769    return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
7770                                &NewMask[0]);
7771  }
7772
7773  // Remove references to rhs if it is undef
7774  if (N1.getOpcode() == ISD::UNDEF) {
7775    bool Changed = false;
7776    SmallVector<int, 8> NewMask;
7777    for (unsigned i = 0; i != NumElts; ++i) {
7778      int Idx = SVN->getMaskElt(i);
7779      if (Idx >= (int)NumElts) {
7780        Idx = -1;
7781        Changed = true;
7782      }
7783      NewMask.push_back(Idx);
7784    }
7785    if (Changed)
7786      return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
7787  }
7788
7789  // If it is a splat, check if the argument vector is another splat or a
7790  // build_vector with all scalar elements the same.
7791  if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
7792    SDNode *V = N0.getNode();
7793
7794    // If this is a bit convert that changes the element type of the vector but
7795    // not the number of vector elements, look through it.  Be careful not to
7796    // look though conversions that change things like v4f32 to v2f64.
7797    if (V->getOpcode() == ISD::BITCAST) {
7798      SDValue ConvInput = V->getOperand(0);
7799      if (ConvInput.getValueType().isVector() &&
7800          ConvInput.getValueType().getVectorNumElements() == NumElts)
7801        V = ConvInput.getNode();
7802    }
7803
7804    if (V->getOpcode() == ISD::BUILD_VECTOR) {
7805      assert(V->getNumOperands() == NumElts &&
7806             "BUILD_VECTOR has wrong number of operands");
7807      SDValue Base;
7808      bool AllSame = true;
7809      for (unsigned i = 0; i != NumElts; ++i) {
7810        if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7811          Base = V->getOperand(i);
7812          break;
7813        }
7814      }
7815      // Splat of <u, u, u, u>, return <u, u, u, u>
7816      if (!Base.getNode())
7817        return N0;
7818      for (unsigned i = 0; i != NumElts; ++i) {
7819        if (V->getOperand(i) != Base) {
7820          AllSame = false;
7821          break;
7822        }
7823      }
7824      // Splat of <x, x, x, x>, return <x, x, x, x>
7825      if (AllSame)
7826        return N0;
7827    }
7828  }
7829
7830  // If this shuffle node is simply a swizzle of another shuffle node,
7831  // and it reverses the swizzle of the previous shuffle then we can
7832  // optimize shuffle(shuffle(x, undef), undef) -> x.
7833  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
7834      N1.getOpcode() == ISD::UNDEF) {
7835
7836    ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
7837
7838    // Shuffle nodes can only reverse shuffles with a single non-undef value.
7839    if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
7840      return SDValue();
7841
7842    // The incoming shuffle must be of the same type as the result of the
7843    // current shuffle.
7844    assert(OtherSV->getOperand(0).getValueType() == VT &&
7845           "Shuffle types don't match");
7846
7847    for (unsigned i = 0; i != NumElts; ++i) {
7848      int Idx = SVN->getMaskElt(i);
7849      assert(Idx < (int)NumElts && "Index references undef operand");
7850      // Next, this index comes from the first value, which is the incoming
7851      // shuffle. Adopt the incoming index.
7852      if (Idx >= 0)
7853        Idx = OtherSV->getMaskElt(Idx);
7854
7855      // The combined shuffle must map each index to itself.
7856      if (Idx >= 0 && (unsigned)Idx != i)
7857        return SDValue();
7858    }
7859
7860    return OtherSV->getOperand(0);
7861  }
7862
7863  return SDValue();
7864}
7865
7866SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
7867  if (!TLI.getShouldFoldAtomicFences())
7868    return SDValue();
7869
7870  SDValue atomic = N->getOperand(0);
7871  switch (atomic.getOpcode()) {
7872    case ISD::ATOMIC_CMP_SWAP:
7873    case ISD::ATOMIC_SWAP:
7874    case ISD::ATOMIC_LOAD_ADD:
7875    case ISD::ATOMIC_LOAD_SUB:
7876    case ISD::ATOMIC_LOAD_AND:
7877    case ISD::ATOMIC_LOAD_OR:
7878    case ISD::ATOMIC_LOAD_XOR:
7879    case ISD::ATOMIC_LOAD_NAND:
7880    case ISD::ATOMIC_LOAD_MIN:
7881    case ISD::ATOMIC_LOAD_MAX:
7882    case ISD::ATOMIC_LOAD_UMIN:
7883    case ISD::ATOMIC_LOAD_UMAX:
7884      break;
7885    default:
7886      return SDValue();
7887  }
7888
7889  SDValue fence = atomic.getOperand(0);
7890  if (fence.getOpcode() != ISD::MEMBARRIER)
7891    return SDValue();
7892
7893  switch (atomic.getOpcode()) {
7894    case ISD::ATOMIC_CMP_SWAP:
7895      return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
7896                                    fence.getOperand(0),
7897                                    atomic.getOperand(1), atomic.getOperand(2),
7898                                    atomic.getOperand(3)), atomic.getResNo());
7899    case ISD::ATOMIC_SWAP:
7900    case ISD::ATOMIC_LOAD_ADD:
7901    case ISD::ATOMIC_LOAD_SUB:
7902    case ISD::ATOMIC_LOAD_AND:
7903    case ISD::ATOMIC_LOAD_OR:
7904    case ISD::ATOMIC_LOAD_XOR:
7905    case ISD::ATOMIC_LOAD_NAND:
7906    case ISD::ATOMIC_LOAD_MIN:
7907    case ISD::ATOMIC_LOAD_MAX:
7908    case ISD::ATOMIC_LOAD_UMIN:
7909    case ISD::ATOMIC_LOAD_UMAX:
7910      return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
7911                                    fence.getOperand(0),
7912                                    atomic.getOperand(1), atomic.getOperand(2)),
7913                     atomic.getResNo());
7914    default:
7915      return SDValue();
7916  }
7917}
7918
7919/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
7920/// an AND to a vector_shuffle with the destination vector and a zero vector.
7921/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
7922///      vector_shuffle V, Zero, <0, 4, 2, 4>
7923SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
7924  EVT VT = N->getValueType(0);
7925  DebugLoc dl = N->getDebugLoc();
7926  SDValue LHS = N->getOperand(0);
7927  SDValue RHS = N->getOperand(1);
7928  if (N->getOpcode() == ISD::AND) {
7929    if (RHS.getOpcode() == ISD::BITCAST)
7930      RHS = RHS.getOperand(0);
7931    if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
7932      SmallVector<int, 8> Indices;
7933      unsigned NumElts = RHS.getNumOperands();
7934      for (unsigned i = 0; i != NumElts; ++i) {
7935        SDValue Elt = RHS.getOperand(i);
7936        if (!isa<ConstantSDNode>(Elt))
7937          return SDValue();
7938
7939        if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
7940          Indices.push_back(i);
7941        else if (cast<ConstantSDNode>(Elt)->isNullValue())
7942          Indices.push_back(NumElts);
7943        else
7944          return SDValue();
7945      }
7946
7947      // Let's see if the target supports this vector_shuffle.
7948      EVT RVT = RHS.getValueType();
7949      if (!TLI.isVectorClearMaskLegal(Indices, RVT))
7950        return SDValue();
7951
7952      // Return the new VECTOR_SHUFFLE node.
7953      EVT EltVT = RVT.getVectorElementType();
7954      SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
7955                                     DAG.getConstant(0, EltVT));
7956      SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
7957                                 RVT, &ZeroOps[0], ZeroOps.size());
7958      LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
7959      SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
7960      return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
7961    }
7962  }
7963
7964  return SDValue();
7965}
7966
7967/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
7968SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
7969  // After legalize, the target may be depending on adds and other
7970  // binary ops to provide legal ways to construct constants or other
7971  // things. Simplifying them may result in a loss of legality.
7972  if (LegalOperations) return SDValue();
7973
7974  assert(N->getValueType(0).isVector() &&
7975         "SimplifyVBinOp only works on vectors!");
7976
7977  SDValue LHS = N->getOperand(0);
7978  SDValue RHS = N->getOperand(1);
7979  SDValue Shuffle = XformToShuffleWithZero(N);
7980  if (Shuffle.getNode()) return Shuffle;
7981
7982  // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
7983  // this operation.
7984  if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
7985      RHS.getOpcode() == ISD::BUILD_VECTOR) {
7986    SmallVector<SDValue, 8> Ops;
7987    for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
7988      SDValue LHSOp = LHS.getOperand(i);
7989      SDValue RHSOp = RHS.getOperand(i);
7990      // If these two elements can't be folded, bail out.
7991      if ((LHSOp.getOpcode() != ISD::UNDEF &&
7992           LHSOp.getOpcode() != ISD::Constant &&
7993           LHSOp.getOpcode() != ISD::ConstantFP) ||
7994          (RHSOp.getOpcode() != ISD::UNDEF &&
7995           RHSOp.getOpcode() != ISD::Constant &&
7996           RHSOp.getOpcode() != ISD::ConstantFP))
7997        break;
7998
7999      // Can't fold divide by zero.
8000      if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
8001          N->getOpcode() == ISD::FDIV) {
8002        if ((RHSOp.getOpcode() == ISD::Constant &&
8003             cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
8004            (RHSOp.getOpcode() == ISD::ConstantFP &&
8005             cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
8006          break;
8007      }
8008
8009      EVT VT = LHSOp.getValueType();
8010      EVT RVT = RHSOp.getValueType();
8011      if (RVT != VT) {
8012        // Integer BUILD_VECTOR operands may have types larger than the element
8013        // size (e.g., when the element type is not legal).  Prior to type
8014        // legalization, the types may not match between the two BUILD_VECTORS.
8015        // Truncate one of the operands to make them match.
8016        if (RVT.getSizeInBits() > VT.getSizeInBits()) {
8017          RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
8018        } else {
8019          LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
8020          VT = RVT;
8021        }
8022      }
8023      SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
8024                                   LHSOp, RHSOp);
8025      if (FoldOp.getOpcode() != ISD::UNDEF &&
8026          FoldOp.getOpcode() != ISD::Constant &&
8027          FoldOp.getOpcode() != ISD::ConstantFP)
8028        break;
8029      Ops.push_back(FoldOp);
8030      AddToWorkList(FoldOp.getNode());
8031    }
8032
8033    if (Ops.size() == LHS.getNumOperands())
8034      return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
8035                         LHS.getValueType(), &Ops[0], Ops.size());
8036  }
8037
8038  return SDValue();
8039}
8040
8041SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
8042                                    SDValue N1, SDValue N2){
8043  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
8044
8045  SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
8046                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8047
8048  // If we got a simplified select_cc node back from SimplifySelectCC, then
8049  // break it down into a new SETCC node, and a new SELECT node, and then return
8050  // the SELECT node, since we were called with a SELECT node.
8051  if (SCC.getNode()) {
8052    // Check to see if we got a select_cc back (to turn into setcc/select).
8053    // Otherwise, just return whatever node we got back, like fabs.
8054    if (SCC.getOpcode() == ISD::SELECT_CC) {
8055      SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
8056                                  N0.getValueType(),
8057                                  SCC.getOperand(0), SCC.getOperand(1),
8058                                  SCC.getOperand(4));
8059      AddToWorkList(SETCC.getNode());
8060      return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
8061                         SCC.getOperand(2), SCC.getOperand(3), SETCC);
8062    }
8063
8064    return SCC;
8065  }
8066  return SDValue();
8067}
8068
8069/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
8070/// are the two values being selected between, see if we can simplify the
8071/// select.  Callers of this should assume that TheSelect is deleted if this
8072/// returns true.  As such, they should return the appropriate thing (e.g. the
8073/// node) back to the top-level of the DAG combiner loop to avoid it being
8074/// looked at.
8075bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
8076                                    SDValue RHS) {
8077
8078  // Cannot simplify select with vector condition
8079  if (TheSelect->getOperand(0).getValueType().isVector()) return false;
8080
8081  // If this is a select from two identical things, try to pull the operation
8082  // through the select.
8083  if (LHS.getOpcode() != RHS.getOpcode() ||
8084      !LHS.hasOneUse() || !RHS.hasOneUse())
8085    return false;
8086
8087  // If this is a load and the token chain is identical, replace the select
8088  // of two loads with a load through a select of the address to load from.
8089  // This triggers in things like "select bool X, 10.0, 123.0" after the FP
8090  // constants have been dropped into the constant pool.
8091  if (LHS.getOpcode() == ISD::LOAD) {
8092    LoadSDNode *LLD = cast<LoadSDNode>(LHS);
8093    LoadSDNode *RLD = cast<LoadSDNode>(RHS);
8094
8095    // Token chains must be identical.
8096    if (LHS.getOperand(0) != RHS.getOperand(0) ||
8097        // Do not let this transformation reduce the number of volatile loads.
8098        LLD->isVolatile() || RLD->isVolatile() ||
8099        // If this is an EXTLOAD, the VT's must match.
8100        LLD->getMemoryVT() != RLD->getMemoryVT() ||
8101        // If this is an EXTLOAD, the kind of extension must match.
8102        (LLD->getExtensionType() != RLD->getExtensionType() &&
8103         // The only exception is if one of the extensions is anyext.
8104         LLD->getExtensionType() != ISD::EXTLOAD &&
8105         RLD->getExtensionType() != ISD::EXTLOAD) ||
8106        // FIXME: this discards src value information.  This is
8107        // over-conservative. It would be beneficial to be able to remember
8108        // both potential memory locations.  Since we are discarding
8109        // src value info, don't do the transformation if the memory
8110        // locations are not in the default address space.
8111        LLD->getPointerInfo().getAddrSpace() != 0 ||
8112        RLD->getPointerInfo().getAddrSpace() != 0)
8113      return false;
8114
8115    // Check that the select condition doesn't reach either load.  If so,
8116    // folding this will induce a cycle into the DAG.  If not, this is safe to
8117    // xform, so create a select of the addresses.
8118    SDValue Addr;
8119    if (TheSelect->getOpcode() == ISD::SELECT) {
8120      SDNode *CondNode = TheSelect->getOperand(0).getNode();
8121      if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
8122          (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
8123        return false;
8124      Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
8125                         LLD->getBasePtr().getValueType(),
8126                         TheSelect->getOperand(0), LLD->getBasePtr(),
8127                         RLD->getBasePtr());
8128    } else {  // Otherwise SELECT_CC
8129      SDNode *CondLHS = TheSelect->getOperand(0).getNode();
8130      SDNode *CondRHS = TheSelect->getOperand(1).getNode();
8131
8132      if ((LLD->hasAnyUseOfValue(1) &&
8133           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
8134          (RLD->hasAnyUseOfValue(1) &&
8135           (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
8136        return false;
8137
8138      Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
8139                         LLD->getBasePtr().getValueType(),
8140                         TheSelect->getOperand(0),
8141                         TheSelect->getOperand(1),
8142                         LLD->getBasePtr(), RLD->getBasePtr(),
8143                         TheSelect->getOperand(4));
8144    }
8145
8146    SDValue Load;
8147    if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
8148      Load = DAG.getLoad(TheSelect->getValueType(0),
8149                         TheSelect->getDebugLoc(),
8150                         // FIXME: Discards pointer info.
8151                         LLD->getChain(), Addr, MachinePointerInfo(),
8152                         LLD->isVolatile(), LLD->isNonTemporal(),
8153                         LLD->isInvariant(), LLD->getAlignment());
8154    } else {
8155      Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
8156                            RLD->getExtensionType() : LLD->getExtensionType(),
8157                            TheSelect->getDebugLoc(),
8158                            TheSelect->getValueType(0),
8159                            // FIXME: Discards pointer info.
8160                            LLD->getChain(), Addr, MachinePointerInfo(),
8161                            LLD->getMemoryVT(), LLD->isVolatile(),
8162                            LLD->isNonTemporal(), LLD->getAlignment());
8163    }
8164
8165    // Users of the select now use the result of the load.
8166    CombineTo(TheSelect, Load);
8167
8168    // Users of the old loads now use the new load's chain.  We know the
8169    // old-load value is dead now.
8170    CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
8171    CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
8172    return true;
8173  }
8174
8175  return false;
8176}
8177
8178/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
8179/// where 'cond' is the comparison specified by CC.
8180SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
8181                                      SDValue N2, SDValue N3,
8182                                      ISD::CondCode CC, bool NotExtCompare) {
8183  // (x ? y : y) -> y.
8184  if (N2 == N3) return N2;
8185
8186  EVT VT = N2.getValueType();
8187  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
8188  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
8189  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
8190
8191  // Determine if the condition we're dealing with is constant
8192  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
8193                              N0, N1, CC, DL, false);
8194  if (SCC.getNode()) AddToWorkList(SCC.getNode());
8195  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
8196
8197  // fold select_cc true, x, y -> x
8198  if (SCCC && !SCCC->isNullValue())
8199    return N2;
8200  // fold select_cc false, x, y -> y
8201  if (SCCC && SCCC->isNullValue())
8202    return N3;
8203
8204  // Check to see if we can simplify the select into an fabs node
8205  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
8206    // Allow either -0.0 or 0.0
8207    if (CFP->getValueAPF().isZero()) {
8208      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
8209      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
8210          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
8211          N2 == N3.getOperand(0))
8212        return DAG.getNode(ISD::FABS, DL, VT, N0);
8213
8214      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
8215      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
8216          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
8217          N2.getOperand(0) == N3)
8218        return DAG.getNode(ISD::FABS, DL, VT, N3);
8219    }
8220  }
8221
8222  // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
8223  // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
8224  // in it.  This is a win when the constant is not otherwise available because
8225  // it replaces two constant pool loads with one.  We only do this if the FP
8226  // type is known to be legal, because if it isn't, then we are before legalize
8227  // types an we want the other legalization to happen first (e.g. to avoid
8228  // messing with soft float) and if the ConstantFP is not legal, because if
8229  // it is legal, we may not need to store the FP constant in a constant pool.
8230  if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
8231    if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
8232      if (TLI.isTypeLegal(N2.getValueType()) &&
8233          (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
8234           TargetLowering::Legal) &&
8235          // If both constants have multiple uses, then we won't need to do an
8236          // extra load, they are likely around in registers for other users.
8237          (TV->hasOneUse() || FV->hasOneUse())) {
8238        Constant *Elts[] = {
8239          const_cast<ConstantFP*>(FV->getConstantFPValue()),
8240          const_cast<ConstantFP*>(TV->getConstantFPValue())
8241        };
8242        Type *FPTy = Elts[0]->getType();
8243        const TargetData &TD = *TLI.getTargetData();
8244
8245        // Create a ConstantArray of the two constants.
8246        Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
8247        SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
8248                                            TD.getPrefTypeAlignment(FPTy));
8249        unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8250
8251        // Get the offsets to the 0 and 1 element of the array so that we can
8252        // select between them.
8253        SDValue Zero = DAG.getIntPtrConstant(0);
8254        unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
8255        SDValue One = DAG.getIntPtrConstant(EltSize);
8256
8257        SDValue Cond = DAG.getSetCC(DL,
8258                                    TLI.getSetCCResultType(N0.getValueType()),
8259                                    N0, N1, CC);
8260        AddToWorkList(Cond.getNode());
8261        SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
8262                                        Cond, One, Zero);
8263        AddToWorkList(CstOffset.getNode());
8264        CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
8265                            CstOffset);
8266        AddToWorkList(CPIdx.getNode());
8267        return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
8268                           MachinePointerInfo::getConstantPool(), false,
8269                           false, false, Alignment);
8270
8271      }
8272    }
8273
8274  // Check to see if we can perform the "gzip trick", transforming
8275  // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
8276  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
8277      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
8278       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
8279    EVT XType = N0.getValueType();
8280    EVT AType = N2.getValueType();
8281    if (XType.bitsGE(AType)) {
8282      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
8283      // single-bit constant.
8284      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
8285        unsigned ShCtV = N2C->getAPIntValue().logBase2();
8286        ShCtV = XType.getSizeInBits()-ShCtV-1;
8287        SDValue ShCt = DAG.getConstant(ShCtV,
8288                                       getShiftAmountTy(N0.getValueType()));
8289        SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
8290                                    XType, N0, ShCt);
8291        AddToWorkList(Shift.getNode());
8292
8293        if (XType.bitsGT(AType)) {
8294          Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8295          AddToWorkList(Shift.getNode());
8296        }
8297
8298        return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8299      }
8300
8301      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
8302                                  XType, N0,
8303                                  DAG.getConstant(XType.getSizeInBits()-1,
8304                                         getShiftAmountTy(N0.getValueType())));
8305      AddToWorkList(Shift.getNode());
8306
8307      if (XType.bitsGT(AType)) {
8308        Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
8309        AddToWorkList(Shift.getNode());
8310      }
8311
8312      return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
8313    }
8314  }
8315
8316  // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
8317  // where y is has a single bit set.
8318  // A plaintext description would be, we can turn the SELECT_CC into an AND
8319  // when the condition can be materialized as an all-ones register.  Any
8320  // single bit-test can be materialized as an all-ones register with
8321  // shift-left and shift-right-arith.
8322  if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
8323      N0->getValueType(0) == VT &&
8324      N1C && N1C->isNullValue() &&
8325      N2C && N2C->isNullValue()) {
8326    SDValue AndLHS = N0->getOperand(0);
8327    ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8328    if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
8329      // Shift the tested bit over the sign bit.
8330      APInt AndMask = ConstAndRHS->getAPIntValue();
8331      SDValue ShlAmt =
8332        DAG.getConstant(AndMask.countLeadingZeros(),
8333                        getShiftAmountTy(AndLHS.getValueType()));
8334      SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
8335
8336      // Now arithmetic right shift it all the way over, so the result is either
8337      // all-ones, or zero.
8338      SDValue ShrAmt =
8339        DAG.getConstant(AndMask.getBitWidth()-1,
8340                        getShiftAmountTy(Shl.getValueType()));
8341      SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
8342
8343      return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
8344    }
8345  }
8346
8347  // fold select C, 16, 0 -> shl C, 4
8348  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
8349    TLI.getBooleanContents(N0.getValueType().isVector()) ==
8350      TargetLowering::ZeroOrOneBooleanContent) {
8351
8352    // If the caller doesn't want us to simplify this into a zext of a compare,
8353    // don't do it.
8354    if (NotExtCompare && N2C->getAPIntValue() == 1)
8355      return SDValue();
8356
8357    // Get a SetCC of the condition
8358    // FIXME: Should probably make sure that setcc is legal if we ever have a
8359    // target where it isn't.
8360    SDValue Temp, SCC;
8361    // cast from setcc result type to select result type
8362    if (LegalTypes) {
8363      SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
8364                          N0, N1, CC);
8365      if (N2.getValueType().bitsLT(SCC.getValueType()))
8366        Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
8367      else
8368        Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8369                           N2.getValueType(), SCC);
8370    } else {
8371      SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
8372      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
8373                         N2.getValueType(), SCC);
8374    }
8375
8376    AddToWorkList(SCC.getNode());
8377    AddToWorkList(Temp.getNode());
8378
8379    if (N2C->getAPIntValue() == 1)
8380      return Temp;
8381
8382    // shl setcc result by log2 n2c
8383    return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
8384                       DAG.getConstant(N2C->getAPIntValue().logBase2(),
8385                                       getShiftAmountTy(Temp.getValueType())));
8386  }
8387
8388  // Check to see if this is the equivalent of setcc
8389  // FIXME: Turn all of these into setcc if setcc if setcc is legal
8390  // otherwise, go ahead with the folds.
8391  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
8392    EVT XType = N0.getValueType();
8393    if (!LegalOperations ||
8394        TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
8395      SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
8396      if (Res.getValueType() != VT)
8397        Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
8398      return Res;
8399    }
8400
8401    // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
8402    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
8403        (!LegalOperations ||
8404         TLI.isOperationLegal(ISD::CTLZ, XType))) {
8405      SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
8406      return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
8407                         DAG.getConstant(Log2_32(XType.getSizeInBits()),
8408                                       getShiftAmountTy(Ctlz.getValueType())));
8409    }
8410    // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
8411    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
8412      SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
8413                                  XType, DAG.getConstant(0, XType), N0);
8414      SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
8415      return DAG.getNode(ISD::SRL, DL, XType,
8416                         DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
8417                         DAG.getConstant(XType.getSizeInBits()-1,
8418                                         getShiftAmountTy(XType)));
8419    }
8420    // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
8421    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
8422      SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
8423                                 DAG.getConstant(XType.getSizeInBits()-1,
8424                                         getShiftAmountTy(N0.getValueType())));
8425      return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
8426    }
8427  }
8428
8429  // Check to see if this is an integer abs.
8430  // select_cc setg[te] X,  0,  X, -X ->
8431  // select_cc setgt    X, -1,  X, -X ->
8432  // select_cc setl[te] X,  0, -X,  X ->
8433  // select_cc setlt    X,  1, -X,  X ->
8434  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
8435  if (N1C) {
8436    ConstantSDNode *SubC = NULL;
8437    if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
8438         (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
8439        N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
8440      SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
8441    else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
8442              (N1C->isOne() && CC == ISD::SETLT)) &&
8443             N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
8444      SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
8445
8446    EVT XType = N0.getValueType();
8447    if (SubC && SubC->isNullValue() && XType.isInteger()) {
8448      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
8449                                  N0,
8450                                  DAG.getConstant(XType.getSizeInBits()-1,
8451                                         getShiftAmountTy(N0.getValueType())));
8452      SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
8453                                XType, N0, Shift);
8454      AddToWorkList(Shift.getNode());
8455      AddToWorkList(Add.getNode());
8456      return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
8457    }
8458  }
8459
8460  return SDValue();
8461}
8462
8463/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
8464SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
8465                                   SDValue N1, ISD::CondCode Cond,
8466                                   DebugLoc DL, bool foldBooleans) {
8467  TargetLowering::DAGCombinerInfo
8468    DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
8469  return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
8470}
8471
8472/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
8473/// return a DAG expression to select that will generate the same value by
8474/// multiplying by a magic number.  See:
8475/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8476SDValue DAGCombiner::BuildSDIV(SDNode *N) {
8477  std::vector<SDNode*> Built;
8478  SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
8479
8480  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8481       ii != ee; ++ii)
8482    AddToWorkList(*ii);
8483  return S;
8484}
8485
8486/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
8487/// return a DAG expression to select that will generate the same value by
8488/// multiplying by a magic number.  See:
8489/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
8490SDValue DAGCombiner::BuildUDIV(SDNode *N) {
8491  std::vector<SDNode*> Built;
8492  SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
8493
8494  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
8495       ii != ee; ++ii)
8496    AddToWorkList(*ii);
8497  return S;
8498}
8499
8500/// FindBaseOffset - Return true if base is a frame index, which is known not
8501// to alias with anything but itself.  Provides base object and offset as
8502// results.
8503static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
8504                           const GlobalValue *&GV, void *&CV) {
8505  // Assume it is a primitive operation.
8506  Base = Ptr; Offset = 0; GV = 0; CV = 0;
8507
8508  // If it's an adding a simple constant then integrate the offset.
8509  if (Base.getOpcode() == ISD::ADD) {
8510    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
8511      Base = Base.getOperand(0);
8512      Offset += C->getZExtValue();
8513    }
8514  }
8515
8516  // Return the underlying GlobalValue, and update the Offset.  Return false
8517  // for GlobalAddressSDNode since the same GlobalAddress may be represented
8518  // by multiple nodes with different offsets.
8519  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
8520    GV = G->getGlobal();
8521    Offset += G->getOffset();
8522    return false;
8523  }
8524
8525  // Return the underlying Constant value, and update the Offset.  Return false
8526  // for ConstantSDNodes since the same constant pool entry may be represented
8527  // by multiple nodes with different offsets.
8528  if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
8529    CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
8530                                         : (void *)C->getConstVal();
8531    Offset += C->getOffset();
8532    return false;
8533  }
8534  // If it's any of the following then it can't alias with anything but itself.
8535  return isa<FrameIndexSDNode>(Base);
8536}
8537
8538/// isAlias - Return true if there is any possibility that the two addresses
8539/// overlap.
8540bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
8541                          const Value *SrcValue1, int SrcValueOffset1,
8542                          unsigned SrcValueAlign1,
8543                          const MDNode *TBAAInfo1,
8544                          SDValue Ptr2, int64_t Size2,
8545                          const Value *SrcValue2, int SrcValueOffset2,
8546                          unsigned SrcValueAlign2,
8547                          const MDNode *TBAAInfo2) const {
8548  // If they are the same then they must be aliases.
8549  if (Ptr1 == Ptr2) return true;
8550
8551  // Gather base node and offset information.
8552  SDValue Base1, Base2;
8553  int64_t Offset1, Offset2;
8554  const GlobalValue *GV1, *GV2;
8555  void *CV1, *CV2;
8556  bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
8557  bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
8558
8559  // If they have a same base address then check to see if they overlap.
8560  if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
8561    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8562
8563  // It is possible for different frame indices to alias each other, mostly
8564  // when tail call optimization reuses return address slots for arguments.
8565  // To catch this case, look up the actual index of frame indices to compute
8566  // the real alias relationship.
8567  if (isFrameIndex1 && isFrameIndex2) {
8568    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8569    Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
8570    Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
8571    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
8572  }
8573
8574  // Otherwise, if we know what the bases are, and they aren't identical, then
8575  // we know they cannot alias.
8576  if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
8577    return false;
8578
8579  // If we know required SrcValue1 and SrcValue2 have relatively large alignment
8580  // compared to the size and offset of the access, we may be able to prove they
8581  // do not alias.  This check is conservative for now to catch cases created by
8582  // splitting vector types.
8583  if ((SrcValueAlign1 == SrcValueAlign2) &&
8584      (SrcValueOffset1 != SrcValueOffset2) &&
8585      (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
8586    int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
8587    int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
8588
8589    // There is no overlap between these relatively aligned accesses of similar
8590    // size, return no alias.
8591    if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
8592      return false;
8593  }
8594
8595  if (CombinerGlobalAA) {
8596    // Use alias analysis information.
8597    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
8598    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
8599    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
8600    AliasAnalysis::AliasResult AAResult =
8601      AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
8602               AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
8603    if (AAResult == AliasAnalysis::NoAlias)
8604      return false;
8605  }
8606
8607  // Otherwise we have to assume they alias.
8608  return true;
8609}
8610
8611/// FindAliasInfo - Extracts the relevant alias information from the memory
8612/// node.  Returns true if the operand was a load.
8613bool DAGCombiner::FindAliasInfo(SDNode *N,
8614                                SDValue &Ptr, int64_t &Size,
8615                                const Value *&SrcValue,
8616                                int &SrcValueOffset,
8617                                unsigned &SrcValueAlign,
8618                                const MDNode *&TBAAInfo) const {
8619  LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
8620
8621  Ptr = LS->getBasePtr();
8622  Size = LS->getMemoryVT().getSizeInBits() >> 3;
8623  SrcValue = LS->getSrcValue();
8624  SrcValueOffset = LS->getSrcValueOffset();
8625  SrcValueAlign = LS->getOriginalAlignment();
8626  TBAAInfo = LS->getTBAAInfo();
8627  return isa<LoadSDNode>(LS);
8628}
8629
8630/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
8631/// looking for aliasing nodes and adding them to the Aliases vector.
8632void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
8633                                   SmallVector<SDValue, 8> &Aliases) {
8634  SmallVector<SDValue, 8> Chains;     // List of chains to visit.
8635  SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
8636
8637  // Get alias information for node.
8638  SDValue Ptr;
8639  int64_t Size;
8640  const Value *SrcValue;
8641  int SrcValueOffset;
8642  unsigned SrcValueAlign;
8643  const MDNode *SrcTBAAInfo;
8644  bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
8645                              SrcValueAlign, SrcTBAAInfo);
8646
8647  // Starting off.
8648  Chains.push_back(OriginalChain);
8649  unsigned Depth = 0;
8650
8651  // Look at each chain and determine if it is an alias.  If so, add it to the
8652  // aliases list.  If not, then continue up the chain looking for the next
8653  // candidate.
8654  while (!Chains.empty()) {
8655    SDValue Chain = Chains.back();
8656    Chains.pop_back();
8657
8658    // For TokenFactor nodes, look at each operand and only continue up the
8659    // chain until we find two aliases.  If we've seen two aliases, assume we'll
8660    // find more and revert to original chain since the xform is unlikely to be
8661    // profitable.
8662    //
8663    // FIXME: The depth check could be made to return the last non-aliasing
8664    // chain we found before we hit a tokenfactor rather than the original
8665    // chain.
8666    if (Depth > 6 || Aliases.size() == 2) {
8667      Aliases.clear();
8668      Aliases.push_back(OriginalChain);
8669      break;
8670    }
8671
8672    // Don't bother if we've been before.
8673    if (!Visited.insert(Chain.getNode()))
8674      continue;
8675
8676    switch (Chain.getOpcode()) {
8677    case ISD::EntryToken:
8678      // Entry token is ideal chain operand, but handled in FindBetterChain.
8679      break;
8680
8681    case ISD::LOAD:
8682    case ISD::STORE: {
8683      // Get alias information for Chain.
8684      SDValue OpPtr;
8685      int64_t OpSize;
8686      const Value *OpSrcValue;
8687      int OpSrcValueOffset;
8688      unsigned OpSrcValueAlign;
8689      const MDNode *OpSrcTBAAInfo;
8690      bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
8691                                    OpSrcValue, OpSrcValueOffset,
8692                                    OpSrcValueAlign,
8693                                    OpSrcTBAAInfo);
8694
8695      // If chain is alias then stop here.
8696      if (!(IsLoad && IsOpLoad) &&
8697          isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
8698                  SrcTBAAInfo,
8699                  OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
8700                  OpSrcValueAlign, OpSrcTBAAInfo)) {
8701        Aliases.push_back(Chain);
8702      } else {
8703        // Look further up the chain.
8704        Chains.push_back(Chain.getOperand(0));
8705        ++Depth;
8706      }
8707      break;
8708    }
8709
8710    case ISD::TokenFactor:
8711      // We have to check each of the operands of the token factor for "small"
8712      // token factors, so we queue them up.  Adding the operands to the queue
8713      // (stack) in reverse order maintains the original order and increases the
8714      // likelihood that getNode will find a matching token factor (CSE.)
8715      if (Chain.getNumOperands() > 16) {
8716        Aliases.push_back(Chain);
8717        break;
8718      }
8719      for (unsigned n = Chain.getNumOperands(); n;)
8720        Chains.push_back(Chain.getOperand(--n));
8721      ++Depth;
8722      break;
8723
8724    default:
8725      // For all other instructions we will just have to take what we can get.
8726      Aliases.push_back(Chain);
8727      break;
8728    }
8729  }
8730}
8731
8732/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
8733/// for a better chain (aliasing node.)
8734SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
8735  SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
8736
8737  // Accumulate all the aliases to this node.
8738  GatherAllAliases(N, OldChain, Aliases);
8739
8740  // If no operands then chain to entry token.
8741  if (Aliases.size() == 0)
8742    return DAG.getEntryNode();
8743
8744  // If a single operand then chain to it.  We don't need to revisit it.
8745  if (Aliases.size() == 1)
8746    return Aliases[0];
8747
8748  // Construct a custom tailored token factor.
8749  return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8750                     &Aliases[0], Aliases.size());
8751}
8752
8753// SelectionDAG::Combine - This is the entry point for the file.
8754//
8755void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
8756                           CodeGenOpt::Level OptLevel) {
8757  /// run - This is the main entry point to this class.
8758  ///
8759  DAGCombiner(*this, AA, OptLevel).Run(Level);
8760}
8761