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