a01d5636dfe8d50b2b6063837bd4a5e9f7a3d45d
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Turn on alias analysis during testing"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Include global information in alias analysis"));
58
59   /// Hidden option to stress test load slicing, i.e., when this option
60   /// is enabled, load slicing bypasses most of its profitability guards.
61   static cl::opt<bool>
62   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63                     cl::desc("Bypass the profitability model of load "
64                              "slicing"),
65                     cl::init(false));
66
67 //------------------------------ DAGCombiner ---------------------------------//
68
69   class DAGCombiner {
70     SelectionDAG &DAG;
71     const TargetLowering &TLI;
72     CombineLevel Level;
73     CodeGenOpt::Level OptLevel;
74     bool LegalOperations;
75     bool LegalTypes;
76     bool ForCodeSize;
77
78     // Worklist of all of the nodes that need to be simplified.
79     //
80     // This has the semantics that when adding to the worklist,
81     // the item added must be next to be processed. It should
82     // also only appear once. The naive approach to this takes
83     // linear time.
84     //
85     // To reduce the insert/remove time to logarithmic, we use
86     // a set and a vector to maintain our worklist.
87     //
88     // The set contains the items on the worklist, but does not
89     // maintain the order they should be visited.
90     //
91     // The vector maintains the order nodes should be visited, but may
92     // contain duplicate or removed nodes. When choosing a node to
93     // visit, we pop off the order stack until we find an item that is
94     // also in the contents set. All operations are O(log N).
95     SmallPtrSet<SDNode*, 64> WorkListContents;
96     SmallVector<SDNode*, 64> WorkListOrder;
97
98     // AA - Used for DAG load/store alias analysis.
99     AliasAnalysis &AA;
100
101     /// AddUsersToWorkList - When an instruction is simplified, add all users of
102     /// the instruction to the work lists because they might get more simplified
103     /// now.
104     ///
105     void AddUsersToWorkList(SDNode *N) {
106       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
107            UI != UE; ++UI)
108         AddToWorkList(*UI);
109     }
110
111     /// visit - call the node-specific routine that knows how to fold each
112     /// particular type of node.
113     SDValue visit(SDNode *N);
114
115   public:
116     /// AddToWorkList - Add to the work list making sure its instance is at the
117     /// back (next to be processed.)
118     void AddToWorkList(SDNode *N) {
119       WorkListContents.insert(N);
120       WorkListOrder.push_back(N);
121     }
122
123     /// removeFromWorkList - remove all instances of N from the worklist.
124     ///
125     void removeFromWorkList(SDNode *N) {
126       WorkListContents.erase(N);
127     }
128
129     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
130                       bool AddTo = true);
131
132     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133       return CombineTo(N, &Res, 1, AddTo);
134     }
135
136     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
137                       bool AddTo = true) {
138       SDValue To[] = { Res0, Res1 };
139       return CombineTo(N, To, 2, AddTo);
140     }
141
142     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
143
144   private:
145
146     /// SimplifyDemandedBits - Check the specified integer node value to see if
147     /// it can be simplified or if things it uses can be simplified by bit
148     /// propagation.  If so, return true.
149     bool SimplifyDemandedBits(SDValue Op) {
150       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151       APInt Demanded = APInt::getAllOnesValue(BitWidth);
152       return SimplifyDemandedBits(Op, Demanded);
153     }
154
155     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
156
157     bool CombineToPreIndexedLoadStore(SDNode *N);
158     bool CombineToPostIndexedLoadStore(SDNode *N);
159     bool SliceUpLoad(SDNode *N);
160
161     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165     SDValue PromoteIntBinOp(SDValue Op);
166     SDValue PromoteIntShiftOp(SDValue Op);
167     SDValue PromoteExtend(SDValue Op);
168     bool PromoteLoad(SDValue Op);
169
170     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172                          ISD::NodeType ExtType);
173
174     /// combine - call the node-specific routine that knows how to fold each
175     /// particular type of node. If that doesn't do anything, try the
176     /// target-specific DAG combines.
177     SDValue combine(SDNode *N);
178
179     // Visitation implementation - Implement dag node combining for different
180     // node types.  The semantics are as follows:
181     // Return Value:
182     //   SDValue.getNode() == 0 - No change was made
183     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
184     //   otherwise              - N should be replaced by the returned Operand.
185     //
186     SDValue visitTokenFactor(SDNode *N);
187     SDValue visitMERGE_VALUES(SDNode *N);
188     SDValue visitADD(SDNode *N);
189     SDValue visitSUB(SDNode *N);
190     SDValue visitADDC(SDNode *N);
191     SDValue visitSUBC(SDNode *N);
192     SDValue visitADDE(SDNode *N);
193     SDValue visitSUBE(SDNode *N);
194     SDValue visitMUL(SDNode *N);
195     SDValue visitSDIV(SDNode *N);
196     SDValue visitUDIV(SDNode *N);
197     SDValue visitSREM(SDNode *N);
198     SDValue visitUREM(SDNode *N);
199     SDValue visitMULHU(SDNode *N);
200     SDValue visitMULHS(SDNode *N);
201     SDValue visitSMUL_LOHI(SDNode *N);
202     SDValue visitUMUL_LOHI(SDNode *N);
203     SDValue visitSMULO(SDNode *N);
204     SDValue visitUMULO(SDNode *N);
205     SDValue visitSDIVREM(SDNode *N);
206     SDValue visitUDIVREM(SDNode *N);
207     SDValue visitAND(SDNode *N);
208     SDValue visitOR(SDNode *N);
209     SDValue visitXOR(SDNode *N);
210     SDValue SimplifyVBinOp(SDNode *N);
211     SDValue SimplifyVUnaryOp(SDNode *N);
212     SDValue visitSHL(SDNode *N);
213     SDValue visitSRA(SDNode *N);
214     SDValue visitSRL(SDNode *N);
215     SDValue visitCTLZ(SDNode *N);
216     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217     SDValue visitCTTZ(SDNode *N);
218     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219     SDValue visitCTPOP(SDNode *N);
220     SDValue visitSELECT(SDNode *N);
221     SDValue visitVSELECT(SDNode *N);
222     SDValue visitSELECT_CC(SDNode *N);
223     SDValue visitSETCC(SDNode *N);
224     SDValue visitSIGN_EXTEND(SDNode *N);
225     SDValue visitZERO_EXTEND(SDNode *N);
226     SDValue visitANY_EXTEND(SDNode *N);
227     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228     SDValue visitTRUNCATE(SDNode *N);
229     SDValue visitBITCAST(SDNode *N);
230     SDValue visitBUILD_PAIR(SDNode *N);
231     SDValue visitFADD(SDNode *N);
232     SDValue visitFSUB(SDNode *N);
233     SDValue visitFMUL(SDNode *N);
234     SDValue visitFMA(SDNode *N);
235     SDValue visitFDIV(SDNode *N);
236     SDValue visitFREM(SDNode *N);
237     SDValue visitFCOPYSIGN(SDNode *N);
238     SDValue visitSINT_TO_FP(SDNode *N);
239     SDValue visitUINT_TO_FP(SDNode *N);
240     SDValue visitFP_TO_SINT(SDNode *N);
241     SDValue visitFP_TO_UINT(SDNode *N);
242     SDValue visitFP_ROUND(SDNode *N);
243     SDValue visitFP_ROUND_INREG(SDNode *N);
244     SDValue visitFP_EXTEND(SDNode *N);
245     SDValue visitFNEG(SDNode *N);
246     SDValue visitFABS(SDNode *N);
247     SDValue visitFCEIL(SDNode *N);
248     SDValue visitFTRUNC(SDNode *N);
249     SDValue visitFFLOOR(SDNode *N);
250     SDValue visitBRCOND(SDNode *N);
251     SDValue visitBR_CC(SDNode *N);
252     SDValue visitLOAD(SDNode *N);
253     SDValue visitSTORE(SDNode *N);
254     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256     SDValue visitBUILD_VECTOR(SDNode *N);
257     SDValue visitCONCAT_VECTORS(SDNode *N);
258     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259     SDValue visitVECTOR_SHUFFLE(SDNode *N);
260
261     SDValue XformToShuffleWithZero(SDNode *N);
262     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
263
264     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
265
266     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270                              SDValue N3, ISD::CondCode CC,
271                              bool NotExtCompare = false);
272     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273                           SDLoc DL, bool foldBooleans = true);
274     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
275                                          unsigned HiOp);
276     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278     SDValue BuildSDIV(SDNode *N);
279     SDValue BuildUDIV(SDNode *N);
280     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281                                bool DemandHighBits = true);
282     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
284     SDValue ReduceLoadWidth(SDNode *N);
285     SDValue ReduceLoadOpStoreWidth(SDNode *N);
286     SDValue TransformFPLoadStorePair(SDNode *N);
287     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
288     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
289
290     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
291
292     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
293     /// looking for aliasing nodes and adding them to the Aliases vector.
294     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
295                           SmallVectorImpl<SDValue> &Aliases);
296
297     /// isAlias - Return true if there is any possibility that the two addresses
298     /// overlap.
299     bool isAlias(SDValue Ptr1, int64_t Size1,
300                  const Value *SrcValue1, int SrcValueOffset1,
301                  unsigned SrcValueAlign1,
302                  const MDNode *TBAAInfo1,
303                  SDValue Ptr2, int64_t Size2,
304                  const Value *SrcValue2, int SrcValueOffset2,
305                  unsigned SrcValueAlign2,
306                  const MDNode *TBAAInfo2) const;
307
308     /// isAlias - Return true if there is any possibility that the two addresses
309     /// overlap.
310     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
311
312     /// FindAliasInfo - Extracts the relevant alias information from the memory
313     /// node.  Returns true if the operand was a load.
314     bool FindAliasInfo(SDNode *N,
315                        SDValue &Ptr, int64_t &Size,
316                        const Value *&SrcValue, int &SrcValueOffset,
317                        unsigned &SrcValueAlignment,
318                        const MDNode *&TBAAInfo) const;
319
320     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
321     /// looking for a better chain (aliasing node.)
322     SDValue FindBetterChain(SDNode *N, SDValue Chain);
323
324     /// Merge consecutive store operations into a wide store.
325     /// This optimization uses wide integers or vectors when possible.
326     /// \return True if some memory operations were changed.
327     bool MergeConsecutiveStores(StoreSDNode *N);
328
329   public:
330     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
331         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
332           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
333       AttributeSet FnAttrs =
334           DAG.getMachineFunction().getFunction()->getAttributes();
335       ForCodeSize =
336           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
337                                Attribute::OptimizeForSize) ||
338           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
339     }
340
341     /// Run - runs the dag combiner on all nodes in the work list
342     void Run(CombineLevel AtLevel);
343
344     SelectionDAG &getDAG() const { return DAG; }
345
346     /// getShiftAmountTy - Returns a type large enough to hold any valid
347     /// shift amount - before type legalization these can be huge.
348     EVT getShiftAmountTy(EVT LHSTy) {
349       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
350       if (LHSTy.isVector())
351         return LHSTy;
352       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
353                         : TLI.getPointerTy();
354     }
355
356     /// isTypeLegal - This method returns true if we are running before type
357     /// legalization or if the specified VT is legal.
358     bool isTypeLegal(const EVT &VT) {
359       if (!LegalTypes) return true;
360       return TLI.isTypeLegal(VT);
361     }
362
363     /// getSetCCResultType - Convenience wrapper around
364     /// TargetLowering::getSetCCResultType
365     EVT getSetCCResultType(EVT VT) const {
366       return TLI.getSetCCResultType(*DAG.getContext(), VT);
367     }
368   };
369 }
370
371
372 namespace {
373 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
374 /// nodes from the worklist.
375 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
376   DAGCombiner &DC;
377 public:
378   explicit WorkListRemover(DAGCombiner &dc)
379     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
380
381   virtual void NodeDeleted(SDNode *N, SDNode *E) {
382     DC.removeFromWorkList(N);
383   }
384 };
385 }
386
387 //===----------------------------------------------------------------------===//
388 //  TargetLowering::DAGCombinerInfo implementation
389 //===----------------------------------------------------------------------===//
390
391 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
392   ((DAGCombiner*)DC)->AddToWorkList(N);
393 }
394
395 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
396   ((DAGCombiner*)DC)->removeFromWorkList(N);
397 }
398
399 SDValue TargetLowering::DAGCombinerInfo::
400 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
401   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
402 }
403
404 SDValue TargetLowering::DAGCombinerInfo::
405 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
406   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
407 }
408
409
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
412   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
413 }
414
415 void TargetLowering::DAGCombinerInfo::
416 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
417   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
418 }
419
420 //===----------------------------------------------------------------------===//
421 // Helper Functions
422 //===----------------------------------------------------------------------===//
423
424 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
425 /// specified expression for the same cost as the expression itself, or 2 if we
426 /// can compute the negated form more cheaply than the expression itself.
427 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
428                                const TargetLowering &TLI,
429                                const TargetOptions *Options,
430                                unsigned Depth = 0) {
431   // fneg is removable even if it has multiple uses.
432   if (Op.getOpcode() == ISD::FNEG) return 2;
433
434   // Don't allow anything with multiple uses.
435   if (!Op.hasOneUse()) return 0;
436
437   // Don't recurse exponentially.
438   if (Depth > 6) return 0;
439
440   switch (Op.getOpcode()) {
441   default: return false;
442   case ISD::ConstantFP:
443     // Don't invert constant FP values after legalize.  The negated constant
444     // isn't necessarily legal.
445     return LegalOperations ? 0 : 1;
446   case ISD::FADD:
447     // FIXME: determine better conditions for this xform.
448     if (!Options->UnsafeFPMath) return 0;
449
450     // After operation legalization, it might not be legal to create new FSUBs.
451     if (LegalOperations &&
452         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
453       return 0;
454
455     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
456     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
457                                     Options, Depth + 1))
458       return V;
459     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
460     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
461                               Depth + 1);
462   case ISD::FSUB:
463     // We can't turn -(A-B) into B-A when we honor signed zeros.
464     if (!Options->UnsafeFPMath) return 0;
465
466     // fold (fneg (fsub A, B)) -> (fsub B, A)
467     return 1;
468
469   case ISD::FMUL:
470   case ISD::FDIV:
471     if (Options->HonorSignDependentRoundingFPMath()) return 0;
472
473     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
474     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
475                                     Options, Depth + 1))
476       return V;
477
478     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
479                               Depth + 1);
480
481   case ISD::FP_EXTEND:
482   case ISD::FP_ROUND:
483   case ISD::FSIN:
484     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
485                               Depth + 1);
486   }
487 }
488
489 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
490 /// returns the newly negated expression.
491 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
492                                     bool LegalOperations, unsigned Depth = 0) {
493   // fneg is removable even if it has multiple uses.
494   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
495
496   // Don't allow anything with multiple uses.
497   assert(Op.hasOneUse() && "Unknown reuse!");
498
499   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
500   switch (Op.getOpcode()) {
501   default: llvm_unreachable("Unknown code");
502   case ISD::ConstantFP: {
503     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
504     V.changeSign();
505     return DAG.getConstantFP(V, Op.getValueType());
506   }
507   case ISD::FADD:
508     // FIXME: determine better conditions for this xform.
509     assert(DAG.getTarget().Options.UnsafeFPMath);
510
511     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
512     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513                            DAG.getTargetLoweringInfo(),
514                            &DAG.getTarget().Options, Depth+1))
515       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
516                          GetNegatedExpression(Op.getOperand(0), DAG,
517                                               LegalOperations, Depth+1),
518                          Op.getOperand(1));
519     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
520     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
521                        GetNegatedExpression(Op.getOperand(1), DAG,
522                                             LegalOperations, Depth+1),
523                        Op.getOperand(0));
524   case ISD::FSUB:
525     // We can't turn -(A-B) into B-A when we honor signed zeros.
526     assert(DAG.getTarget().Options.UnsafeFPMath);
527
528     // fold (fneg (fsub 0, B)) -> B
529     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
530       if (N0CFP->getValueAPF().isZero())
531         return Op.getOperand(1);
532
533     // fold (fneg (fsub A, B)) -> (fsub B, A)
534     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
535                        Op.getOperand(1), Op.getOperand(0));
536
537   case ISD::FMUL:
538   case ISD::FDIV:
539     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
540
541     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
542     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                            DAG.getTargetLoweringInfo(),
544                            &DAG.getTarget().Options, Depth+1))
545       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
546                          GetNegatedExpression(Op.getOperand(0), DAG,
547                                               LegalOperations, Depth+1),
548                          Op.getOperand(1));
549
550     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
551     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
552                        Op.getOperand(0),
553                        GetNegatedExpression(Op.getOperand(1), DAG,
554                                             LegalOperations, Depth+1));
555
556   case ISD::FP_EXTEND:
557   case ISD::FSIN:
558     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
559                        GetNegatedExpression(Op.getOperand(0), DAG,
560                                             LegalOperations, Depth+1));
561   case ISD::FP_ROUND:
562       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
563                          GetNegatedExpression(Op.getOperand(0), DAG,
564                                               LegalOperations, Depth+1),
565                          Op.getOperand(1));
566   }
567 }
568
569
570 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
571 // that selects between the values 1 and 0, making it equivalent to a setcc.
572 // Also, set the incoming LHS, RHS, and CC references to the appropriate
573 // nodes based on the type of node we are checking.  This simplifies life a
574 // bit for the callers.
575 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
576                               SDValue &CC) {
577   if (N.getOpcode() == ISD::SETCC) {
578     LHS = N.getOperand(0);
579     RHS = N.getOperand(1);
580     CC  = N.getOperand(2);
581     return true;
582   }
583   if (N.getOpcode() == ISD::SELECT_CC &&
584       N.getOperand(2).getOpcode() == ISD::Constant &&
585       N.getOperand(3).getOpcode() == ISD::Constant &&
586       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
587       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
588     LHS = N.getOperand(0);
589     RHS = N.getOperand(1);
590     CC  = N.getOperand(4);
591     return true;
592   }
593   return false;
594 }
595
596 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
597 // one use.  If this is true, it allows the users to invert the operation for
598 // free when it is profitable to do so.
599 static bool isOneUseSetCC(SDValue N) {
600   SDValue N0, N1, N2;
601   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
602     return true;
603   return false;
604 }
605
606 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
607                                     SDValue N0, SDValue N1) {
608   EVT VT = N0.getValueType();
609   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
610     if (isa<ConstantSDNode>(N1)) {
611       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
612       SDValue OpNode =
613         DAG.FoldConstantArithmetic(Opc, VT,
614                                    cast<ConstantSDNode>(N0.getOperand(1)),
615                                    cast<ConstantSDNode>(N1));
616       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
617     }
618     if (N0.hasOneUse()) {
619       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
620       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
621                                    N0.getOperand(0), N1);
622       AddToWorkList(OpNode.getNode());
623       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
624     }
625   }
626
627   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
628     if (isa<ConstantSDNode>(N0)) {
629       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
630       SDValue OpNode =
631         DAG.FoldConstantArithmetic(Opc, VT,
632                                    cast<ConstantSDNode>(N1.getOperand(1)),
633                                    cast<ConstantSDNode>(N0));
634       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
635     }
636     if (N1.hasOneUse()) {
637       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
638       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
639                                    N1.getOperand(0), N0);
640       AddToWorkList(OpNode.getNode());
641       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
642     }
643   }
644
645   return SDValue();
646 }
647
648 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
649                                bool AddTo) {
650   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
651   ++NodesCombined;
652   DEBUG(dbgs() << "\nReplacing.1 ";
653         N->dump(&DAG);
654         dbgs() << "\nWith: ";
655         To[0].getNode()->dump(&DAG);
656         dbgs() << " and " << NumTo-1 << " other values\n";
657         for (unsigned i = 0, e = NumTo; i != e; ++i)
658           assert((!To[i].getNode() ||
659                   N->getValueType(i) == To[i].getValueType()) &&
660                  "Cannot combine value to value of different type!"));
661   WorkListRemover DeadNodes(*this);
662   DAG.ReplaceAllUsesWith(N, To);
663   if (AddTo) {
664     // Push the new nodes and any users onto the worklist
665     for (unsigned i = 0, e = NumTo; i != e; ++i) {
666       if (To[i].getNode()) {
667         AddToWorkList(To[i].getNode());
668         AddUsersToWorkList(To[i].getNode());
669       }
670     }
671   }
672
673   // Finally, if the node is now dead, remove it from the graph.  The node
674   // may not be dead if the replacement process recursively simplified to
675   // something else needing this node.
676   if (N->use_empty()) {
677     // Nodes can be reintroduced into the worklist.  Make sure we do not
678     // process a node that has been replaced.
679     removeFromWorkList(N);
680
681     // Finally, since the node is now dead, remove it from the graph.
682     DAG.DeleteNode(N);
683   }
684   return SDValue(N, 0);
685 }
686
687 void DAGCombiner::
688 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
689   // Replace all uses.  If any nodes become isomorphic to other nodes and
690   // are deleted, make sure to remove them from our worklist.
691   WorkListRemover DeadNodes(*this);
692   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
693
694   // Push the new node and any (possibly new) users onto the worklist.
695   AddToWorkList(TLO.New.getNode());
696   AddUsersToWorkList(TLO.New.getNode());
697
698   // Finally, if the node is now dead, remove it from the graph.  The node
699   // may not be dead if the replacement process recursively simplified to
700   // something else needing this node.
701   if (TLO.Old.getNode()->use_empty()) {
702     removeFromWorkList(TLO.Old.getNode());
703
704     // If the operands of this node are only used by the node, they will now
705     // be dead.  Make sure to visit them first to delete dead nodes early.
706     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
707       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
708         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
709
710     DAG.DeleteNode(TLO.Old.getNode());
711   }
712 }
713
714 /// SimplifyDemandedBits - Check the specified integer node value to see if
715 /// it can be simplified or if things it uses can be simplified by bit
716 /// propagation.  If so, return true.
717 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
718   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
719   APInt KnownZero, KnownOne;
720   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
721     return false;
722
723   // Revisit the node.
724   AddToWorkList(Op.getNode());
725
726   // Replace the old value with the new one.
727   ++NodesCombined;
728   DEBUG(dbgs() << "\nReplacing.2 ";
729         TLO.Old.getNode()->dump(&DAG);
730         dbgs() << "\nWith: ";
731         TLO.New.getNode()->dump(&DAG);
732         dbgs() << '\n');
733
734   CommitTargetLoweringOpt(TLO);
735   return true;
736 }
737
738 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
739   SDLoc dl(Load);
740   EVT VT = Load->getValueType(0);
741   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
742
743   DEBUG(dbgs() << "\nReplacing.9 ";
744         Load->dump(&DAG);
745         dbgs() << "\nWith: ";
746         Trunc.getNode()->dump(&DAG);
747         dbgs() << '\n');
748   WorkListRemover DeadNodes(*this);
749   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
750   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
751   removeFromWorkList(Load);
752   DAG.DeleteNode(Load);
753   AddToWorkList(Trunc.getNode());
754 }
755
756 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
757   Replace = false;
758   SDLoc dl(Op);
759   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
760     EVT MemVT = LD->getMemoryVT();
761     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
762       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
763                                                   : ISD::EXTLOAD)
764       : LD->getExtensionType();
765     Replace = true;
766     return DAG.getExtLoad(ExtType, dl, PVT,
767                           LD->getChain(), LD->getBasePtr(),
768                           LD->getPointerInfo(),
769                           MemVT, LD->isVolatile(),
770                           LD->isNonTemporal(), LD->getAlignment());
771   }
772
773   unsigned Opc = Op.getOpcode();
774   switch (Opc) {
775   default: break;
776   case ISD::AssertSext:
777     return DAG.getNode(ISD::AssertSext, dl, PVT,
778                        SExtPromoteOperand(Op.getOperand(0), PVT),
779                        Op.getOperand(1));
780   case ISD::AssertZext:
781     return DAG.getNode(ISD::AssertZext, dl, PVT,
782                        ZExtPromoteOperand(Op.getOperand(0), PVT),
783                        Op.getOperand(1));
784   case ISD::Constant: {
785     unsigned ExtOpc =
786       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
787     return DAG.getNode(ExtOpc, dl, PVT, Op);
788   }
789   }
790
791   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
792     return SDValue();
793   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
794 }
795
796 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
797   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
798     return SDValue();
799   EVT OldVT = Op.getValueType();
800   SDLoc dl(Op);
801   bool Replace = false;
802   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
803   if (NewOp.getNode() == 0)
804     return SDValue();
805   AddToWorkList(NewOp.getNode());
806
807   if (Replace)
808     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
809   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
810                      DAG.getValueType(OldVT));
811 }
812
813 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
814   EVT OldVT = Op.getValueType();
815   SDLoc dl(Op);
816   bool Replace = false;
817   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
818   if (NewOp.getNode() == 0)
819     return SDValue();
820   AddToWorkList(NewOp.getNode());
821
822   if (Replace)
823     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
824   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
825 }
826
827 /// PromoteIntBinOp - Promote the specified integer binary operation if the
828 /// target indicates it is beneficial. e.g. On x86, it's usually better to
829 /// promote i16 operations to i32 since i16 instructions are longer.
830 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
831   if (!LegalOperations)
832     return SDValue();
833
834   EVT VT = Op.getValueType();
835   if (VT.isVector() || !VT.isInteger())
836     return SDValue();
837
838   // If operation type is 'undesirable', e.g. i16 on x86, consider
839   // promoting it.
840   unsigned Opc = Op.getOpcode();
841   if (TLI.isTypeDesirableForOp(Opc, VT))
842     return SDValue();
843
844   EVT PVT = VT;
845   // Consult target whether it is a good idea to promote this operation and
846   // what's the right type to promote it to.
847   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
848     assert(PVT != VT && "Don't know what type to promote to!");
849
850     bool Replace0 = false;
851     SDValue N0 = Op.getOperand(0);
852     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
853     if (NN0.getNode() == 0)
854       return SDValue();
855
856     bool Replace1 = false;
857     SDValue N1 = Op.getOperand(1);
858     SDValue NN1;
859     if (N0 == N1)
860       NN1 = NN0;
861     else {
862       NN1 = PromoteOperand(N1, PVT, Replace1);
863       if (NN1.getNode() == 0)
864         return SDValue();
865     }
866
867     AddToWorkList(NN0.getNode());
868     if (NN1.getNode())
869       AddToWorkList(NN1.getNode());
870
871     if (Replace0)
872       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
873     if (Replace1)
874       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
875
876     DEBUG(dbgs() << "\nPromoting ";
877           Op.getNode()->dump(&DAG));
878     SDLoc dl(Op);
879     return DAG.getNode(ISD::TRUNCATE, dl, VT,
880                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
881   }
882   return SDValue();
883 }
884
885 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
886 /// target indicates it is beneficial. e.g. On x86, it's usually better to
887 /// promote i16 operations to i32 since i16 instructions are longer.
888 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
889   if (!LegalOperations)
890     return SDValue();
891
892   EVT VT = Op.getValueType();
893   if (VT.isVector() || !VT.isInteger())
894     return SDValue();
895
896   // If operation type is 'undesirable', e.g. i16 on x86, consider
897   // promoting it.
898   unsigned Opc = Op.getOpcode();
899   if (TLI.isTypeDesirableForOp(Opc, VT))
900     return SDValue();
901
902   EVT PVT = VT;
903   // Consult target whether it is a good idea to promote this operation and
904   // what's the right type to promote it to.
905   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
906     assert(PVT != VT && "Don't know what type to promote to!");
907
908     bool Replace = false;
909     SDValue N0 = Op.getOperand(0);
910     if (Opc == ISD::SRA)
911       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
912     else if (Opc == ISD::SRL)
913       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
914     else
915       N0 = PromoteOperand(N0, PVT, Replace);
916     if (N0.getNode() == 0)
917       return SDValue();
918
919     AddToWorkList(N0.getNode());
920     if (Replace)
921       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
922
923     DEBUG(dbgs() << "\nPromoting ";
924           Op.getNode()->dump(&DAG));
925     SDLoc dl(Op);
926     return DAG.getNode(ISD::TRUNCATE, dl, VT,
927                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
928   }
929   return SDValue();
930 }
931
932 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
933   if (!LegalOperations)
934     return SDValue();
935
936   EVT VT = Op.getValueType();
937   if (VT.isVector() || !VT.isInteger())
938     return SDValue();
939
940   // If operation type is 'undesirable', e.g. i16 on x86, consider
941   // promoting it.
942   unsigned Opc = Op.getOpcode();
943   if (TLI.isTypeDesirableForOp(Opc, VT))
944     return SDValue();
945
946   EVT PVT = VT;
947   // Consult target whether it is a good idea to promote this operation and
948   // what's the right type to promote it to.
949   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950     assert(PVT != VT && "Don't know what type to promote to!");
951     // fold (aext (aext x)) -> (aext x)
952     // fold (aext (zext x)) -> (zext x)
953     // fold (aext (sext x)) -> (sext x)
954     DEBUG(dbgs() << "\nPromoting ";
955           Op.getNode()->dump(&DAG));
956     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
957   }
958   return SDValue();
959 }
960
961 bool DAGCombiner::PromoteLoad(SDValue Op) {
962   if (!LegalOperations)
963     return false;
964
965   EVT VT = Op.getValueType();
966   if (VT.isVector() || !VT.isInteger())
967     return false;
968
969   // If operation type is 'undesirable', e.g. i16 on x86, consider
970   // promoting it.
971   unsigned Opc = Op.getOpcode();
972   if (TLI.isTypeDesirableForOp(Opc, VT))
973     return false;
974
975   EVT PVT = VT;
976   // Consult target whether it is a good idea to promote this operation and
977   // what's the right type to promote it to.
978   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
979     assert(PVT != VT && "Don't know what type to promote to!");
980
981     SDLoc dl(Op);
982     SDNode *N = Op.getNode();
983     LoadSDNode *LD = cast<LoadSDNode>(N);
984     EVT MemVT = LD->getMemoryVT();
985     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
986       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
987                                                   : ISD::EXTLOAD)
988       : LD->getExtensionType();
989     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
990                                    LD->getChain(), LD->getBasePtr(),
991                                    LD->getPointerInfo(),
992                                    MemVT, LD->isVolatile(),
993                                    LD->isNonTemporal(), LD->getAlignment());
994     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
995
996     DEBUG(dbgs() << "\nPromoting ";
997           N->dump(&DAG);
998           dbgs() << "\nTo: ";
999           Result.getNode()->dump(&DAG);
1000           dbgs() << '\n');
1001     WorkListRemover DeadNodes(*this);
1002     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1003     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1004     removeFromWorkList(N);
1005     DAG.DeleteNode(N);
1006     AddToWorkList(Result.getNode());
1007     return true;
1008   }
1009   return false;
1010 }
1011
1012
1013 //===----------------------------------------------------------------------===//
1014 //  Main DAG Combiner implementation
1015 //===----------------------------------------------------------------------===//
1016
1017 void DAGCombiner::Run(CombineLevel AtLevel) {
1018   // set the instance variables, so that the various visit routines may use it.
1019   Level = AtLevel;
1020   LegalOperations = Level >= AfterLegalizeVectorOps;
1021   LegalTypes = Level >= AfterLegalizeTypes;
1022
1023   // Add all the dag nodes to the worklist.
1024   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1025        E = DAG.allnodes_end(); I != E; ++I)
1026     AddToWorkList(I);
1027
1028   // Create a dummy node (which is not added to allnodes), that adds a reference
1029   // to the root node, preventing it from being deleted, and tracking any
1030   // changes of the root.
1031   HandleSDNode Dummy(DAG.getRoot());
1032
1033   // The root of the dag may dangle to deleted nodes until the dag combiner is
1034   // done.  Set it to null to avoid confusion.
1035   DAG.setRoot(SDValue());
1036
1037   // while the worklist isn't empty, find a node and
1038   // try and combine it.
1039   while (!WorkListContents.empty()) {
1040     SDNode *N;
1041     // The WorkListOrder holds the SDNodes in order, but it may contain
1042     // duplicates.
1043     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1044     // worklist *should* contain, and check the node we want to visit is should
1045     // actually be visited.
1046     do {
1047       N = WorkListOrder.pop_back_val();
1048     } while (!WorkListContents.erase(N));
1049
1050     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1051     // N is deleted from the DAG, since they too may now be dead or may have a
1052     // reduced number of uses, allowing other xforms.
1053     if (N->use_empty() && N != &Dummy) {
1054       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1055         AddToWorkList(N->getOperand(i).getNode());
1056
1057       DAG.DeleteNode(N);
1058       continue;
1059     }
1060
1061     SDValue RV = combine(N);
1062
1063     if (RV.getNode() == 0)
1064       continue;
1065
1066     ++NodesCombined;
1067
1068     // If we get back the same node we passed in, rather than a new node or
1069     // zero, we know that the node must have defined multiple values and
1070     // CombineTo was used.  Since CombineTo takes care of the worklist
1071     // mechanics for us, we have no work to do in this case.
1072     if (RV.getNode() == N)
1073       continue;
1074
1075     assert(N->getOpcode() != ISD::DELETED_NODE &&
1076            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1077            "Node was deleted but visit returned new node!");
1078
1079     DEBUG(dbgs() << "\nReplacing.3 ";
1080           N->dump(&DAG);
1081           dbgs() << "\nWith: ";
1082           RV.getNode()->dump(&DAG);
1083           dbgs() << '\n');
1084
1085     // Transfer debug value.
1086     DAG.TransferDbgValues(SDValue(N, 0), RV);
1087     WorkListRemover DeadNodes(*this);
1088     if (N->getNumValues() == RV.getNode()->getNumValues())
1089       DAG.ReplaceAllUsesWith(N, RV.getNode());
1090     else {
1091       assert(N->getValueType(0) == RV.getValueType() &&
1092              N->getNumValues() == 1 && "Type mismatch");
1093       SDValue OpV = RV;
1094       DAG.ReplaceAllUsesWith(N, &OpV);
1095     }
1096
1097     // Push the new node and any users onto the worklist
1098     AddToWorkList(RV.getNode());
1099     AddUsersToWorkList(RV.getNode());
1100
1101     // Add any uses of the old node to the worklist in case this node is the
1102     // last one that uses them.  They may become dead after this node is
1103     // deleted.
1104     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1105       AddToWorkList(N->getOperand(i).getNode());
1106
1107     // Finally, if the node is now dead, remove it from the graph.  The node
1108     // may not be dead if the replacement process recursively simplified to
1109     // something else needing this node.
1110     if (N->use_empty()) {
1111       // Nodes can be reintroduced into the worklist.  Make sure we do not
1112       // process a node that has been replaced.
1113       removeFromWorkList(N);
1114
1115       // Finally, since the node is now dead, remove it from the graph.
1116       DAG.DeleteNode(N);
1117     }
1118   }
1119
1120   // If the root changed (e.g. it was a dead load, update the root).
1121   DAG.setRoot(Dummy.getValue());
1122   DAG.RemoveDeadNodes();
1123 }
1124
1125 SDValue DAGCombiner::visit(SDNode *N) {
1126   switch (N->getOpcode()) {
1127   default: break;
1128   case ISD::TokenFactor:        return visitTokenFactor(N);
1129   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1130   case ISD::ADD:                return visitADD(N);
1131   case ISD::SUB:                return visitSUB(N);
1132   case ISD::ADDC:               return visitADDC(N);
1133   case ISD::SUBC:               return visitSUBC(N);
1134   case ISD::ADDE:               return visitADDE(N);
1135   case ISD::SUBE:               return visitSUBE(N);
1136   case ISD::MUL:                return visitMUL(N);
1137   case ISD::SDIV:               return visitSDIV(N);
1138   case ISD::UDIV:               return visitUDIV(N);
1139   case ISD::SREM:               return visitSREM(N);
1140   case ISD::UREM:               return visitUREM(N);
1141   case ISD::MULHU:              return visitMULHU(N);
1142   case ISD::MULHS:              return visitMULHS(N);
1143   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1144   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1145   case ISD::SMULO:              return visitSMULO(N);
1146   case ISD::UMULO:              return visitUMULO(N);
1147   case ISD::SDIVREM:            return visitSDIVREM(N);
1148   case ISD::UDIVREM:            return visitUDIVREM(N);
1149   case ISD::AND:                return visitAND(N);
1150   case ISD::OR:                 return visitOR(N);
1151   case ISD::XOR:                return visitXOR(N);
1152   case ISD::SHL:                return visitSHL(N);
1153   case ISD::SRA:                return visitSRA(N);
1154   case ISD::SRL:                return visitSRL(N);
1155   case ISD::CTLZ:               return visitCTLZ(N);
1156   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1157   case ISD::CTTZ:               return visitCTTZ(N);
1158   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1159   case ISD::CTPOP:              return visitCTPOP(N);
1160   case ISD::SELECT:             return visitSELECT(N);
1161   case ISD::VSELECT:            return visitVSELECT(N);
1162   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1163   case ISD::SETCC:              return visitSETCC(N);
1164   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1165   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1166   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1167   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1168   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1169   case ISD::BITCAST:            return visitBITCAST(N);
1170   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1171   case ISD::FADD:               return visitFADD(N);
1172   case ISD::FSUB:               return visitFSUB(N);
1173   case ISD::FMUL:               return visitFMUL(N);
1174   case ISD::FMA:                return visitFMA(N);
1175   case ISD::FDIV:               return visitFDIV(N);
1176   case ISD::FREM:               return visitFREM(N);
1177   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1178   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1179   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1180   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1181   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1182   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1183   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1184   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1185   case ISD::FNEG:               return visitFNEG(N);
1186   case ISD::FABS:               return visitFABS(N);
1187   case ISD::FFLOOR:             return visitFFLOOR(N);
1188   case ISD::FCEIL:              return visitFCEIL(N);
1189   case ISD::FTRUNC:             return visitFTRUNC(N);
1190   case ISD::BRCOND:             return visitBRCOND(N);
1191   case ISD::BR_CC:              return visitBR_CC(N);
1192   case ISD::LOAD:               return visitLOAD(N);
1193   case ISD::STORE:              return visitSTORE(N);
1194   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1195   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1196   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1197   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1198   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1199   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1200   }
1201   return SDValue();
1202 }
1203
1204 SDValue DAGCombiner::combine(SDNode *N) {
1205   SDValue RV = visit(N);
1206
1207   // If nothing happened, try a target-specific DAG combine.
1208   if (RV.getNode() == 0) {
1209     assert(N->getOpcode() != ISD::DELETED_NODE &&
1210            "Node was deleted but visit returned NULL!");
1211
1212     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1213         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1214
1215       // Expose the DAG combiner to the target combiner impls.
1216       TargetLowering::DAGCombinerInfo
1217         DagCombineInfo(DAG, Level, false, this);
1218
1219       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1220     }
1221   }
1222
1223   // If nothing happened still, try promoting the operation.
1224   if (RV.getNode() == 0) {
1225     switch (N->getOpcode()) {
1226     default: break;
1227     case ISD::ADD:
1228     case ISD::SUB:
1229     case ISD::MUL:
1230     case ISD::AND:
1231     case ISD::OR:
1232     case ISD::XOR:
1233       RV = PromoteIntBinOp(SDValue(N, 0));
1234       break;
1235     case ISD::SHL:
1236     case ISD::SRA:
1237     case ISD::SRL:
1238       RV = PromoteIntShiftOp(SDValue(N, 0));
1239       break;
1240     case ISD::SIGN_EXTEND:
1241     case ISD::ZERO_EXTEND:
1242     case ISD::ANY_EXTEND:
1243       RV = PromoteExtend(SDValue(N, 0));
1244       break;
1245     case ISD::LOAD:
1246       if (PromoteLoad(SDValue(N, 0)))
1247         RV = SDValue(N, 0);
1248       break;
1249     }
1250   }
1251
1252   // If N is a commutative binary node, try commuting it to enable more
1253   // sdisel CSE.
1254   if (RV.getNode() == 0 &&
1255       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1256       N->getNumValues() == 1) {
1257     SDValue N0 = N->getOperand(0);
1258     SDValue N1 = N->getOperand(1);
1259
1260     // Constant operands are canonicalized to RHS.
1261     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1262       SDValue Ops[] = { N1, N0 };
1263       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1264                                             Ops, 2);
1265       if (CSENode)
1266         return SDValue(CSENode, 0);
1267     }
1268   }
1269
1270   return RV;
1271 }
1272
1273 /// getInputChainForNode - Given a node, return its input chain if it has one,
1274 /// otherwise return a null sd operand.
1275 static SDValue getInputChainForNode(SDNode *N) {
1276   if (unsigned NumOps = N->getNumOperands()) {
1277     if (N->getOperand(0).getValueType() == MVT::Other)
1278       return N->getOperand(0);
1279     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1280       return N->getOperand(NumOps-1);
1281     for (unsigned i = 1; i < NumOps-1; ++i)
1282       if (N->getOperand(i).getValueType() == MVT::Other)
1283         return N->getOperand(i);
1284   }
1285   return SDValue();
1286 }
1287
1288 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1289   // If N has two operands, where one has an input chain equal to the other,
1290   // the 'other' chain is redundant.
1291   if (N->getNumOperands() == 2) {
1292     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1293       return N->getOperand(0);
1294     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1295       return N->getOperand(1);
1296   }
1297
1298   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1299   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1300   SmallPtrSet<SDNode*, 16> SeenOps;
1301   bool Changed = false;             // If we should replace this token factor.
1302
1303   // Start out with this token factor.
1304   TFs.push_back(N);
1305
1306   // Iterate through token factors.  The TFs grows when new token factors are
1307   // encountered.
1308   for (unsigned i = 0; i < TFs.size(); ++i) {
1309     SDNode *TF = TFs[i];
1310
1311     // Check each of the operands.
1312     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1313       SDValue Op = TF->getOperand(i);
1314
1315       switch (Op.getOpcode()) {
1316       case ISD::EntryToken:
1317         // Entry tokens don't need to be added to the list. They are
1318         // rededundant.
1319         Changed = true;
1320         break;
1321
1322       case ISD::TokenFactor:
1323         if (Op.hasOneUse() &&
1324             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1325           // Queue up for processing.
1326           TFs.push_back(Op.getNode());
1327           // Clean up in case the token factor is removed.
1328           AddToWorkList(Op.getNode());
1329           Changed = true;
1330           break;
1331         }
1332         // Fall thru
1333
1334       default:
1335         // Only add if it isn't already in the list.
1336         if (SeenOps.insert(Op.getNode()))
1337           Ops.push_back(Op);
1338         else
1339           Changed = true;
1340         break;
1341       }
1342     }
1343   }
1344
1345   SDValue Result;
1346
1347   // If we've change things around then replace token factor.
1348   if (Changed) {
1349     if (Ops.empty()) {
1350       // The entry token is the only possible outcome.
1351       Result = DAG.getEntryNode();
1352     } else {
1353       // New and improved token factor.
1354       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1355                            MVT::Other, &Ops[0], Ops.size());
1356     }
1357
1358     // Don't add users to work list.
1359     return CombineTo(N, Result, false);
1360   }
1361
1362   return Result;
1363 }
1364
1365 /// MERGE_VALUES can always be eliminated.
1366 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1367   WorkListRemover DeadNodes(*this);
1368   // Replacing results may cause a different MERGE_VALUES to suddenly
1369   // be CSE'd with N, and carry its uses with it. Iterate until no
1370   // uses remain, to ensure that the node can be safely deleted.
1371   // First add the users of this node to the work list so that they
1372   // can be tried again once they have new operands.
1373   AddUsersToWorkList(N);
1374   do {
1375     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1376       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1377   } while (!N->use_empty());
1378   removeFromWorkList(N);
1379   DAG.DeleteNode(N);
1380   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1381 }
1382
1383 static
1384 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1385                               SelectionDAG &DAG) {
1386   EVT VT = N0.getValueType();
1387   SDValue N00 = N0.getOperand(0);
1388   SDValue N01 = N0.getOperand(1);
1389   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1390
1391   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1392       isa<ConstantSDNode>(N00.getOperand(1))) {
1393     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1394     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1395                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1396                                  N00.getOperand(0), N01),
1397                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1398                                  N00.getOperand(1), N01));
1399     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1400   }
1401
1402   return SDValue();
1403 }
1404
1405 SDValue DAGCombiner::visitADD(SDNode *N) {
1406   SDValue N0 = N->getOperand(0);
1407   SDValue N1 = N->getOperand(1);
1408   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1409   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1410   EVT VT = N0.getValueType();
1411
1412   // fold vector ops
1413   if (VT.isVector()) {
1414     SDValue FoldedVOp = SimplifyVBinOp(N);
1415     if (FoldedVOp.getNode()) return FoldedVOp;
1416
1417     // fold (add x, 0) -> x, vector edition
1418     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1419       return N0;
1420     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1421       return N1;
1422   }
1423
1424   // fold (add x, undef) -> undef
1425   if (N0.getOpcode() == ISD::UNDEF)
1426     return N0;
1427   if (N1.getOpcode() == ISD::UNDEF)
1428     return N1;
1429   // fold (add c1, c2) -> c1+c2
1430   if (N0C && N1C)
1431     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1432   // canonicalize constant to RHS
1433   if (N0C && !N1C)
1434     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1435   // fold (add x, 0) -> x
1436   if (N1C && N1C->isNullValue())
1437     return N0;
1438   // fold (add Sym, c) -> Sym+c
1439   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1440     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1441         GA->getOpcode() == ISD::GlobalAddress)
1442       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1443                                   GA->getOffset() +
1444                                     (uint64_t)N1C->getSExtValue());
1445   // fold ((c1-A)+c2) -> (c1+c2)-A
1446   if (N1C && N0.getOpcode() == ISD::SUB)
1447     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1448       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1449                          DAG.getConstant(N1C->getAPIntValue()+
1450                                          N0C->getAPIntValue(), VT),
1451                          N0.getOperand(1));
1452   // reassociate add
1453   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1454   if (RADD.getNode() != 0)
1455     return RADD;
1456   // fold ((0-A) + B) -> B-A
1457   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1458       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1459     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1460   // fold (A + (0-B)) -> A-B
1461   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1462       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1463     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1464   // fold (A+(B-A)) -> B
1465   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1466     return N1.getOperand(0);
1467   // fold ((B-A)+A) -> B
1468   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1469     return N0.getOperand(0);
1470   // fold (A+(B-(A+C))) to (B-C)
1471   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1472       N0 == N1.getOperand(1).getOperand(0))
1473     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1474                        N1.getOperand(1).getOperand(1));
1475   // fold (A+(B-(C+A))) to (B-C)
1476   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1477       N0 == N1.getOperand(1).getOperand(1))
1478     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1479                        N1.getOperand(1).getOperand(0));
1480   // fold (A+((B-A)+or-C)) to (B+or-C)
1481   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1482       N1.getOperand(0).getOpcode() == ISD::SUB &&
1483       N0 == N1.getOperand(0).getOperand(1))
1484     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1485                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1486
1487   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1488   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1489     SDValue N00 = N0.getOperand(0);
1490     SDValue N01 = N0.getOperand(1);
1491     SDValue N10 = N1.getOperand(0);
1492     SDValue N11 = N1.getOperand(1);
1493
1494     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1495       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1496                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1497                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1498   }
1499
1500   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1501     return SDValue(N, 0);
1502
1503   // fold (a+b) -> (a|b) iff a and b share no bits.
1504   if (VT.isInteger() && !VT.isVector()) {
1505     APInt LHSZero, LHSOne;
1506     APInt RHSZero, RHSOne;
1507     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1508
1509     if (LHSZero.getBoolValue()) {
1510       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1511
1512       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1513       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1514       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1515         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1516     }
1517   }
1518
1519   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1520   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1521     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1522     if (Result.getNode()) return Result;
1523   }
1524   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1525     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1526     if (Result.getNode()) return Result;
1527   }
1528
1529   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1530   if (N1.getOpcode() == ISD::SHL &&
1531       N1.getOperand(0).getOpcode() == ISD::SUB)
1532     if (ConstantSDNode *C =
1533           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1534       if (C->getAPIntValue() == 0)
1535         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1536                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1537                                        N1.getOperand(0).getOperand(1),
1538                                        N1.getOperand(1)));
1539   if (N0.getOpcode() == ISD::SHL &&
1540       N0.getOperand(0).getOpcode() == ISD::SUB)
1541     if (ConstantSDNode *C =
1542           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1543       if (C->getAPIntValue() == 0)
1544         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1545                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1546                                        N0.getOperand(0).getOperand(1),
1547                                        N0.getOperand(1)));
1548
1549   if (N1.getOpcode() == ISD::AND) {
1550     SDValue AndOp0 = N1.getOperand(0);
1551     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1552     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1553     unsigned DestBits = VT.getScalarType().getSizeInBits();
1554
1555     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1556     // and similar xforms where the inner op is either ~0 or 0.
1557     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1558       SDLoc DL(N);
1559       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1560     }
1561   }
1562
1563   // add (sext i1), X -> sub X, (zext i1)
1564   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1565       N0.getOperand(0).getValueType() == MVT::i1 &&
1566       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1567     SDLoc DL(N);
1568     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1569     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1570   }
1571
1572   return SDValue();
1573 }
1574
1575 SDValue DAGCombiner::visitADDC(SDNode *N) {
1576   SDValue N0 = N->getOperand(0);
1577   SDValue N1 = N->getOperand(1);
1578   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1580   EVT VT = N0.getValueType();
1581
1582   // If the flag result is dead, turn this into an ADD.
1583   if (!N->hasAnyUseOfValue(1))
1584     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1585                      DAG.getNode(ISD::CARRY_FALSE,
1586                                  SDLoc(N), MVT::Glue));
1587
1588   // canonicalize constant to RHS.
1589   if (N0C && !N1C)
1590     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1591
1592   // fold (addc x, 0) -> x + no carry out
1593   if (N1C && N1C->isNullValue())
1594     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1595                                         SDLoc(N), MVT::Glue));
1596
1597   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1598   APInt LHSZero, LHSOne;
1599   APInt RHSZero, RHSOne;
1600   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1601
1602   if (LHSZero.getBoolValue()) {
1603     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1604
1605     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1606     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1607     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1608       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1609                        DAG.getNode(ISD::CARRY_FALSE,
1610                                    SDLoc(N), MVT::Glue));
1611   }
1612
1613   return SDValue();
1614 }
1615
1616 SDValue DAGCombiner::visitADDE(SDNode *N) {
1617   SDValue N0 = N->getOperand(0);
1618   SDValue N1 = N->getOperand(1);
1619   SDValue CarryIn = N->getOperand(2);
1620   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1621   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1622
1623   // canonicalize constant to RHS
1624   if (N0C && !N1C)
1625     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1626                        N1, N0, CarryIn);
1627
1628   // fold (adde x, y, false) -> (addc x, y)
1629   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1630     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1631
1632   return SDValue();
1633 }
1634
1635 // Since it may not be valid to emit a fold to zero for vector initializers
1636 // check if we can before folding.
1637 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1638                              SelectionDAG &DAG,
1639                              bool LegalOperations, bool LegalTypes) {
1640   if (!VT.isVector())
1641     return DAG.getConstant(0, VT);
1642   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1643     // Produce a vector of zeros.
1644     EVT ElemTy = VT.getVectorElementType();
1645     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1646                       TargetLowering::TypePromoteInteger)
1647       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1648     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1649            "Type for zero vector elements is not legal");
1650     SDValue El = DAG.getConstant(0, ElemTy);
1651     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1652     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1653       &Ops[0], Ops.size());
1654   }
1655   return SDValue();
1656 }
1657
1658 SDValue DAGCombiner::visitSUB(SDNode *N) {
1659   SDValue N0 = N->getOperand(0);
1660   SDValue N1 = N->getOperand(1);
1661   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1662   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1663   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1664     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1665   EVT VT = N0.getValueType();
1666
1667   // fold vector ops
1668   if (VT.isVector()) {
1669     SDValue FoldedVOp = SimplifyVBinOp(N);
1670     if (FoldedVOp.getNode()) return FoldedVOp;
1671
1672     // fold (sub x, 0) -> x, vector edition
1673     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1674       return N0;
1675   }
1676
1677   // fold (sub x, x) -> 0
1678   // FIXME: Refactor this and xor and other similar operations together.
1679   if (N0 == N1)
1680     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1681   // fold (sub c1, c2) -> c1-c2
1682   if (N0C && N1C)
1683     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1684   // fold (sub x, c) -> (add x, -c)
1685   if (N1C)
1686     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1687                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1688   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1689   if (N0C && N0C->isAllOnesValue())
1690     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1691   // fold A-(A-B) -> B
1692   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1693     return N1.getOperand(1);
1694   // fold (A+B)-A -> B
1695   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1696     return N0.getOperand(1);
1697   // fold (A+B)-B -> A
1698   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1699     return N0.getOperand(0);
1700   // fold C2-(A+C1) -> (C2-C1)-A
1701   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1702     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1703                                    VT);
1704     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1705                        N1.getOperand(0));
1706   }
1707   // fold ((A+(B+or-C))-B) -> A+or-C
1708   if (N0.getOpcode() == ISD::ADD &&
1709       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1710        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1711       N0.getOperand(1).getOperand(0) == N1)
1712     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1713                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1714   // fold ((A+(C+B))-B) -> A+C
1715   if (N0.getOpcode() == ISD::ADD &&
1716       N0.getOperand(1).getOpcode() == ISD::ADD &&
1717       N0.getOperand(1).getOperand(1) == N1)
1718     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1719                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1720   // fold ((A-(B-C))-C) -> A-B
1721   if (N0.getOpcode() == ISD::SUB &&
1722       N0.getOperand(1).getOpcode() == ISD::SUB &&
1723       N0.getOperand(1).getOperand(1) == N1)
1724     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1725                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1726
1727   // If either operand of a sub is undef, the result is undef
1728   if (N0.getOpcode() == ISD::UNDEF)
1729     return N0;
1730   if (N1.getOpcode() == ISD::UNDEF)
1731     return N1;
1732
1733   // If the relocation model supports it, consider symbol offsets.
1734   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1735     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1736       // fold (sub Sym, c) -> Sym-c
1737       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1738         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1739                                     GA->getOffset() -
1740                                       (uint64_t)N1C->getSExtValue());
1741       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1742       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1743         if (GA->getGlobal() == GB->getGlobal())
1744           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1745                                  VT);
1746     }
1747
1748   return SDValue();
1749 }
1750
1751 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1752   SDValue N0 = N->getOperand(0);
1753   SDValue N1 = N->getOperand(1);
1754   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1755   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1756   EVT VT = N0.getValueType();
1757
1758   // If the flag result is dead, turn this into an SUB.
1759   if (!N->hasAnyUseOfValue(1))
1760     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1761                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1762                                  MVT::Glue));
1763
1764   // fold (subc x, x) -> 0 + no borrow
1765   if (N0 == N1)
1766     return CombineTo(N, DAG.getConstant(0, VT),
1767                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1768                                  MVT::Glue));
1769
1770   // fold (subc x, 0) -> x + no borrow
1771   if (N1C && N1C->isNullValue())
1772     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1773                                         MVT::Glue));
1774
1775   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1776   if (N0C && N0C->isAllOnesValue())
1777     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1778                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1779                                  MVT::Glue));
1780
1781   return SDValue();
1782 }
1783
1784 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1785   SDValue N0 = N->getOperand(0);
1786   SDValue N1 = N->getOperand(1);
1787   SDValue CarryIn = N->getOperand(2);
1788
1789   // fold (sube x, y, false) -> (subc x, y)
1790   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1791     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1792
1793   return SDValue();
1794 }
1795
1796 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1797 /// elements are all the same constant or undefined.
1798 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1799   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1800   if (!C)
1801     return false;
1802
1803   APInt SplatUndef;
1804   unsigned SplatBitSize;
1805   bool HasAnyUndefs;
1806   EVT EltVT = N->getValueType(0).getVectorElementType();
1807   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1808                              HasAnyUndefs) &&
1809           EltVT.getSizeInBits() >= SplatBitSize);
1810 }
1811
1812 SDValue DAGCombiner::visitMUL(SDNode *N) {
1813   SDValue N0 = N->getOperand(0);
1814   SDValue N1 = N->getOperand(1);
1815   EVT VT = N0.getValueType();
1816
1817   // fold (mul x, undef) -> 0
1818   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1819     return DAG.getConstant(0, VT);
1820
1821   bool N0IsConst = false;
1822   bool N1IsConst = false;
1823   APInt ConstValue0, ConstValue1;
1824   // fold vector ops
1825   if (VT.isVector()) {
1826     SDValue FoldedVOp = SimplifyVBinOp(N);
1827     if (FoldedVOp.getNode()) return FoldedVOp;
1828
1829     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1830     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1831   } else {
1832     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1833     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1834                             : APInt();
1835     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1836     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1837                             : APInt();
1838   }
1839
1840   // fold (mul c1, c2) -> c1*c2
1841   if (N0IsConst && N1IsConst)
1842     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1843
1844   // canonicalize constant to RHS
1845   if (N0IsConst && !N1IsConst)
1846     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1847   // fold (mul x, 0) -> 0
1848   if (N1IsConst && ConstValue1 == 0)
1849     return N1;
1850   // We require a splat of the entire scalar bit width for non-contiguous
1851   // bit patterns.
1852   bool IsFullSplat =
1853     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1854   // fold (mul x, 1) -> x
1855   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1856     return N0;
1857   // fold (mul x, -1) -> 0-x
1858   if (N1IsConst && ConstValue1.isAllOnesValue())
1859     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1860                        DAG.getConstant(0, VT), N0);
1861   // fold (mul x, (1 << c)) -> x << c
1862   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1863     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1864                        DAG.getConstant(ConstValue1.logBase2(),
1865                                        getShiftAmountTy(N0.getValueType())));
1866   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1867   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1868     unsigned Log2Val = (-ConstValue1).logBase2();
1869     // FIXME: If the input is something that is easily negated (e.g. a
1870     // single-use add), we should put the negate there.
1871     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1872                        DAG.getConstant(0, VT),
1873                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1874                             DAG.getConstant(Log2Val,
1875                                       getShiftAmountTy(N0.getValueType()))));
1876   }
1877
1878   APInt Val;
1879   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1880   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1881       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1882                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1883     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1884                              N1, N0.getOperand(1));
1885     AddToWorkList(C3.getNode());
1886     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1887                        N0.getOperand(0), C3);
1888   }
1889
1890   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1891   // use.
1892   {
1893     SDValue Sh(0,0), Y(0,0);
1894     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1895     if (N0.getOpcode() == ISD::SHL &&
1896         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1897                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1898         N0.getNode()->hasOneUse()) {
1899       Sh = N0; Y = N1;
1900     } else if (N1.getOpcode() == ISD::SHL &&
1901                isa<ConstantSDNode>(N1.getOperand(1)) &&
1902                N1.getNode()->hasOneUse()) {
1903       Sh = N1; Y = N0;
1904     }
1905
1906     if (Sh.getNode()) {
1907       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1908                                 Sh.getOperand(0), Y);
1909       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1910                          Mul, Sh.getOperand(1));
1911     }
1912   }
1913
1914   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1915   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1916       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1917                      isa<ConstantSDNode>(N0.getOperand(1))))
1918     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1919                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1920                                    N0.getOperand(0), N1),
1921                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1922                                    N0.getOperand(1), N1));
1923
1924   // reassociate mul
1925   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1926   if (RMUL.getNode() != 0)
1927     return RMUL;
1928
1929   return SDValue();
1930 }
1931
1932 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1933   SDValue N0 = N->getOperand(0);
1934   SDValue N1 = N->getOperand(1);
1935   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1936   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1937   EVT VT = N->getValueType(0);
1938
1939   // fold vector ops
1940   if (VT.isVector()) {
1941     SDValue FoldedVOp = SimplifyVBinOp(N);
1942     if (FoldedVOp.getNode()) return FoldedVOp;
1943   }
1944
1945   // fold (sdiv c1, c2) -> c1/c2
1946   if (N0C && N1C && !N1C->isNullValue())
1947     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1948   // fold (sdiv X, 1) -> X
1949   if (N1C && N1C->getAPIntValue() == 1LL)
1950     return N0;
1951   // fold (sdiv X, -1) -> 0-X
1952   if (N1C && N1C->isAllOnesValue())
1953     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1954                        DAG.getConstant(0, VT), N0);
1955   // If we know the sign bits of both operands are zero, strength reduce to a
1956   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1957   if (!VT.isVector()) {
1958     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1959       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1960                          N0, N1);
1961   }
1962   // fold (sdiv X, pow2) -> simple ops after legalize
1963   if (N1C && !N1C->isNullValue() &&
1964       (N1C->getAPIntValue().isPowerOf2() ||
1965        (-N1C->getAPIntValue()).isPowerOf2())) {
1966     // If dividing by powers of two is cheap, then don't perform the following
1967     // fold.
1968     if (TLI.isPow2DivCheap())
1969       return SDValue();
1970
1971     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1972
1973     // Splat the sign bit into the register
1974     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1975                               DAG.getConstant(VT.getSizeInBits()-1,
1976                                        getShiftAmountTy(N0.getValueType())));
1977     AddToWorkList(SGN.getNode());
1978
1979     // Add (N0 < 0) ? abs2 - 1 : 0;
1980     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1981                               DAG.getConstant(VT.getSizeInBits() - lg2,
1982                                        getShiftAmountTy(SGN.getValueType())));
1983     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1984     AddToWorkList(SRL.getNode());
1985     AddToWorkList(ADD.getNode());    // Divide by pow2
1986     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1987                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1988
1989     // If we're dividing by a positive value, we're done.  Otherwise, we must
1990     // negate the result.
1991     if (N1C->getAPIntValue().isNonNegative())
1992       return SRA;
1993
1994     AddToWorkList(SRA.getNode());
1995     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1996                        DAG.getConstant(0, VT), SRA);
1997   }
1998
1999   // if integer divide is expensive and we satisfy the requirements, emit an
2000   // alternate sequence.
2001   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2002     SDValue Op = BuildSDIV(N);
2003     if (Op.getNode()) return Op;
2004   }
2005
2006   // undef / X -> 0
2007   if (N0.getOpcode() == ISD::UNDEF)
2008     return DAG.getConstant(0, VT);
2009   // X / undef -> undef
2010   if (N1.getOpcode() == ISD::UNDEF)
2011     return N1;
2012
2013   return SDValue();
2014 }
2015
2016 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2017   SDValue N0 = N->getOperand(0);
2018   SDValue N1 = N->getOperand(1);
2019   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2020   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2021   EVT VT = N->getValueType(0);
2022
2023   // fold vector ops
2024   if (VT.isVector()) {
2025     SDValue FoldedVOp = SimplifyVBinOp(N);
2026     if (FoldedVOp.getNode()) return FoldedVOp;
2027   }
2028
2029   // fold (udiv c1, c2) -> c1/c2
2030   if (N0C && N1C && !N1C->isNullValue())
2031     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2032   // fold (udiv x, (1 << c)) -> x >>u c
2033   if (N1C && N1C->getAPIntValue().isPowerOf2())
2034     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2035                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2036                                        getShiftAmountTy(N0.getValueType())));
2037   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2038   if (N1.getOpcode() == ISD::SHL) {
2039     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2040       if (SHC->getAPIntValue().isPowerOf2()) {
2041         EVT ADDVT = N1.getOperand(1).getValueType();
2042         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2043                                   N1.getOperand(1),
2044                                   DAG.getConstant(SHC->getAPIntValue()
2045                                                                   .logBase2(),
2046                                                   ADDVT));
2047         AddToWorkList(Add.getNode());
2048         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2049       }
2050     }
2051   }
2052   // fold (udiv x, c) -> alternate
2053   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2054     SDValue Op = BuildUDIV(N);
2055     if (Op.getNode()) return Op;
2056   }
2057
2058   // undef / X -> 0
2059   if (N0.getOpcode() == ISD::UNDEF)
2060     return DAG.getConstant(0, VT);
2061   // X / undef -> undef
2062   if (N1.getOpcode() == ISD::UNDEF)
2063     return N1;
2064
2065   return SDValue();
2066 }
2067
2068 SDValue DAGCombiner::visitSREM(SDNode *N) {
2069   SDValue N0 = N->getOperand(0);
2070   SDValue N1 = N->getOperand(1);
2071   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2072   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2073   EVT VT = N->getValueType(0);
2074
2075   // fold (srem c1, c2) -> c1%c2
2076   if (N0C && N1C && !N1C->isNullValue())
2077     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2078   // If we know the sign bits of both operands are zero, strength reduce to a
2079   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2080   if (!VT.isVector()) {
2081     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2082       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2083   }
2084
2085   // If X/C can be simplified by the division-by-constant logic, lower
2086   // X%C to the equivalent of X-X/C*C.
2087   if (N1C && !N1C->isNullValue()) {
2088     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2089     AddToWorkList(Div.getNode());
2090     SDValue OptimizedDiv = combine(Div.getNode());
2091     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2092       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2093                                 OptimizedDiv, N1);
2094       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2095       AddToWorkList(Mul.getNode());
2096       return Sub;
2097     }
2098   }
2099
2100   // undef % X -> 0
2101   if (N0.getOpcode() == ISD::UNDEF)
2102     return DAG.getConstant(0, VT);
2103   // X % undef -> undef
2104   if (N1.getOpcode() == ISD::UNDEF)
2105     return N1;
2106
2107   return SDValue();
2108 }
2109
2110 SDValue DAGCombiner::visitUREM(SDNode *N) {
2111   SDValue N0 = N->getOperand(0);
2112   SDValue N1 = N->getOperand(1);
2113   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2114   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2115   EVT VT = N->getValueType(0);
2116
2117   // fold (urem c1, c2) -> c1%c2
2118   if (N0C && N1C && !N1C->isNullValue())
2119     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2120   // fold (urem x, pow2) -> (and x, pow2-1)
2121   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2122     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2123                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2124   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2125   if (N1.getOpcode() == ISD::SHL) {
2126     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2127       if (SHC->getAPIntValue().isPowerOf2()) {
2128         SDValue Add =
2129           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2130                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2131                                  VT));
2132         AddToWorkList(Add.getNode());
2133         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2134       }
2135     }
2136   }
2137
2138   // If X/C can be simplified by the division-by-constant logic, lower
2139   // X%C to the equivalent of X-X/C*C.
2140   if (N1C && !N1C->isNullValue()) {
2141     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2142     AddToWorkList(Div.getNode());
2143     SDValue OptimizedDiv = combine(Div.getNode());
2144     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2145       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2146                                 OptimizedDiv, N1);
2147       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2148       AddToWorkList(Mul.getNode());
2149       return Sub;
2150     }
2151   }
2152
2153   // undef % X -> 0
2154   if (N0.getOpcode() == ISD::UNDEF)
2155     return DAG.getConstant(0, VT);
2156   // X % undef -> undef
2157   if (N1.getOpcode() == ISD::UNDEF)
2158     return N1;
2159
2160   return SDValue();
2161 }
2162
2163 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2164   SDValue N0 = N->getOperand(0);
2165   SDValue N1 = N->getOperand(1);
2166   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2167   EVT VT = N->getValueType(0);
2168   SDLoc DL(N);
2169
2170   // fold (mulhs x, 0) -> 0
2171   if (N1C && N1C->isNullValue())
2172     return N1;
2173   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2174   if (N1C && N1C->getAPIntValue() == 1)
2175     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2176                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2177                                        getShiftAmountTy(N0.getValueType())));
2178   // fold (mulhs x, undef) -> 0
2179   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2180     return DAG.getConstant(0, VT);
2181
2182   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2183   // plus a shift.
2184   if (VT.isSimple() && !VT.isVector()) {
2185     MVT Simple = VT.getSimpleVT();
2186     unsigned SimpleSize = Simple.getSizeInBits();
2187     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2188     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2189       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2190       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2191       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2192       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2193             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2194       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2195     }
2196   }
2197
2198   return SDValue();
2199 }
2200
2201 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2202   SDValue N0 = N->getOperand(0);
2203   SDValue N1 = N->getOperand(1);
2204   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2205   EVT VT = N->getValueType(0);
2206   SDLoc DL(N);
2207
2208   // fold (mulhu x, 0) -> 0
2209   if (N1C && N1C->isNullValue())
2210     return N1;
2211   // fold (mulhu x, 1) -> 0
2212   if (N1C && N1C->getAPIntValue() == 1)
2213     return DAG.getConstant(0, N0.getValueType());
2214   // fold (mulhu x, undef) -> 0
2215   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2216     return DAG.getConstant(0, VT);
2217
2218   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2219   // plus a shift.
2220   if (VT.isSimple() && !VT.isVector()) {
2221     MVT Simple = VT.getSimpleVT();
2222     unsigned SimpleSize = Simple.getSizeInBits();
2223     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2224     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2225       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2226       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2227       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2228       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2229             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2230       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2231     }
2232   }
2233
2234   return SDValue();
2235 }
2236
2237 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2238 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2239 /// that are being performed. Return true if a simplification was made.
2240 ///
2241 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2242                                                 unsigned HiOp) {
2243   // If the high half is not needed, just compute the low half.
2244   bool HiExists = N->hasAnyUseOfValue(1);
2245   if (!HiExists &&
2246       (!LegalOperations ||
2247        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2248     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2249                               N->op_begin(), N->getNumOperands());
2250     return CombineTo(N, Res, Res);
2251   }
2252
2253   // If the low half is not needed, just compute the high half.
2254   bool LoExists = N->hasAnyUseOfValue(0);
2255   if (!LoExists &&
2256       (!LegalOperations ||
2257        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2258     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2259                               N->op_begin(), N->getNumOperands());
2260     return CombineTo(N, Res, Res);
2261   }
2262
2263   // If both halves are used, return as it is.
2264   if (LoExists && HiExists)
2265     return SDValue();
2266
2267   // If the two computed results can be simplified separately, separate them.
2268   if (LoExists) {
2269     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2270                              N->op_begin(), N->getNumOperands());
2271     AddToWorkList(Lo.getNode());
2272     SDValue LoOpt = combine(Lo.getNode());
2273     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2274         (!LegalOperations ||
2275          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2276       return CombineTo(N, LoOpt, LoOpt);
2277   }
2278
2279   if (HiExists) {
2280     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2281                              N->op_begin(), N->getNumOperands());
2282     AddToWorkList(Hi.getNode());
2283     SDValue HiOpt = combine(Hi.getNode());
2284     if (HiOpt.getNode() && HiOpt != Hi &&
2285         (!LegalOperations ||
2286          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2287       return CombineTo(N, HiOpt, HiOpt);
2288   }
2289
2290   return SDValue();
2291 }
2292
2293 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2294   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2295   if (Res.getNode()) return Res;
2296
2297   EVT VT = N->getValueType(0);
2298   SDLoc DL(N);
2299
2300   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2301   // plus a shift.
2302   if (VT.isSimple() && !VT.isVector()) {
2303     MVT Simple = VT.getSimpleVT();
2304     unsigned SimpleSize = Simple.getSizeInBits();
2305     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2306     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2307       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2308       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2309       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2310       // Compute the high part as N1.
2311       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2312             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2313       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2314       // Compute the low part as N0.
2315       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2316       return CombineTo(N, Lo, Hi);
2317     }
2318   }
2319
2320   return SDValue();
2321 }
2322
2323 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2324   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2325   if (Res.getNode()) return Res;
2326
2327   EVT VT = N->getValueType(0);
2328   SDLoc DL(N);
2329
2330   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2331   // plus a shift.
2332   if (VT.isSimple() && !VT.isVector()) {
2333     MVT Simple = VT.getSimpleVT();
2334     unsigned SimpleSize = Simple.getSizeInBits();
2335     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2336     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2337       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2338       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2339       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2340       // Compute the high part as N1.
2341       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2342             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2343       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2344       // Compute the low part as N0.
2345       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2346       return CombineTo(N, Lo, Hi);
2347     }
2348   }
2349
2350   return SDValue();
2351 }
2352
2353 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2354   // (smulo x, 2) -> (saddo x, x)
2355   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2356     if (C2->getAPIntValue() == 2)
2357       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2358                          N->getOperand(0), N->getOperand(0));
2359
2360   return SDValue();
2361 }
2362
2363 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2364   // (umulo x, 2) -> (uaddo x, x)
2365   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2366     if (C2->getAPIntValue() == 2)
2367       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2368                          N->getOperand(0), N->getOperand(0));
2369
2370   return SDValue();
2371 }
2372
2373 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2374   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2375   if (Res.getNode()) return Res;
2376
2377   return SDValue();
2378 }
2379
2380 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2381   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2382   if (Res.getNode()) return Res;
2383
2384   return SDValue();
2385 }
2386
2387 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2388 /// two operands of the same opcode, try to simplify it.
2389 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2390   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2391   EVT VT = N0.getValueType();
2392   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2393
2394   // Bail early if none of these transforms apply.
2395   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2396
2397   // For each of OP in AND/OR/XOR:
2398   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2399   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2400   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2401   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2402   //
2403   // do not sink logical op inside of a vector extend, since it may combine
2404   // into a vsetcc.
2405   EVT Op0VT = N0.getOperand(0).getValueType();
2406   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2407        N0.getOpcode() == ISD::SIGN_EXTEND ||
2408        // Avoid infinite looping with PromoteIntBinOp.
2409        (N0.getOpcode() == ISD::ANY_EXTEND &&
2410         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2411        (N0.getOpcode() == ISD::TRUNCATE &&
2412         (!TLI.isZExtFree(VT, Op0VT) ||
2413          !TLI.isTruncateFree(Op0VT, VT)) &&
2414         TLI.isTypeLegal(Op0VT))) &&
2415       !VT.isVector() &&
2416       Op0VT == N1.getOperand(0).getValueType() &&
2417       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2418     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2419                                  N0.getOperand(0).getValueType(),
2420                                  N0.getOperand(0), N1.getOperand(0));
2421     AddToWorkList(ORNode.getNode());
2422     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2423   }
2424
2425   // For each of OP in SHL/SRL/SRA/AND...
2426   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2427   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2428   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2429   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2430        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2431       N0.getOperand(1) == N1.getOperand(1)) {
2432     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2433                                  N0.getOperand(0).getValueType(),
2434                                  N0.getOperand(0), N1.getOperand(0));
2435     AddToWorkList(ORNode.getNode());
2436     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2437                        ORNode, N0.getOperand(1));
2438   }
2439
2440   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2441   // Only perform this optimization after type legalization and before
2442   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2443   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2444   // we don't want to undo this promotion.
2445   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2446   // on scalars.
2447   if ((N0.getOpcode() == ISD::BITCAST ||
2448        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2449       Level == AfterLegalizeTypes) {
2450     SDValue In0 = N0.getOperand(0);
2451     SDValue In1 = N1.getOperand(0);
2452     EVT In0Ty = In0.getValueType();
2453     EVT In1Ty = In1.getValueType();
2454     SDLoc DL(N);
2455     // If both incoming values are integers, and the original types are the
2456     // same.
2457     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2458       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2459       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2460       AddToWorkList(Op.getNode());
2461       return BC;
2462     }
2463   }
2464
2465   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2466   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2467   // If both shuffles use the same mask, and both shuffle within a single
2468   // vector, then it is worthwhile to move the swizzle after the operation.
2469   // The type-legalizer generates this pattern when loading illegal
2470   // vector types from memory. In many cases this allows additional shuffle
2471   // optimizations.
2472   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2473       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2474       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2475     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2476     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2477
2478     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2479            "Inputs to shuffles are not the same type");
2480
2481     unsigned NumElts = VT.getVectorNumElements();
2482
2483     // Check that both shuffles use the same mask. The masks are known to be of
2484     // the same length because the result vector type is the same.
2485     bool SameMask = true;
2486     for (unsigned i = 0; i != NumElts; ++i) {
2487       int Idx0 = SVN0->getMaskElt(i);
2488       int Idx1 = SVN1->getMaskElt(i);
2489       if (Idx0 != Idx1) {
2490         SameMask = false;
2491         break;
2492       }
2493     }
2494
2495     if (SameMask) {
2496       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2497                                N0.getOperand(0), N1.getOperand(0));
2498       AddToWorkList(Op.getNode());
2499       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2500                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2501     }
2502   }
2503
2504   return SDValue();
2505 }
2506
2507 SDValue DAGCombiner::visitAND(SDNode *N) {
2508   SDValue N0 = N->getOperand(0);
2509   SDValue N1 = N->getOperand(1);
2510   SDValue LL, LR, RL, RR, CC0, CC1;
2511   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2512   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2513   EVT VT = N1.getValueType();
2514   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2515
2516   // fold vector ops
2517   if (VT.isVector()) {
2518     SDValue FoldedVOp = SimplifyVBinOp(N);
2519     if (FoldedVOp.getNode()) return FoldedVOp;
2520
2521     // fold (and x, 0) -> 0, vector edition
2522     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2523       return N0;
2524     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2525       return N1;
2526
2527     // fold (and x, -1) -> x, vector edition
2528     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2529       return N1;
2530     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2531       return N0;
2532   }
2533
2534   // fold (and x, undef) -> 0
2535   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2536     return DAG.getConstant(0, VT);
2537   // fold (and c1, c2) -> c1&c2
2538   if (N0C && N1C)
2539     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2540   // canonicalize constant to RHS
2541   if (N0C && !N1C)
2542     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2543   // fold (and x, -1) -> x
2544   if (N1C && N1C->isAllOnesValue())
2545     return N0;
2546   // if (and x, c) is known to be zero, return 0
2547   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2548                                    APInt::getAllOnesValue(BitWidth)))
2549     return DAG.getConstant(0, VT);
2550   // reassociate and
2551   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2552   if (RAND.getNode() != 0)
2553     return RAND;
2554   // fold (and (or x, C), D) -> D if (C & D) == D
2555   if (N1C && N0.getOpcode() == ISD::OR)
2556     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2557       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2558         return N1;
2559   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2560   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2561     SDValue N0Op0 = N0.getOperand(0);
2562     APInt Mask = ~N1C->getAPIntValue();
2563     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2564     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2565       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2566                                  N0.getValueType(), N0Op0);
2567
2568       // Replace uses of the AND with uses of the Zero extend node.
2569       CombineTo(N, Zext);
2570
2571       // We actually want to replace all uses of the any_extend with the
2572       // zero_extend, to avoid duplicating things.  This will later cause this
2573       // AND to be folded.
2574       CombineTo(N0.getNode(), Zext);
2575       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2576     }
2577   }
2578   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2579   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2580   // already be zero by virtue of the width of the base type of the load.
2581   //
2582   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2583   // more cases.
2584   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2585        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2586       N0.getOpcode() == ISD::LOAD) {
2587     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2588                                          N0 : N0.getOperand(0) );
2589
2590     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2591     // This can be a pure constant or a vector splat, in which case we treat the
2592     // vector as a scalar and use the splat value.
2593     APInt Constant = APInt::getNullValue(1);
2594     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2595       Constant = C->getAPIntValue();
2596     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2597       APInt SplatValue, SplatUndef;
2598       unsigned SplatBitSize;
2599       bool HasAnyUndefs;
2600       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2601                                              SplatBitSize, HasAnyUndefs);
2602       if (IsSplat) {
2603         // Undef bits can contribute to a possible optimisation if set, so
2604         // set them.
2605         SplatValue |= SplatUndef;
2606
2607         // The splat value may be something like "0x00FFFFFF", which means 0 for
2608         // the first vector value and FF for the rest, repeating. We need a mask
2609         // that will apply equally to all members of the vector, so AND all the
2610         // lanes of the constant together.
2611         EVT VT = Vector->getValueType(0);
2612         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2613
2614         // If the splat value has been compressed to a bitlength lower
2615         // than the size of the vector lane, we need to re-expand it to
2616         // the lane size.
2617         if (BitWidth > SplatBitSize)
2618           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2619                SplatBitSize < BitWidth;
2620                SplatBitSize = SplatBitSize * 2)
2621             SplatValue |= SplatValue.shl(SplatBitSize);
2622
2623         Constant = APInt::getAllOnesValue(BitWidth);
2624         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2625           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2626       }
2627     }
2628
2629     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2630     // actually legal and isn't going to get expanded, else this is a false
2631     // optimisation.
2632     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2633                                                     Load->getMemoryVT());
2634
2635     // Resize the constant to the same size as the original memory access before
2636     // extension. If it is still the AllOnesValue then this AND is completely
2637     // unneeded.
2638     Constant =
2639       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2640
2641     bool B;
2642     switch (Load->getExtensionType()) {
2643     default: B = false; break;
2644     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2645     case ISD::ZEXTLOAD:
2646     case ISD::NON_EXTLOAD: B = true; break;
2647     }
2648
2649     if (B && Constant.isAllOnesValue()) {
2650       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2651       // preserve semantics once we get rid of the AND.
2652       SDValue NewLoad(Load, 0);
2653       if (Load->getExtensionType() == ISD::EXTLOAD) {
2654         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2655                               Load->getValueType(0), SDLoc(Load),
2656                               Load->getChain(), Load->getBasePtr(),
2657                               Load->getOffset(), Load->getMemoryVT(),
2658                               Load->getMemOperand());
2659         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2660         if (Load->getNumValues() == 3) {
2661           // PRE/POST_INC loads have 3 values.
2662           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2663                            NewLoad.getValue(2) };
2664           CombineTo(Load, To, 3, true);
2665         } else {
2666           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2667         }
2668       }
2669
2670       // Fold the AND away, taking care not to fold to the old load node if we
2671       // replaced it.
2672       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2673
2674       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2675     }
2676   }
2677   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2678   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2679     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2680     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2681
2682     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2683         LL.getValueType().isInteger()) {
2684       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2685       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2686         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2687                                      LR.getValueType(), LL, RL);
2688         AddToWorkList(ORNode.getNode());
2689         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2690       }
2691       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2692       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2693         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2694                                       LR.getValueType(), LL, RL);
2695         AddToWorkList(ANDNode.getNode());
2696         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2697       }
2698       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2699       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2700         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2701                                      LR.getValueType(), LL, RL);
2702         AddToWorkList(ORNode.getNode());
2703         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2704       }
2705     }
2706     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2707     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2708         Op0 == Op1 && LL.getValueType().isInteger() &&
2709       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2710                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2711                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2712                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2713       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2714                                     LL, DAG.getConstant(1, LL.getValueType()));
2715       AddToWorkList(ADDNode.getNode());
2716       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2717                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2718     }
2719     // canonicalize equivalent to ll == rl
2720     if (LL == RR && LR == RL) {
2721       Op1 = ISD::getSetCCSwappedOperands(Op1);
2722       std::swap(RL, RR);
2723     }
2724     if (LL == RL && LR == RR) {
2725       bool isInteger = LL.getValueType().isInteger();
2726       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2727       if (Result != ISD::SETCC_INVALID &&
2728           (!LegalOperations ||
2729            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2730             TLI.isOperationLegal(ISD::SETCC,
2731                             getSetCCResultType(N0.getSimpleValueType())))))
2732         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2733                             LL, LR, Result);
2734     }
2735   }
2736
2737   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2738   if (N0.getOpcode() == N1.getOpcode()) {
2739     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2740     if (Tmp.getNode()) return Tmp;
2741   }
2742
2743   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2744   // fold (and (sra)) -> (and (srl)) when possible.
2745   if (!VT.isVector() &&
2746       SimplifyDemandedBits(SDValue(N, 0)))
2747     return SDValue(N, 0);
2748
2749   // fold (zext_inreg (extload x)) -> (zextload x)
2750   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2751     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2752     EVT MemVT = LN0->getMemoryVT();
2753     // If we zero all the possible extended bits, then we can turn this into
2754     // a zextload if we are running before legalize or the operation is legal.
2755     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2756     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2757                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2758         ((!LegalOperations && !LN0->isVolatile()) ||
2759          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2760       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2761                                        LN0->getChain(), LN0->getBasePtr(),
2762                                        LN0->getPointerInfo(), MemVT,
2763                                        LN0->isVolatile(), LN0->isNonTemporal(),
2764                                        LN0->getAlignment());
2765       AddToWorkList(N);
2766       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2767       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2768     }
2769   }
2770   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2771   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2772       N0.hasOneUse()) {
2773     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2774     EVT MemVT = LN0->getMemoryVT();
2775     // If we zero all the possible extended bits, then we can turn this into
2776     // a zextload if we are running before legalize or the operation is legal.
2777     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2778     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2779                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2780         ((!LegalOperations && !LN0->isVolatile()) ||
2781          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2782       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2783                                        LN0->getChain(),
2784                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2785                                        MemVT,
2786                                        LN0->isVolatile(), LN0->isNonTemporal(),
2787                                        LN0->getAlignment());
2788       AddToWorkList(N);
2789       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2790       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2791     }
2792   }
2793
2794   // fold (and (load x), 255) -> (zextload x, i8)
2795   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2796   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2797   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2798               (N0.getOpcode() == ISD::ANY_EXTEND &&
2799                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2800     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2801     LoadSDNode *LN0 = HasAnyExt
2802       ? cast<LoadSDNode>(N0.getOperand(0))
2803       : cast<LoadSDNode>(N0);
2804     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2805         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2806       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2807       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2808         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2809         EVT LoadedVT = LN0->getMemoryVT();
2810
2811         if (ExtVT == LoadedVT &&
2812             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2814
2815           SDValue NewLoad =
2816             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2817                            LN0->getChain(), LN0->getBasePtr(),
2818                            LN0->getPointerInfo(),
2819                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2820                            LN0->getAlignment());
2821           AddToWorkList(N);
2822           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2823           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2824         }
2825
2826         // Do not change the width of a volatile load.
2827         // Do not generate loads of non-round integer types since these can
2828         // be expensive (and would be wrong if the type is not byte sized).
2829         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2830             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2831           EVT PtrType = LN0->getOperand(1).getValueType();
2832
2833           unsigned Alignment = LN0->getAlignment();
2834           SDValue NewPtr = LN0->getBasePtr();
2835
2836           // For big endian targets, we need to add an offset to the pointer
2837           // to load the correct bytes.  For little endian systems, we merely
2838           // need to read fewer bytes from the same pointer.
2839           if (TLI.isBigEndian()) {
2840             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2841             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2842             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2843             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2844                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2845             Alignment = MinAlign(Alignment, PtrOff);
2846           }
2847
2848           AddToWorkList(NewPtr.getNode());
2849
2850           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2851           SDValue Load =
2852             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2853                            LN0->getChain(), NewPtr,
2854                            LN0->getPointerInfo(),
2855                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2856                            Alignment);
2857           AddToWorkList(N);
2858           CombineTo(LN0, Load, Load.getValue(1));
2859           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2860         }
2861       }
2862     }
2863   }
2864
2865   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2866       VT.getSizeInBits() <= 64) {
2867     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2868       APInt ADDC = ADDI->getAPIntValue();
2869       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2870         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2871         // immediate for an add, but it is legal if its top c2 bits are set,
2872         // transform the ADD so the immediate doesn't need to be materialized
2873         // in a register.
2874         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2875           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2876                                              SRLI->getZExtValue());
2877           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2878             ADDC |= Mask;
2879             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2880               SDValue NewAdd =
2881                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2882                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2883               CombineTo(N0.getNode(), NewAdd);
2884               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2885             }
2886           }
2887         }
2888       }
2889     }
2890   }
2891
2892   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2893   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2894     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2895                                        N0.getOperand(1), false);
2896     if (BSwap.getNode())
2897       return BSwap;
2898   }
2899
2900   return SDValue();
2901 }
2902
2903 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2904 ///
2905 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2906                                         bool DemandHighBits) {
2907   if (!LegalOperations)
2908     return SDValue();
2909
2910   EVT VT = N->getValueType(0);
2911   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2912     return SDValue();
2913   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2914     return SDValue();
2915
2916   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2917   bool LookPassAnd0 = false;
2918   bool LookPassAnd1 = false;
2919   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2920       std::swap(N0, N1);
2921   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2922       std::swap(N0, N1);
2923   if (N0.getOpcode() == ISD::AND) {
2924     if (!N0.getNode()->hasOneUse())
2925       return SDValue();
2926     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2927     if (!N01C || N01C->getZExtValue() != 0xFF00)
2928       return SDValue();
2929     N0 = N0.getOperand(0);
2930     LookPassAnd0 = true;
2931   }
2932
2933   if (N1.getOpcode() == ISD::AND) {
2934     if (!N1.getNode()->hasOneUse())
2935       return SDValue();
2936     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2937     if (!N11C || N11C->getZExtValue() != 0xFF)
2938       return SDValue();
2939     N1 = N1.getOperand(0);
2940     LookPassAnd1 = true;
2941   }
2942
2943   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2944     std::swap(N0, N1);
2945   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2946     return SDValue();
2947   if (!N0.getNode()->hasOneUse() ||
2948       !N1.getNode()->hasOneUse())
2949     return SDValue();
2950
2951   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2952   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2953   if (!N01C || !N11C)
2954     return SDValue();
2955   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2956     return SDValue();
2957
2958   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2959   SDValue N00 = N0->getOperand(0);
2960   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2961     if (!N00.getNode()->hasOneUse())
2962       return SDValue();
2963     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2964     if (!N001C || N001C->getZExtValue() != 0xFF)
2965       return SDValue();
2966     N00 = N00.getOperand(0);
2967     LookPassAnd0 = true;
2968   }
2969
2970   SDValue N10 = N1->getOperand(0);
2971   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2972     if (!N10.getNode()->hasOneUse())
2973       return SDValue();
2974     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2975     if (!N101C || N101C->getZExtValue() != 0xFF00)
2976       return SDValue();
2977     N10 = N10.getOperand(0);
2978     LookPassAnd1 = true;
2979   }
2980
2981   if (N00 != N10)
2982     return SDValue();
2983
2984   // Make sure everything beyond the low halfword gets set to zero since the SRL
2985   // 16 will clear the top bits.
2986   unsigned OpSizeInBits = VT.getSizeInBits();
2987   if (DemandHighBits && OpSizeInBits > 16) {
2988     // If the left-shift isn't masked out then the only way this is a bswap is
2989     // if all bits beyond the low 8 are 0. In that case the entire pattern
2990     // reduces to a left shift anyway: leave it for other parts of the combiner.
2991     if (!LookPassAnd0)
2992       return SDValue();
2993
2994     // However, if the right shift isn't masked out then it might be because
2995     // it's not needed. See if we can spot that too.
2996     if (!LookPassAnd1 &&
2997         !DAG.MaskedValueIsZero(
2998             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2999       return SDValue();
3000   }
3001
3002   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3003   if (OpSizeInBits > 16)
3004     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3005                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3006   return Res;
3007 }
3008
3009 /// isBSwapHWordElement - Return true if the specified node is an element
3010 /// that makes up a 32-bit packed halfword byteswap. i.e.
3011 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3012 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3013   if (!N.getNode()->hasOneUse())
3014     return false;
3015
3016   unsigned Opc = N.getOpcode();
3017   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3018     return false;
3019
3020   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3021   if (!N1C)
3022     return false;
3023
3024   unsigned Num;
3025   switch (N1C->getZExtValue()) {
3026   default:
3027     return false;
3028   case 0xFF:       Num = 0; break;
3029   case 0xFF00:     Num = 1; break;
3030   case 0xFF0000:   Num = 2; break;
3031   case 0xFF000000: Num = 3; break;
3032   }
3033
3034   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3035   SDValue N0 = N.getOperand(0);
3036   if (Opc == ISD::AND) {
3037     if (Num == 0 || Num == 2) {
3038       // (x >> 8) & 0xff
3039       // (x >> 8) & 0xff0000
3040       if (N0.getOpcode() != ISD::SRL)
3041         return false;
3042       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3043       if (!C || C->getZExtValue() != 8)
3044         return false;
3045     } else {
3046       // (x << 8) & 0xff00
3047       // (x << 8) & 0xff000000
3048       if (N0.getOpcode() != ISD::SHL)
3049         return false;
3050       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3051       if (!C || C->getZExtValue() != 8)
3052         return false;
3053     }
3054   } else if (Opc == ISD::SHL) {
3055     // (x & 0xff) << 8
3056     // (x & 0xff0000) << 8
3057     if (Num != 0 && Num != 2)
3058       return false;
3059     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3060     if (!C || C->getZExtValue() != 8)
3061       return false;
3062   } else { // Opc == ISD::SRL
3063     // (x & 0xff00) >> 8
3064     // (x & 0xff000000) >> 8
3065     if (Num != 1 && Num != 3)
3066       return false;
3067     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3068     if (!C || C->getZExtValue() != 8)
3069       return false;
3070   }
3071
3072   if (Parts[Num])
3073     return false;
3074
3075   Parts[Num] = N0.getOperand(0).getNode();
3076   return true;
3077 }
3078
3079 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3080 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3081 /// => (rotl (bswap x), 16)
3082 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3083   if (!LegalOperations)
3084     return SDValue();
3085
3086   EVT VT = N->getValueType(0);
3087   if (VT != MVT::i32)
3088     return SDValue();
3089   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3090     return SDValue();
3091
3092   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3093   // Look for either
3094   // (or (or (and), (and)), (or (and), (and)))
3095   // (or (or (or (and), (and)), (and)), (and))
3096   if (N0.getOpcode() != ISD::OR)
3097     return SDValue();
3098   SDValue N00 = N0.getOperand(0);
3099   SDValue N01 = N0.getOperand(1);
3100
3101   if (N1.getOpcode() == ISD::OR &&
3102       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3103     // (or (or (and), (and)), (or (and), (and)))
3104     SDValue N000 = N00.getOperand(0);
3105     if (!isBSwapHWordElement(N000, Parts))
3106       return SDValue();
3107
3108     SDValue N001 = N00.getOperand(1);
3109     if (!isBSwapHWordElement(N001, Parts))
3110       return SDValue();
3111     SDValue N010 = N01.getOperand(0);
3112     if (!isBSwapHWordElement(N010, Parts))
3113       return SDValue();
3114     SDValue N011 = N01.getOperand(1);
3115     if (!isBSwapHWordElement(N011, Parts))
3116       return SDValue();
3117   } else {
3118     // (or (or (or (and), (and)), (and)), (and))
3119     if (!isBSwapHWordElement(N1, Parts))
3120       return SDValue();
3121     if (!isBSwapHWordElement(N01, Parts))
3122       return SDValue();
3123     if (N00.getOpcode() != ISD::OR)
3124       return SDValue();
3125     SDValue N000 = N00.getOperand(0);
3126     if (!isBSwapHWordElement(N000, Parts))
3127       return SDValue();
3128     SDValue N001 = N00.getOperand(1);
3129     if (!isBSwapHWordElement(N001, Parts))
3130       return SDValue();
3131   }
3132
3133   // Make sure the parts are all coming from the same node.
3134   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3135     return SDValue();
3136
3137   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3138                               SDValue(Parts[0],0));
3139
3140   // Result of the bswap should be rotated by 16. If it's not legal, then
3141   // do  (x << 16) | (x >> 16).
3142   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3143   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3144     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3145   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3146     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3147   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3148                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3149                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3150 }
3151
3152 SDValue DAGCombiner::visitOR(SDNode *N) {
3153   SDValue N0 = N->getOperand(0);
3154   SDValue N1 = N->getOperand(1);
3155   SDValue LL, LR, RL, RR, CC0, CC1;
3156   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3157   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3158   EVT VT = N1.getValueType();
3159
3160   // fold vector ops
3161   if (VT.isVector()) {
3162     SDValue FoldedVOp = SimplifyVBinOp(N);
3163     if (FoldedVOp.getNode()) return FoldedVOp;
3164
3165     // fold (or x, 0) -> x, vector edition
3166     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3167       return N1;
3168     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3169       return N0;
3170
3171     // fold (or x, -1) -> -1, vector edition
3172     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3173       return N0;
3174     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3175       return N1;
3176   }
3177
3178   // fold (or x, undef) -> -1
3179   if (!LegalOperations &&
3180       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3181     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3182     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3183   }
3184   // fold (or c1, c2) -> c1|c2
3185   if (N0C && N1C)
3186     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3187   // canonicalize constant to RHS
3188   if (N0C && !N1C)
3189     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3190   // fold (or x, 0) -> x
3191   if (N1C && N1C->isNullValue())
3192     return N0;
3193   // fold (or x, -1) -> -1
3194   if (N1C && N1C->isAllOnesValue())
3195     return N1;
3196   // fold (or x, c) -> c iff (x & ~c) == 0
3197   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3198     return N1;
3199
3200   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3201   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3202   if (BSwap.getNode() != 0)
3203     return BSwap;
3204   BSwap = MatchBSwapHWordLow(N, N0, N1);
3205   if (BSwap.getNode() != 0)
3206     return BSwap;
3207
3208   // reassociate or
3209   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3210   if (ROR.getNode() != 0)
3211     return ROR;
3212   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3213   // iff (c1 & c2) == 0.
3214   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3215              isa<ConstantSDNode>(N0.getOperand(1))) {
3216     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3217     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3218       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3219                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3220                                      N0.getOperand(0), N1),
3221                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3222   }
3223   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3224   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3225     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3226     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3227
3228     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3229         LL.getValueType().isInteger()) {
3230       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3231       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3232       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3233           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3234         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3235                                      LR.getValueType(), LL, RL);
3236         AddToWorkList(ORNode.getNode());
3237         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3238       }
3239       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3240       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3241       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3242           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3243         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3244                                       LR.getValueType(), LL, RL);
3245         AddToWorkList(ANDNode.getNode());
3246         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3247       }
3248     }
3249     // canonicalize equivalent to ll == rl
3250     if (LL == RR && LR == RL) {
3251       Op1 = ISD::getSetCCSwappedOperands(Op1);
3252       std::swap(RL, RR);
3253     }
3254     if (LL == RL && LR == RR) {
3255       bool isInteger = LL.getValueType().isInteger();
3256       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3257       if (Result != ISD::SETCC_INVALID &&
3258           (!LegalOperations ||
3259            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3260             TLI.isOperationLegal(ISD::SETCC,
3261               getSetCCResultType(N0.getValueType())))))
3262         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3263                             LL, LR, Result);
3264     }
3265   }
3266
3267   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3268   if (N0.getOpcode() == N1.getOpcode()) {
3269     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3270     if (Tmp.getNode()) return Tmp;
3271   }
3272
3273   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3274   if (N0.getOpcode() == ISD::AND &&
3275       N1.getOpcode() == ISD::AND &&
3276       N0.getOperand(1).getOpcode() == ISD::Constant &&
3277       N1.getOperand(1).getOpcode() == ISD::Constant &&
3278       // Don't increase # computations.
3279       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3280     // We can only do this xform if we know that bits from X that are set in C2
3281     // but not in C1 are already zero.  Likewise for Y.
3282     const APInt &LHSMask =
3283       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3284     const APInt &RHSMask =
3285       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3286
3287     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3288         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3289       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3290                               N0.getOperand(0), N1.getOperand(0));
3291       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3292                          DAG.getConstant(LHSMask | RHSMask, VT));
3293     }
3294   }
3295
3296   // See if this is some rotate idiom.
3297   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3298     return SDValue(Rot, 0);
3299
3300   // Simplify the operands using demanded-bits information.
3301   if (!VT.isVector() &&
3302       SimplifyDemandedBits(SDValue(N, 0)))
3303     return SDValue(N, 0);
3304
3305   return SDValue();
3306 }
3307
3308 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3309 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3310   if (Op.getOpcode() == ISD::AND) {
3311     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3312       Mask = Op.getOperand(1);
3313       Op = Op.getOperand(0);
3314     } else {
3315       return false;
3316     }
3317   }
3318
3319   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3320     Shift = Op;
3321     return true;
3322   }
3323
3324   return false;
3325 }
3326
3327 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3328 // idioms for rotate, and if the target supports rotation instructions, generate
3329 // a rot[lr].
3330 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3331   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3332   EVT VT = LHS.getValueType();
3333   if (!TLI.isTypeLegal(VT)) return 0;
3334
3335   // The target must have at least one rotate flavor.
3336   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3337   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3338   if (!HasROTL && !HasROTR) return 0;
3339
3340   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3341   SDValue LHSShift;   // The shift.
3342   SDValue LHSMask;    // AND value if any.
3343   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3344     return 0; // Not part of a rotate.
3345
3346   SDValue RHSShift;   // The shift.
3347   SDValue RHSMask;    // AND value if any.
3348   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3349     return 0; // Not part of a rotate.
3350
3351   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3352     return 0;   // Not shifting the same value.
3353
3354   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3355     return 0;   // Shifts must disagree.
3356
3357   // Canonicalize shl to left side in a shl/srl pair.
3358   if (RHSShift.getOpcode() == ISD::SHL) {
3359     std::swap(LHS, RHS);
3360     std::swap(LHSShift, RHSShift);
3361     std::swap(LHSMask , RHSMask );
3362   }
3363
3364   unsigned OpSizeInBits = VT.getSizeInBits();
3365   SDValue LHSShiftArg = LHSShift.getOperand(0);
3366   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3367   SDValue RHSShiftArg = RHSShift.getOperand(0);
3368   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3369
3370   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3371   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3372   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3373       RHSShiftAmt.getOpcode() == ISD::Constant) {
3374     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3375     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3376     if ((LShVal + RShVal) != OpSizeInBits)
3377       return 0;
3378
3379     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3380                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3381
3382     // If there is an AND of either shifted operand, apply it to the result.
3383     if (LHSMask.getNode() || RHSMask.getNode()) {
3384       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3385
3386       if (LHSMask.getNode()) {
3387         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3388         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3389       }
3390       if (RHSMask.getNode()) {
3391         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3392         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3393       }
3394
3395       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3396     }
3397
3398     return Rot.getNode();
3399   }
3400
3401   // If there is a mask here, and we have a variable shift, we can't be sure
3402   // that we're masking out the right stuff.
3403   if (LHSMask.getNode() || RHSMask.getNode())
3404     return 0;
3405
3406   // If the shift amount is sign/zext/any-extended just peel it off.
3407   SDValue LExtOp0 = LHSShiftAmt;
3408   SDValue RExtOp0 = RHSShiftAmt;
3409   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3410        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3411        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3412        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3413       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3414        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3415        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3416        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3417     LExtOp0 = LHSShiftAmt.getOperand(0);
3418     RExtOp0 = RHSShiftAmt.getOperand(0);
3419   }
3420
3421   if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3422     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3423     //   (rotl x, y)
3424     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3425     //   (rotr x, (sub 32, y))
3426     if (ConstantSDNode *SUBC =
3427             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3428       if (SUBC->getAPIntValue() == OpSizeInBits) {
3429         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3430                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3431       } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3432                  LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3433         // fold (or (shl (*ext x), (*ext y)),
3434         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3435         //   (*ext (rotl x, y))
3436         // fold (or (shl (*ext x), (*ext y)),
3437         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3438         //   (*ext (rotr x, (sub 32, y)))
3439         SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3440         EVT LArgVT = LArgExtOp0.getValueType();
3441         bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3442         bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3443         if (HasROTRWithLArg || HasROTLWithLArg) {
3444           if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3445             SDValue V =
3446                 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3447                             LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3448             return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3449           }
3450         }
3451       }
3452     }
3453   } else if (LExtOp0.getOpcode() == ISD::SUB &&
3454              RExtOp0 == LExtOp0.getOperand(1)) {
3455     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3456     //   (rotr x, y)
3457     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3458     //   (rotl x, (sub 32, y))
3459     if (ConstantSDNode *SUBC =
3460             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3461       if (SUBC->getAPIntValue() == OpSizeInBits) {
3462         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3463                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3464       } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3465                  RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3466         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3467         //          (srl (*ext x), (*ext y))) ->
3468         //   (*ext (rotl x, y))
3469         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3470         //          (srl (*ext x), (*ext y))) ->
3471         //   (*ext (rotr x, (sub 32, y)))
3472         SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3473         EVT RArgVT = RArgExtOp0.getValueType();
3474         bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3475         bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3476         if (HasROTRWithRArg || HasROTLWithRArg) {
3477           if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3478             SDValue V =
3479                 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3480                             RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3481             return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3482           }
3483         }
3484       }
3485     }
3486   }
3487
3488   return 0;
3489 }
3490
3491 SDValue DAGCombiner::visitXOR(SDNode *N) {
3492   SDValue N0 = N->getOperand(0);
3493   SDValue N1 = N->getOperand(1);
3494   SDValue LHS, RHS, CC;
3495   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3496   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3497   EVT VT = N0.getValueType();
3498
3499   // fold vector ops
3500   if (VT.isVector()) {
3501     SDValue FoldedVOp = SimplifyVBinOp(N);
3502     if (FoldedVOp.getNode()) return FoldedVOp;
3503
3504     // fold (xor x, 0) -> x, vector edition
3505     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3506       return N1;
3507     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3508       return N0;
3509   }
3510
3511   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3512   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3513     return DAG.getConstant(0, VT);
3514   // fold (xor x, undef) -> undef
3515   if (N0.getOpcode() == ISD::UNDEF)
3516     return N0;
3517   if (N1.getOpcode() == ISD::UNDEF)
3518     return N1;
3519   // fold (xor c1, c2) -> c1^c2
3520   if (N0C && N1C)
3521     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3522   // canonicalize constant to RHS
3523   if (N0C && !N1C)
3524     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3525   // fold (xor x, 0) -> x
3526   if (N1C && N1C->isNullValue())
3527     return N0;
3528   // reassociate xor
3529   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3530   if (RXOR.getNode() != 0)
3531     return RXOR;
3532
3533   // fold !(x cc y) -> (x !cc y)
3534   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3535     bool isInt = LHS.getValueType().isInteger();
3536     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3537                                                isInt);
3538
3539     if (!LegalOperations ||
3540         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3541       switch (N0.getOpcode()) {
3542       default:
3543         llvm_unreachable("Unhandled SetCC Equivalent!");
3544       case ISD::SETCC:
3545         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3546       case ISD::SELECT_CC:
3547         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3548                                N0.getOperand(3), NotCC);
3549       }
3550     }
3551   }
3552
3553   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3554   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3555       N0.getNode()->hasOneUse() &&
3556       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3557     SDValue V = N0.getOperand(0);
3558     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3559                     DAG.getConstant(1, V.getValueType()));
3560     AddToWorkList(V.getNode());
3561     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3562   }
3563
3564   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3565   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3566       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3567     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3568     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3569       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3570       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3571       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3572       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3573       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3574     }
3575   }
3576   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3577   if (N1C && N1C->isAllOnesValue() &&
3578       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3579     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3580     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3581       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3582       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3583       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3584       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3585       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3586     }
3587   }
3588   // fold (xor (and x, y), y) -> (and (not x), y)
3589   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3590       N0->getOperand(1) == N1 && isTypeLegal(VT.getScalarType())) {
3591     SDValue X = N0->getOperand(0);
3592     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3593     AddToWorkList(NotX.getNode());
3594     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3595   }
3596   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3597   if (N1C && N0.getOpcode() == ISD::XOR) {
3598     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3599     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3600     if (N00C)
3601       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3602                          DAG.getConstant(N1C->getAPIntValue() ^
3603                                          N00C->getAPIntValue(), VT));
3604     if (N01C)
3605       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3606                          DAG.getConstant(N1C->getAPIntValue() ^
3607                                          N01C->getAPIntValue(), VT));
3608   }
3609   // fold (xor x, x) -> 0
3610   if (N0 == N1)
3611     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3612
3613   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3614   if (N0.getOpcode() == N1.getOpcode()) {
3615     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3616     if (Tmp.getNode()) return Tmp;
3617   }
3618
3619   // Simplify the expression using non-local knowledge.
3620   if (!VT.isVector() &&
3621       SimplifyDemandedBits(SDValue(N, 0)))
3622     return SDValue(N, 0);
3623
3624   return SDValue();
3625 }
3626
3627 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3628 /// the shift amount is a constant.
3629 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3630   SDNode *LHS = N->getOperand(0).getNode();
3631   if (!LHS->hasOneUse()) return SDValue();
3632
3633   // We want to pull some binops through shifts, so that we have (and (shift))
3634   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3635   // thing happens with address calculations, so it's important to canonicalize
3636   // it.
3637   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3638
3639   switch (LHS->getOpcode()) {
3640   default: return SDValue();
3641   case ISD::OR:
3642   case ISD::XOR:
3643     HighBitSet = false; // We can only transform sra if the high bit is clear.
3644     break;
3645   case ISD::AND:
3646     HighBitSet = true;  // We can only transform sra if the high bit is set.
3647     break;
3648   case ISD::ADD:
3649     if (N->getOpcode() != ISD::SHL)
3650       return SDValue(); // only shl(add) not sr[al](add).
3651     HighBitSet = false; // We can only transform sra if the high bit is clear.
3652     break;
3653   }
3654
3655   // We require the RHS of the binop to be a constant as well.
3656   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3657   if (!BinOpCst) return SDValue();
3658
3659   // FIXME: disable this unless the input to the binop is a shift by a constant.
3660   // If it is not a shift, it pessimizes some common cases like:
3661   //
3662   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3663   //    int bar(int *X, int i) { return X[i & 255]; }
3664   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3665   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3666        BinOpLHSVal->getOpcode() != ISD::SRA &&
3667        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3668       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3669     return SDValue();
3670
3671   EVT VT = N->getValueType(0);
3672
3673   // If this is a signed shift right, and the high bit is modified by the
3674   // logical operation, do not perform the transformation. The highBitSet
3675   // boolean indicates the value of the high bit of the constant which would
3676   // cause it to be modified for this operation.
3677   if (N->getOpcode() == ISD::SRA) {
3678     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3679     if (BinOpRHSSignSet != HighBitSet)
3680       return SDValue();
3681   }
3682
3683   // Fold the constants, shifting the binop RHS by the shift amount.
3684   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3685                                N->getValueType(0),
3686                                LHS->getOperand(1), N->getOperand(1));
3687
3688   // Create the new shift.
3689   SDValue NewShift = DAG.getNode(N->getOpcode(),
3690                                  SDLoc(LHS->getOperand(0)),
3691                                  VT, LHS->getOperand(0), N->getOperand(1));
3692
3693   // Create the new binop.
3694   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3695 }
3696
3697 SDValue DAGCombiner::visitSHL(SDNode *N) {
3698   SDValue N0 = N->getOperand(0);
3699   SDValue N1 = N->getOperand(1);
3700   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3701   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3702   EVT VT = N0.getValueType();
3703   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3704
3705   // fold (shl c1, c2) -> c1<<c2
3706   if (N0C && N1C)
3707     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3708   // fold (shl 0, x) -> 0
3709   if (N0C && N0C->isNullValue())
3710     return N0;
3711   // fold (shl x, c >= size(x)) -> undef
3712   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3713     return DAG.getUNDEF(VT);
3714   // fold (shl x, 0) -> x
3715   if (N1C && N1C->isNullValue())
3716     return N0;
3717   // fold (shl undef, x) -> 0
3718   if (N0.getOpcode() == ISD::UNDEF)
3719     return DAG.getConstant(0, VT);
3720   // if (shl x, c) is known to be zero, return 0
3721   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3722                             APInt::getAllOnesValue(OpSizeInBits)))
3723     return DAG.getConstant(0, VT);
3724   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3725   if (N1.getOpcode() == ISD::TRUNCATE &&
3726       N1.getOperand(0).getOpcode() == ISD::AND &&
3727       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3728     SDValue N101 = N1.getOperand(0).getOperand(1);
3729     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3730       EVT TruncVT = N1.getValueType();
3731       SDValue N100 = N1.getOperand(0).getOperand(0);
3732       APInt TruncC = N101C->getAPIntValue();
3733       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3734       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3735                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3736                                      DAG.getNode(ISD::TRUNCATE,
3737                                                  SDLoc(N),
3738                                                  TruncVT, N100),
3739                                      DAG.getConstant(TruncC, TruncVT)));
3740     }
3741   }
3742
3743   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3744     return SDValue(N, 0);
3745
3746   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3747   if (N1C && N0.getOpcode() == ISD::SHL &&
3748       N0.getOperand(1).getOpcode() == ISD::Constant) {
3749     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3750     uint64_t c2 = N1C->getZExtValue();
3751     if (c1 + c2 >= OpSizeInBits)
3752       return DAG.getConstant(0, VT);
3753     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3754                        DAG.getConstant(c1 + c2, N1.getValueType()));
3755   }
3756
3757   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3758   // For this to be valid, the second form must not preserve any of the bits
3759   // that are shifted out by the inner shift in the first form.  This means
3760   // the outer shift size must be >= the number of bits added by the ext.
3761   // As a corollary, we don't care what kind of ext it is.
3762   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3763               N0.getOpcode() == ISD::ANY_EXTEND ||
3764               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3765       N0.getOperand(0).getOpcode() == ISD::SHL &&
3766       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3767     uint64_t c1 =
3768       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3769     uint64_t c2 = N1C->getZExtValue();
3770     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3771     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3772     if (c2 >= OpSizeInBits - InnerShiftSize) {
3773       if (c1 + c2 >= OpSizeInBits)
3774         return DAG.getConstant(0, VT);
3775       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3776                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3777                                      N0.getOperand(0)->getOperand(0)),
3778                          DAG.getConstant(c1 + c2, N1.getValueType()));
3779     }
3780   }
3781
3782   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3783   // Only fold this if the inner zext has no other uses to avoid increasing
3784   // the total number of instructions.
3785   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3786       N0.getOperand(0).getOpcode() == ISD::SRL &&
3787       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3788     uint64_t c1 =
3789       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3790     if (c1 < VT.getSizeInBits()) {
3791       uint64_t c2 = N1C->getZExtValue();
3792       if (c1 == c2) {
3793         SDValue NewOp0 = N0.getOperand(0);
3794         EVT CountVT = NewOp0.getOperand(1).getValueType();
3795         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3796                                      NewOp0, DAG.getConstant(c2, CountVT));
3797         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3798       }
3799     }
3800   }
3801
3802   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3803   //                               (and (srl x, (sub c1, c2), MASK)
3804   // Only fold this if the inner shift has no other uses -- if it does, folding
3805   // this will increase the total number of instructions.
3806   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3807       N0.getOperand(1).getOpcode() == ISD::Constant) {
3808     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3809     if (c1 < VT.getSizeInBits()) {
3810       uint64_t c2 = N1C->getZExtValue();
3811       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3812                                          VT.getSizeInBits() - c1);
3813       SDValue Shift;
3814       if (c2 > c1) {
3815         Mask = Mask.shl(c2-c1);
3816         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3817                             DAG.getConstant(c2-c1, N1.getValueType()));
3818       } else {
3819         Mask = Mask.lshr(c1-c2);
3820         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3821                             DAG.getConstant(c1-c2, N1.getValueType()));
3822       }
3823       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3824                          DAG.getConstant(Mask, VT));
3825     }
3826   }
3827   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3828   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3829     SDValue HiBitsMask =
3830       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3831                                             VT.getSizeInBits() -
3832                                               N1C->getZExtValue()),
3833                       VT);
3834     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3835                        HiBitsMask);
3836   }
3837
3838   if (N1C) {
3839     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3840     if (NewSHL.getNode())
3841       return NewSHL;
3842   }
3843
3844   return SDValue();
3845 }
3846
3847 SDValue DAGCombiner::visitSRA(SDNode *N) {
3848   SDValue N0 = N->getOperand(0);
3849   SDValue N1 = N->getOperand(1);
3850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3852   EVT VT = N0.getValueType();
3853   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3854
3855   // fold (sra c1, c2) -> (sra c1, c2)
3856   if (N0C && N1C)
3857     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3858   // fold (sra 0, x) -> 0
3859   if (N0C && N0C->isNullValue())
3860     return N0;
3861   // fold (sra -1, x) -> -1
3862   if (N0C && N0C->isAllOnesValue())
3863     return N0;
3864   // fold (sra x, (setge c, size(x))) -> undef
3865   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3866     return DAG.getUNDEF(VT);
3867   // fold (sra x, 0) -> x
3868   if (N1C && N1C->isNullValue())
3869     return N0;
3870   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3871   // sext_inreg.
3872   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3873     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3874     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3875     if (VT.isVector())
3876       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3877                                ExtVT, VT.getVectorNumElements());
3878     if ((!LegalOperations ||
3879          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3880       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3881                          N0.getOperand(0), DAG.getValueType(ExtVT));
3882   }
3883
3884   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3885   if (N1C && N0.getOpcode() == ISD::SRA) {
3886     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3887       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3888       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3889       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3890                          DAG.getConstant(Sum, N1C->getValueType(0)));
3891     }
3892   }
3893
3894   // fold (sra (shl X, m), (sub result_size, n))
3895   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3896   // result_size - n != m.
3897   // If truncate is free for the target sext(shl) is likely to result in better
3898   // code.
3899   if (N0.getOpcode() == ISD::SHL) {
3900     // Get the two constanst of the shifts, CN0 = m, CN = n.
3901     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3902     if (N01C && N1C) {
3903       // Determine what the truncate's result bitsize and type would be.
3904       EVT TruncVT =
3905         EVT::getIntegerVT(*DAG.getContext(),
3906                           OpSizeInBits - N1C->getZExtValue());
3907       // Determine the residual right-shift amount.
3908       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3909
3910       // If the shift is not a no-op (in which case this should be just a sign
3911       // extend already), the truncated to type is legal, sign_extend is legal
3912       // on that type, and the truncate to that type is both legal and free,
3913       // perform the transform.
3914       if ((ShiftAmt > 0) &&
3915           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3916           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3917           TLI.isTruncateFree(VT, TruncVT)) {
3918
3919           SDValue Amt = DAG.getConstant(ShiftAmt,
3920               getShiftAmountTy(N0.getOperand(0).getValueType()));
3921           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3922                                       N0.getOperand(0), Amt);
3923           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3924                                       Shift);
3925           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3926                              N->getValueType(0), Trunc);
3927       }
3928     }
3929   }
3930
3931   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3932   if (N1.getOpcode() == ISD::TRUNCATE &&
3933       N1.getOperand(0).getOpcode() == ISD::AND &&
3934       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3935     SDValue N101 = N1.getOperand(0).getOperand(1);
3936     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3937       EVT TruncVT = N1.getValueType();
3938       SDValue N100 = N1.getOperand(0).getOperand(0);
3939       APInt TruncC = N101C->getAPIntValue();
3940       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3941       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3942                          DAG.getNode(ISD::AND, SDLoc(N),
3943                                      TruncVT,
3944                                      DAG.getNode(ISD::TRUNCATE,
3945                                                  SDLoc(N),
3946                                                  TruncVT, N100),
3947                                      DAG.getConstant(TruncC, TruncVT)));
3948     }
3949   }
3950
3951   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3952   //      if c1 is equal to the number of bits the trunc removes
3953   if (N0.getOpcode() == ISD::TRUNCATE &&
3954       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3955        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3956       N0.getOperand(0).hasOneUse() &&
3957       N0.getOperand(0).getOperand(1).hasOneUse() &&
3958       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3959     EVT LargeVT = N0.getOperand(0).getValueType();
3960     ConstantSDNode *LargeShiftAmt =
3961       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3962
3963     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3964         LargeShiftAmt->getZExtValue()) {
3965       SDValue Amt =
3966         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3967               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3968       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3969                                 N0.getOperand(0).getOperand(0), Amt);
3970       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3971     }
3972   }
3973
3974   // Simplify, based on bits shifted out of the LHS.
3975   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3976     return SDValue(N, 0);
3977
3978
3979   // If the sign bit is known to be zero, switch this to a SRL.
3980   if (DAG.SignBitIsZero(N0))
3981     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3982
3983   if (N1C) {
3984     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3985     if (NewSRA.getNode())
3986       return NewSRA;
3987   }
3988
3989   return SDValue();
3990 }
3991
3992 SDValue DAGCombiner::visitSRL(SDNode *N) {
3993   SDValue N0 = N->getOperand(0);
3994   SDValue N1 = N->getOperand(1);
3995   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3996   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3997   EVT VT = N0.getValueType();
3998   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3999
4000   // fold (srl c1, c2) -> c1 >>u c2
4001   if (N0C && N1C)
4002     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4003   // fold (srl 0, x) -> 0
4004   if (N0C && N0C->isNullValue())
4005     return N0;
4006   // fold (srl x, c >= size(x)) -> undef
4007   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4008     return DAG.getUNDEF(VT);
4009   // fold (srl x, 0) -> x
4010   if (N1C && N1C->isNullValue())
4011     return N0;
4012   // if (srl x, c) is known to be zero, return 0
4013   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4014                                    APInt::getAllOnesValue(OpSizeInBits)))
4015     return DAG.getConstant(0, VT);
4016
4017   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4018   if (N1C && N0.getOpcode() == ISD::SRL &&
4019       N0.getOperand(1).getOpcode() == ISD::Constant) {
4020     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4021     uint64_t c2 = N1C->getZExtValue();
4022     if (c1 + c2 >= OpSizeInBits)
4023       return DAG.getConstant(0, VT);
4024     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4025                        DAG.getConstant(c1 + c2, N1.getValueType()));
4026   }
4027
4028   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4029   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4030       N0.getOperand(0).getOpcode() == ISD::SRL &&
4031       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4032     uint64_t c1 =
4033       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4034     uint64_t c2 = N1C->getZExtValue();
4035     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4036     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4037     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4038     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4039     if (c1 + OpSizeInBits == InnerShiftSize) {
4040       if (c1 + c2 >= InnerShiftSize)
4041         return DAG.getConstant(0, VT);
4042       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4043                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4044                                      N0.getOperand(0)->getOperand(0),
4045                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4046     }
4047   }
4048
4049   // fold (srl (shl x, c), c) -> (and x, cst2)
4050   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4051       N0.getValueSizeInBits() <= 64) {
4052     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4053     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4054                        DAG.getConstant(~0ULL >> ShAmt, VT));
4055   }
4056
4057   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4058   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4059     // Shifting in all undef bits?
4060     EVT SmallVT = N0.getOperand(0).getValueType();
4061     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4062       return DAG.getUNDEF(VT);
4063
4064     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4065       uint64_t ShiftAmt = N1C->getZExtValue();
4066       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4067                                        N0.getOperand(0),
4068                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4069       AddToWorkList(SmallShift.getNode());
4070       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4071       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4072                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4073                          DAG.getConstant(Mask, VT));
4074     }
4075   }
4076
4077   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4078   // bit, which is unmodified by sra.
4079   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4080     if (N0.getOpcode() == ISD::SRA)
4081       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4082   }
4083
4084   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4085   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4086       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4087     APInt KnownZero, KnownOne;
4088     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4089
4090     // If any of the input bits are KnownOne, then the input couldn't be all
4091     // zeros, thus the result of the srl will always be zero.
4092     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4093
4094     // If all of the bits input the to ctlz node are known to be zero, then
4095     // the result of the ctlz is "32" and the result of the shift is one.
4096     APInt UnknownBits = ~KnownZero;
4097     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4098
4099     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4100     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4101       // Okay, we know that only that the single bit specified by UnknownBits
4102       // could be set on input to the CTLZ node. If this bit is set, the SRL
4103       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4104       // to an SRL/XOR pair, which is likely to simplify more.
4105       unsigned ShAmt = UnknownBits.countTrailingZeros();
4106       SDValue Op = N0.getOperand(0);
4107
4108       if (ShAmt) {
4109         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4110                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4111         AddToWorkList(Op.getNode());
4112       }
4113
4114       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4115                          Op, DAG.getConstant(1, VT));
4116     }
4117   }
4118
4119   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4120   if (N1.getOpcode() == ISD::TRUNCATE &&
4121       N1.getOperand(0).getOpcode() == ISD::AND &&
4122       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4123     SDValue N101 = N1.getOperand(0).getOperand(1);
4124     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4125       EVT TruncVT = N1.getValueType();
4126       SDValue N100 = N1.getOperand(0).getOperand(0);
4127       APInt TruncC = N101C->getAPIntValue();
4128       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4129       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4130                          DAG.getNode(ISD::AND, SDLoc(N),
4131                                      TruncVT,
4132                                      DAG.getNode(ISD::TRUNCATE,
4133                                                  SDLoc(N),
4134                                                  TruncVT, N100),
4135                                      DAG.getConstant(TruncC, TruncVT)));
4136     }
4137   }
4138
4139   // fold operands of srl based on knowledge that the low bits are not
4140   // demanded.
4141   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4142     return SDValue(N, 0);
4143
4144   if (N1C) {
4145     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4146     if (NewSRL.getNode())
4147       return NewSRL;
4148   }
4149
4150   // Attempt to convert a srl of a load into a narrower zero-extending load.
4151   SDValue NarrowLoad = ReduceLoadWidth(N);
4152   if (NarrowLoad.getNode())
4153     return NarrowLoad;
4154
4155   // Here is a common situation. We want to optimize:
4156   //
4157   //   %a = ...
4158   //   %b = and i32 %a, 2
4159   //   %c = srl i32 %b, 1
4160   //   brcond i32 %c ...
4161   //
4162   // into
4163   //
4164   //   %a = ...
4165   //   %b = and %a, 2
4166   //   %c = setcc eq %b, 0
4167   //   brcond %c ...
4168   //
4169   // However when after the source operand of SRL is optimized into AND, the SRL
4170   // itself may not be optimized further. Look for it and add the BRCOND into
4171   // the worklist.
4172   if (N->hasOneUse()) {
4173     SDNode *Use = *N->use_begin();
4174     if (Use->getOpcode() == ISD::BRCOND)
4175       AddToWorkList(Use);
4176     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4177       // Also look pass the truncate.
4178       Use = *Use->use_begin();
4179       if (Use->getOpcode() == ISD::BRCOND)
4180         AddToWorkList(Use);
4181     }
4182   }
4183
4184   return SDValue();
4185 }
4186
4187 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4188   SDValue N0 = N->getOperand(0);
4189   EVT VT = N->getValueType(0);
4190
4191   // fold (ctlz c1) -> c2
4192   if (isa<ConstantSDNode>(N0))
4193     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4194   return SDValue();
4195 }
4196
4197 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4198   SDValue N0 = N->getOperand(0);
4199   EVT VT = N->getValueType(0);
4200
4201   // fold (ctlz_zero_undef c1) -> c2
4202   if (isa<ConstantSDNode>(N0))
4203     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4204   return SDValue();
4205 }
4206
4207 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4208   SDValue N0 = N->getOperand(0);
4209   EVT VT = N->getValueType(0);
4210
4211   // fold (cttz c1) -> c2
4212   if (isa<ConstantSDNode>(N0))
4213     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4214   return SDValue();
4215 }
4216
4217 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4218   SDValue N0 = N->getOperand(0);
4219   EVT VT = N->getValueType(0);
4220
4221   // fold (cttz_zero_undef c1) -> c2
4222   if (isa<ConstantSDNode>(N0))
4223     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4224   return SDValue();
4225 }
4226
4227 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4228   SDValue N0 = N->getOperand(0);
4229   EVT VT = N->getValueType(0);
4230
4231   // fold (ctpop c1) -> c2
4232   if (isa<ConstantSDNode>(N0))
4233     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4234   return SDValue();
4235 }
4236
4237 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4238   SDValue N0 = N->getOperand(0);
4239   SDValue N1 = N->getOperand(1);
4240   SDValue N2 = N->getOperand(2);
4241   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4242   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4243   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4244   EVT VT = N->getValueType(0);
4245   EVT VT0 = N0.getValueType();
4246
4247   // fold (select C, X, X) -> X
4248   if (N1 == N2)
4249     return N1;
4250   // fold (select true, X, Y) -> X
4251   if (N0C && !N0C->isNullValue())
4252     return N1;
4253   // fold (select false, X, Y) -> Y
4254   if (N0C && N0C->isNullValue())
4255     return N2;
4256   // fold (select C, 1, X) -> (or C, X)
4257   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4258     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4259   // fold (select C, 0, 1) -> (xor C, 1)
4260   if (VT.isInteger() &&
4261       (VT0 == MVT::i1 ||
4262        (VT0.isInteger() &&
4263         TLI.getBooleanContents(false) ==
4264         TargetLowering::ZeroOrOneBooleanContent)) &&
4265       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4266     SDValue XORNode;
4267     if (VT == VT0)
4268       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4269                          N0, DAG.getConstant(1, VT0));
4270     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4271                           N0, DAG.getConstant(1, VT0));
4272     AddToWorkList(XORNode.getNode());
4273     if (VT.bitsGT(VT0))
4274       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4275     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4276   }
4277   // fold (select C, 0, X) -> (and (not C), X)
4278   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4279     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4280     AddToWorkList(NOTNode.getNode());
4281     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4282   }
4283   // fold (select C, X, 1) -> (or (not C), X)
4284   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4285     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4286     AddToWorkList(NOTNode.getNode());
4287     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4288   }
4289   // fold (select C, X, 0) -> (and C, X)
4290   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4291     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4292   // fold (select X, X, Y) -> (or X, Y)
4293   // fold (select X, 1, Y) -> (or X, Y)
4294   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4295     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4296   // fold (select X, Y, X) -> (and X, Y)
4297   // fold (select X, Y, 0) -> (and X, Y)
4298   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4299     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4300
4301   // If we can fold this based on the true/false value, do so.
4302   if (SimplifySelectOps(N, N1, N2))
4303     return SDValue(N, 0);  // Don't revisit N.
4304
4305   // fold selects based on a setcc into other things, such as min/max/abs
4306   if (N0.getOpcode() == ISD::SETCC) {
4307     // FIXME:
4308     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4309     // having to say they don't support SELECT_CC on every type the DAG knows
4310     // about, since there is no way to mark an opcode illegal at all value types
4311     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4312         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4313       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4314                          N0.getOperand(0), N0.getOperand(1),
4315                          N1, N2, N0.getOperand(2));
4316     return SimplifySelect(SDLoc(N), N0, N1, N2);
4317   }
4318
4319   return SDValue();
4320 }
4321
4322 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4323   SDValue N0 = N->getOperand(0);
4324   SDValue N1 = N->getOperand(1);
4325   SDValue N2 = N->getOperand(2);
4326   SDLoc DL(N);
4327
4328   // Canonicalize integer abs.
4329   // vselect (setg[te] X,  0),  X, -X ->
4330   // vselect (setgt    X, -1),  X, -X ->
4331   // vselect (setl[te] X,  0), -X,  X ->
4332   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4333   if (N0.getOpcode() == ISD::SETCC) {
4334     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4335     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4336     bool isAbs = false;
4337     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4338
4339     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4340          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4341         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4342       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4343     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4344              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4345       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4346
4347     if (isAbs) {
4348       EVT VT = LHS.getValueType();
4349       SDValue Shift = DAG.getNode(
4350           ISD::SRA, DL, VT, LHS,
4351           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4352       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4353       AddToWorkList(Shift.getNode());
4354       AddToWorkList(Add.getNode());
4355       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4356     }
4357   }
4358
4359   return SDValue();
4360 }
4361
4362 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4363   SDValue N0 = N->getOperand(0);
4364   SDValue N1 = N->getOperand(1);
4365   SDValue N2 = N->getOperand(2);
4366   SDValue N3 = N->getOperand(3);
4367   SDValue N4 = N->getOperand(4);
4368   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4369
4370   // fold select_cc lhs, rhs, x, x, cc -> x
4371   if (N2 == N3)
4372     return N2;
4373
4374   // Determine if the condition we're dealing with is constant
4375   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4376                               N0, N1, CC, SDLoc(N), false);
4377   if (SCC.getNode()) {
4378     AddToWorkList(SCC.getNode());
4379
4380     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4381       if (!SCCC->isNullValue())
4382         return N2;    // cond always true -> true val
4383       else
4384         return N3;    // cond always false -> false val
4385     }
4386
4387     // Fold to a simpler select_cc
4388     if (SCC.getOpcode() == ISD::SETCC)
4389       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4390                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4391                          SCC.getOperand(2));
4392   }
4393
4394   // If we can fold this based on the true/false value, do so.
4395   if (SimplifySelectOps(N, N2, N3))
4396     return SDValue(N, 0);  // Don't revisit N.
4397
4398   // fold select_cc into other things, such as min/max/abs
4399   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4400 }
4401
4402 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4403   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4404                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4405                        SDLoc(N));
4406 }
4407
4408 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4409 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4410 // transformation. Returns true if extension are possible and the above
4411 // mentioned transformation is profitable.
4412 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4413                                     unsigned ExtOpc,
4414                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4415                                     const TargetLowering &TLI) {
4416   bool HasCopyToRegUses = false;
4417   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4418   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4419                             UE = N0.getNode()->use_end();
4420        UI != UE; ++UI) {
4421     SDNode *User = *UI;
4422     if (User == N)
4423       continue;
4424     if (UI.getUse().getResNo() != N0.getResNo())
4425       continue;
4426     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4427     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4428       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4429       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4430         // Sign bits will be lost after a zext.
4431         return false;
4432       bool Add = false;
4433       for (unsigned i = 0; i != 2; ++i) {
4434         SDValue UseOp = User->getOperand(i);
4435         if (UseOp == N0)
4436           continue;
4437         if (!isa<ConstantSDNode>(UseOp))
4438           return false;
4439         Add = true;
4440       }
4441       if (Add)
4442         ExtendNodes.push_back(User);
4443       continue;
4444     }
4445     // If truncates aren't free and there are users we can't
4446     // extend, it isn't worthwhile.
4447     if (!isTruncFree)
4448       return false;
4449     // Remember if this value is live-out.
4450     if (User->getOpcode() == ISD::CopyToReg)
4451       HasCopyToRegUses = true;
4452   }
4453
4454   if (HasCopyToRegUses) {
4455     bool BothLiveOut = false;
4456     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4457          UI != UE; ++UI) {
4458       SDUse &Use = UI.getUse();
4459       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4460         BothLiveOut = true;
4461         break;
4462       }
4463     }
4464     if (BothLiveOut)
4465       // Both unextended and extended values are live out. There had better be
4466       // a good reason for the transformation.
4467       return ExtendNodes.size();
4468   }
4469   return true;
4470 }
4471
4472 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4473                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4474                                   ISD::NodeType ExtType) {
4475   // Extend SetCC uses if necessary.
4476   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4477     SDNode *SetCC = SetCCs[i];
4478     SmallVector<SDValue, 4> Ops;
4479
4480     for (unsigned j = 0; j != 2; ++j) {
4481       SDValue SOp = SetCC->getOperand(j);
4482       if (SOp == Trunc)
4483         Ops.push_back(ExtLoad);
4484       else
4485         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4486     }
4487
4488     Ops.push_back(SetCC->getOperand(2));
4489     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4490                                  &Ops[0], Ops.size()));
4491   }
4492 }
4493
4494 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4495   SDValue N0 = N->getOperand(0);
4496   EVT VT = N->getValueType(0);
4497
4498   // fold (sext c1) -> c1
4499   if (isa<ConstantSDNode>(N0))
4500     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4501
4502   // fold (sext (sext x)) -> (sext x)
4503   // fold (sext (aext x)) -> (sext x)
4504   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4505     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4506                        N0.getOperand(0));
4507
4508   if (N0.getOpcode() == ISD::TRUNCATE) {
4509     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4510     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4511     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4512     if (NarrowLoad.getNode()) {
4513       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4514       if (NarrowLoad.getNode() != N0.getNode()) {
4515         CombineTo(N0.getNode(), NarrowLoad);
4516         // CombineTo deleted the truncate, if needed, but not what's under it.
4517         AddToWorkList(oye);
4518       }
4519       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4520     }
4521
4522     // See if the value being truncated is already sign extended.  If so, just
4523     // eliminate the trunc/sext pair.
4524     SDValue Op = N0.getOperand(0);
4525     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4526     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4527     unsigned DestBits = VT.getScalarType().getSizeInBits();
4528     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4529
4530     if (OpBits == DestBits) {
4531       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4532       // bits, it is already ready.
4533       if (NumSignBits > DestBits-MidBits)
4534         return Op;
4535     } else if (OpBits < DestBits) {
4536       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4537       // bits, just sext from i32.
4538       if (NumSignBits > OpBits-MidBits)
4539         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4540     } else {
4541       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4542       // bits, just truncate to i32.
4543       if (NumSignBits > OpBits-MidBits)
4544         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4545     }
4546
4547     // fold (sext (truncate x)) -> (sextinreg x).
4548     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4549                                                  N0.getValueType())) {
4550       if (OpBits < DestBits)
4551         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4552       else if (OpBits > DestBits)
4553         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4554       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4555                          DAG.getValueType(N0.getValueType()));
4556     }
4557   }
4558
4559   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4560   // None of the supported targets knows how to perform load and sign extend
4561   // on vectors in one instruction.  We only perform this transformation on
4562   // scalars.
4563   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4564       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4565        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4566     bool DoXform = true;
4567     SmallVector<SDNode*, 4> SetCCs;
4568     if (!N0.hasOneUse())
4569       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4570     if (DoXform) {
4571       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4572       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4573                                        LN0->getChain(),
4574                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4575                                        N0.getValueType(),
4576                                        LN0->isVolatile(), LN0->isNonTemporal(),
4577                                        LN0->getAlignment());
4578       CombineTo(N, ExtLoad);
4579       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4580                                   N0.getValueType(), ExtLoad);
4581       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4582       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4583                       ISD::SIGN_EXTEND);
4584       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4585     }
4586   }
4587
4588   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4589   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4590   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4591       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4592     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4593     EVT MemVT = LN0->getMemoryVT();
4594     if ((!LegalOperations && !LN0->isVolatile()) ||
4595         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4596       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4597                                        LN0->getChain(),
4598                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4599                                        MemVT,
4600                                        LN0->isVolatile(), LN0->isNonTemporal(),
4601                                        LN0->getAlignment());
4602       CombineTo(N, ExtLoad);
4603       CombineTo(N0.getNode(),
4604                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4605                             N0.getValueType(), ExtLoad),
4606                 ExtLoad.getValue(1));
4607       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4608     }
4609   }
4610
4611   // fold (sext (and/or/xor (load x), cst)) ->
4612   //      (and/or/xor (sextload x), (sext cst))
4613   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4614        N0.getOpcode() == ISD::XOR) &&
4615       isa<LoadSDNode>(N0.getOperand(0)) &&
4616       N0.getOperand(1).getOpcode() == ISD::Constant &&
4617       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4618       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4619     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4620     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4621       bool DoXform = true;
4622       SmallVector<SDNode*, 4> SetCCs;
4623       if (!N0.hasOneUse())
4624         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4625                                           SetCCs, TLI);
4626       if (DoXform) {
4627         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4628                                          LN0->getChain(), LN0->getBasePtr(),
4629                                          LN0->getPointerInfo(),
4630                                          LN0->getMemoryVT(),
4631                                          LN0->isVolatile(),
4632                                          LN0->isNonTemporal(),
4633                                          LN0->getAlignment());
4634         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4635         Mask = Mask.sext(VT.getSizeInBits());
4636         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4637                                   ExtLoad, DAG.getConstant(Mask, VT));
4638         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4639                                     SDLoc(N0.getOperand(0)),
4640                                     N0.getOperand(0).getValueType(), ExtLoad);
4641         CombineTo(N, And);
4642         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4643         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4644                         ISD::SIGN_EXTEND);
4645         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4646       }
4647     }
4648   }
4649
4650   if (N0.getOpcode() == ISD::SETCC) {
4651     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4652     // Only do this before legalize for now.
4653     if (VT.isVector() && !LegalOperations &&
4654         TLI.getBooleanContents(true) ==
4655           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4656       EVT N0VT = N0.getOperand(0).getValueType();
4657       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4658       // of the same size as the compared operands. Only optimize sext(setcc())
4659       // if this is the case.
4660       EVT SVT = getSetCCResultType(N0VT);
4661
4662       // We know that the # elements of the results is the same as the
4663       // # elements of the compare (and the # elements of the compare result
4664       // for that matter).  Check to see that they are the same size.  If so,
4665       // we know that the element size of the sext'd result matches the
4666       // element size of the compare operands.
4667       if (VT.getSizeInBits() == SVT.getSizeInBits())
4668         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4669                              N0.getOperand(1),
4670                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4671
4672       // If the desired elements are smaller or larger than the source
4673       // elements we can use a matching integer vector type and then
4674       // truncate/sign extend
4675       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4676       if (SVT == MatchingVectorType) {
4677         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4678                                N0.getOperand(0), N0.getOperand(1),
4679                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4680         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4681       }
4682     }
4683
4684     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4685     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4686     SDValue NegOne =
4687       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4688     SDValue SCC =
4689       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4690                        NegOne, DAG.getConstant(0, VT),
4691                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4692     if (SCC.getNode()) return SCC;
4693     if (!VT.isVector() &&
4694         (!LegalOperations ||
4695          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4696       return DAG.getSelect(SDLoc(N), VT,
4697                            DAG.getSetCC(SDLoc(N),
4698                            getSetCCResultType(VT),
4699                            N0.getOperand(0), N0.getOperand(1),
4700                            cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4701                            NegOne, DAG.getConstant(0, VT));
4702     }
4703   }
4704
4705   // fold (sext x) -> (zext x) if the sign bit is known zero.
4706   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4707       DAG.SignBitIsZero(N0))
4708     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4709
4710   return SDValue();
4711 }
4712
4713 // isTruncateOf - If N is a truncate of some other value, return true, record
4714 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4715 // This function computes KnownZero to avoid a duplicated call to
4716 // ComputeMaskedBits in the caller.
4717 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4718                          APInt &KnownZero) {
4719   APInt KnownOne;
4720   if (N->getOpcode() == ISD::TRUNCATE) {
4721     Op = N->getOperand(0);
4722     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4723     return true;
4724   }
4725
4726   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4727       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4728     return false;
4729
4730   SDValue Op0 = N->getOperand(0);
4731   SDValue Op1 = N->getOperand(1);
4732   assert(Op0.getValueType() == Op1.getValueType());
4733
4734   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4735   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4736   if (COp0 && COp0->isNullValue())
4737     Op = Op1;
4738   else if (COp1 && COp1->isNullValue())
4739     Op = Op0;
4740   else
4741     return false;
4742
4743   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4744
4745   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4746     return false;
4747
4748   return true;
4749 }
4750
4751 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4752   SDValue N0 = N->getOperand(0);
4753   EVT VT = N->getValueType(0);
4754
4755   // fold (zext c1) -> c1
4756   if (isa<ConstantSDNode>(N0))
4757     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4758   // fold (zext (zext x)) -> (zext x)
4759   // fold (zext (aext x)) -> (zext x)
4760   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4761     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4762                        N0.getOperand(0));
4763
4764   // fold (zext (truncate x)) -> (zext x) or
4765   //      (zext (truncate x)) -> (truncate x)
4766   // This is valid when the truncated bits of x are already zero.
4767   // FIXME: We should extend this to work for vectors too.
4768   SDValue Op;
4769   APInt KnownZero;
4770   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4771     APInt TruncatedBits =
4772       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4773       APInt(Op.getValueSizeInBits(), 0) :
4774       APInt::getBitsSet(Op.getValueSizeInBits(),
4775                         N0.getValueSizeInBits(),
4776                         std::min(Op.getValueSizeInBits(),
4777                                  VT.getSizeInBits()));
4778     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4779       if (VT.bitsGT(Op.getValueType()))
4780         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4781       if (VT.bitsLT(Op.getValueType()))
4782         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4783
4784       return Op;
4785     }
4786   }
4787
4788   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4789   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4790   if (N0.getOpcode() == ISD::TRUNCATE) {
4791     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4792     if (NarrowLoad.getNode()) {
4793       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4794       if (NarrowLoad.getNode() != N0.getNode()) {
4795         CombineTo(N0.getNode(), NarrowLoad);
4796         // CombineTo deleted the truncate, if needed, but not what's under it.
4797         AddToWorkList(oye);
4798       }
4799       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4800     }
4801   }
4802
4803   // fold (zext (truncate x)) -> (and x, mask)
4804   if (N0.getOpcode() == ISD::TRUNCATE &&
4805       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4806
4807     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4808     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4809     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4810     if (NarrowLoad.getNode()) {
4811       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4812       if (NarrowLoad.getNode() != N0.getNode()) {
4813         CombineTo(N0.getNode(), NarrowLoad);
4814         // CombineTo deleted the truncate, if needed, but not what's under it.
4815         AddToWorkList(oye);
4816       }
4817       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4818     }
4819
4820     SDValue Op = N0.getOperand(0);
4821     if (Op.getValueType().bitsLT(VT)) {
4822       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4823       AddToWorkList(Op.getNode());
4824     } else if (Op.getValueType().bitsGT(VT)) {
4825       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4826       AddToWorkList(Op.getNode());
4827     }
4828     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4829                                   N0.getValueType().getScalarType());
4830   }
4831
4832   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4833   // if either of the casts is not free.
4834   if (N0.getOpcode() == ISD::AND &&
4835       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4836       N0.getOperand(1).getOpcode() == ISD::Constant &&
4837       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4838                            N0.getValueType()) ||
4839        !TLI.isZExtFree(N0.getValueType(), VT))) {
4840     SDValue X = N0.getOperand(0).getOperand(0);
4841     if (X.getValueType().bitsLT(VT)) {
4842       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4843     } else if (X.getValueType().bitsGT(VT)) {
4844       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4845     }
4846     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4847     Mask = Mask.zext(VT.getSizeInBits());
4848     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4849                        X, DAG.getConstant(Mask, VT));
4850   }
4851
4852   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4853   // None of the supported targets knows how to perform load and vector_zext
4854   // on vectors in one instruction.  We only perform this transformation on
4855   // scalars.
4856   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4857       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4858        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4859     bool DoXform = true;
4860     SmallVector<SDNode*, 4> SetCCs;
4861     if (!N0.hasOneUse())
4862       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4863     if (DoXform) {
4864       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4865       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4866                                        LN0->getChain(),
4867                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4868                                        N0.getValueType(),
4869                                        LN0->isVolatile(), LN0->isNonTemporal(),
4870                                        LN0->getAlignment());
4871       CombineTo(N, ExtLoad);
4872       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4873                                   N0.getValueType(), ExtLoad);
4874       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4875
4876       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4877                       ISD::ZERO_EXTEND);
4878       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4879     }
4880   }
4881
4882   // fold (zext (and/or/xor (load x), cst)) ->
4883   //      (and/or/xor (zextload x), (zext cst))
4884   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4885        N0.getOpcode() == ISD::XOR) &&
4886       isa<LoadSDNode>(N0.getOperand(0)) &&
4887       N0.getOperand(1).getOpcode() == ISD::Constant &&
4888       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4889       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4890     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4891     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4892       bool DoXform = true;
4893       SmallVector<SDNode*, 4> SetCCs;
4894       if (!N0.hasOneUse())
4895         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4896                                           SetCCs, TLI);
4897       if (DoXform) {
4898         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4899                                          LN0->getChain(), LN0->getBasePtr(),
4900                                          LN0->getPointerInfo(),
4901                                          LN0->getMemoryVT(),
4902                                          LN0->isVolatile(),
4903                                          LN0->isNonTemporal(),
4904                                          LN0->getAlignment());
4905         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4906         Mask = Mask.zext(VT.getSizeInBits());
4907         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4908                                   ExtLoad, DAG.getConstant(Mask, VT));
4909         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4910                                     SDLoc(N0.getOperand(0)),
4911                                     N0.getOperand(0).getValueType(), ExtLoad);
4912         CombineTo(N, And);
4913         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4914         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4915                         ISD::ZERO_EXTEND);
4916         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4917       }
4918     }
4919   }
4920
4921   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4922   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4923   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4924       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4925     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4926     EVT MemVT = LN0->getMemoryVT();
4927     if ((!LegalOperations && !LN0->isVolatile()) ||
4928         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4929       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4930                                        LN0->getChain(),
4931                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4932                                        MemVT,
4933                                        LN0->isVolatile(), LN0->isNonTemporal(),
4934                                        LN0->getAlignment());
4935       CombineTo(N, ExtLoad);
4936       CombineTo(N0.getNode(),
4937                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4938                             ExtLoad),
4939                 ExtLoad.getValue(1));
4940       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4941     }
4942   }
4943
4944   if (N0.getOpcode() == ISD::SETCC) {
4945     if (!LegalOperations && VT.isVector()) {
4946       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4947       // Only do this before legalize for now.
4948       EVT N0VT = N0.getOperand(0).getValueType();
4949       EVT EltVT = VT.getVectorElementType();
4950       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4951                                     DAG.getConstant(1, EltVT));
4952       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4953         // We know that the # elements of the results is the same as the
4954         // # elements of the compare (and the # elements of the compare result
4955         // for that matter).  Check to see that they are the same size.  If so,
4956         // we know that the element size of the sext'd result matches the
4957         // element size of the compare operands.
4958         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4959                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4960                                          N0.getOperand(1),
4961                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4962                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4963                                        &OneOps[0], OneOps.size()));
4964
4965       // If the desired elements are smaller or larger than the source
4966       // elements we can use a matching integer vector type and then
4967       // truncate/sign extend
4968       EVT MatchingElementType =
4969         EVT::getIntegerVT(*DAG.getContext(),
4970                           N0VT.getScalarType().getSizeInBits());
4971       EVT MatchingVectorType =
4972         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4973                          N0VT.getVectorNumElements());
4974       SDValue VsetCC =
4975         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4976                       N0.getOperand(1),
4977                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4978       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4979                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4980                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4981                                      &OneOps[0], OneOps.size()));
4982     }
4983
4984     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4985     SDValue SCC =
4986       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4987                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4988                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4989     if (SCC.getNode()) return SCC;
4990   }
4991
4992   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4993   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4994       isa<ConstantSDNode>(N0.getOperand(1)) &&
4995       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4996       N0.hasOneUse()) {
4997     SDValue ShAmt = N0.getOperand(1);
4998     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4999     if (N0.getOpcode() == ISD::SHL) {
5000       SDValue InnerZExt = N0.getOperand(0);
5001       // If the original shl may be shifting out bits, do not perform this
5002       // transformation.
5003       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5004         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5005       if (ShAmtVal > KnownZeroBits)
5006         return SDValue();
5007     }
5008
5009     SDLoc DL(N);
5010
5011     // Ensure that the shift amount is wide enough for the shifted value.
5012     if (VT.getSizeInBits() >= 256)
5013       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5014
5015     return DAG.getNode(N0.getOpcode(), DL, VT,
5016                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5017                        ShAmt);
5018   }
5019
5020   return SDValue();
5021 }
5022
5023 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5024   SDValue N0 = N->getOperand(0);
5025   EVT VT = N->getValueType(0);
5026
5027   // fold (aext c1) -> c1
5028   if (isa<ConstantSDNode>(N0))
5029     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5030   // fold (aext (aext x)) -> (aext x)
5031   // fold (aext (zext x)) -> (zext x)
5032   // fold (aext (sext x)) -> (sext x)
5033   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5034       N0.getOpcode() == ISD::ZERO_EXTEND ||
5035       N0.getOpcode() == ISD::SIGN_EXTEND)
5036     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5037
5038   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5039   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5040   if (N0.getOpcode() == ISD::TRUNCATE) {
5041     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5042     if (NarrowLoad.getNode()) {
5043       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5044       if (NarrowLoad.getNode() != N0.getNode()) {
5045         CombineTo(N0.getNode(), NarrowLoad);
5046         // CombineTo deleted the truncate, if needed, but not what's under it.
5047         AddToWorkList(oye);
5048       }
5049       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5050     }
5051   }
5052
5053   // fold (aext (truncate x))
5054   if (N0.getOpcode() == ISD::TRUNCATE) {
5055     SDValue TruncOp = N0.getOperand(0);
5056     if (TruncOp.getValueType() == VT)
5057       return TruncOp; // x iff x size == zext size.
5058     if (TruncOp.getValueType().bitsGT(VT))
5059       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5060     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5061   }
5062
5063   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5064   // if the trunc is not free.
5065   if (N0.getOpcode() == ISD::AND &&
5066       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5067       N0.getOperand(1).getOpcode() == ISD::Constant &&
5068       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5069                           N0.getValueType())) {
5070     SDValue X = N0.getOperand(0).getOperand(0);
5071     if (X.getValueType().bitsLT(VT)) {
5072       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5073     } else if (X.getValueType().bitsGT(VT)) {
5074       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5075     }
5076     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5077     Mask = Mask.zext(VT.getSizeInBits());
5078     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5079                        X, DAG.getConstant(Mask, VT));
5080   }
5081
5082   // fold (aext (load x)) -> (aext (truncate (extload x)))
5083   // None of the supported targets knows how to perform load and any_ext
5084   // on vectors in one instruction.  We only perform this transformation on
5085   // scalars.
5086   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5087       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5088        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5089     bool DoXform = true;
5090     SmallVector<SDNode*, 4> SetCCs;
5091     if (!N0.hasOneUse())
5092       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5093     if (DoXform) {
5094       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5095       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5096                                        LN0->getChain(),
5097                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5098                                        N0.getValueType(),
5099                                        LN0->isVolatile(), LN0->isNonTemporal(),
5100                                        LN0->getAlignment());
5101       CombineTo(N, ExtLoad);
5102       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5103                                   N0.getValueType(), ExtLoad);
5104       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5105       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5106                       ISD::ANY_EXTEND);
5107       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5108     }
5109   }
5110
5111   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5112   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5113   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5114   if (N0.getOpcode() == ISD::LOAD &&
5115       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5116       N0.hasOneUse()) {
5117     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5118     EVT MemVT = LN0->getMemoryVT();
5119     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5120                                      VT, LN0->getChain(), LN0->getBasePtr(),
5121                                      LN0->getPointerInfo(), MemVT,
5122                                      LN0->isVolatile(), LN0->isNonTemporal(),
5123                                      LN0->getAlignment());
5124     CombineTo(N, ExtLoad);
5125     CombineTo(N0.getNode(),
5126               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5127                           N0.getValueType(), ExtLoad),
5128               ExtLoad.getValue(1));
5129     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5130   }
5131
5132   if (N0.getOpcode() == ISD::SETCC) {
5133     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5134     // Only do this before legalize for now.
5135     if (VT.isVector() && !LegalOperations) {
5136       EVT N0VT = N0.getOperand(0).getValueType();
5137         // We know that the # elements of the results is the same as the
5138         // # elements of the compare (and the # elements of the compare result
5139         // for that matter).  Check to see that they are the same size.  If so,
5140         // we know that the element size of the sext'd result matches the
5141         // element size of the compare operands.
5142       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5143         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5144                              N0.getOperand(1),
5145                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5146       // If the desired elements are smaller or larger than the source
5147       // elements we can use a matching integer vector type and then
5148       // truncate/sign extend
5149       else {
5150         EVT MatchingElementType =
5151           EVT::getIntegerVT(*DAG.getContext(),
5152                             N0VT.getScalarType().getSizeInBits());
5153         EVT MatchingVectorType =
5154           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5155                            N0VT.getVectorNumElements());
5156         SDValue VsetCC =
5157           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5158                         N0.getOperand(1),
5159                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5160         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5161       }
5162     }
5163
5164     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5165     SDValue SCC =
5166       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5167                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5168                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5169     if (SCC.getNode())
5170       return SCC;
5171   }
5172
5173   return SDValue();
5174 }
5175
5176 /// GetDemandedBits - See if the specified operand can be simplified with the
5177 /// knowledge that only the bits specified by Mask are used.  If so, return the
5178 /// simpler operand, otherwise return a null SDValue.
5179 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5180   switch (V.getOpcode()) {
5181   default: break;
5182   case ISD::Constant: {
5183     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5184     assert(CV != 0 && "Const value should be ConstSDNode.");
5185     const APInt &CVal = CV->getAPIntValue();
5186     APInt NewVal = CVal & Mask;
5187     if (NewVal != CVal)
5188       return DAG.getConstant(NewVal, V.getValueType());
5189     break;
5190   }
5191   case ISD::OR:
5192   case ISD::XOR:
5193     // If the LHS or RHS don't contribute bits to the or, drop them.
5194     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5195       return V.getOperand(1);
5196     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5197       return V.getOperand(0);
5198     break;
5199   case ISD::SRL:
5200     // Only look at single-use SRLs.
5201     if (!V.getNode()->hasOneUse())
5202       break;
5203     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5204       // See if we can recursively simplify the LHS.
5205       unsigned Amt = RHSC->getZExtValue();
5206
5207       // Watch out for shift count overflow though.
5208       if (Amt >= Mask.getBitWidth()) break;
5209       APInt NewMask = Mask << Amt;
5210       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5211       if (SimplifyLHS.getNode())
5212         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5213                            SimplifyLHS, V.getOperand(1));
5214     }
5215   }
5216   return SDValue();
5217 }
5218
5219 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5220 /// bits and then truncated to a narrower type and where N is a multiple
5221 /// of number of bits of the narrower type, transform it to a narrower load
5222 /// from address + N / num of bits of new type. If the result is to be
5223 /// extended, also fold the extension to form a extending load.
5224 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5225   unsigned Opc = N->getOpcode();
5226
5227   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5228   SDValue N0 = N->getOperand(0);
5229   EVT VT = N->getValueType(0);
5230   EVT ExtVT = VT;
5231
5232   // This transformation isn't valid for vector loads.
5233   if (VT.isVector())
5234     return SDValue();
5235
5236   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5237   // extended to VT.
5238   if (Opc == ISD::SIGN_EXTEND_INREG) {
5239     ExtType = ISD::SEXTLOAD;
5240     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5241   } else if (Opc == ISD::SRL) {
5242     // Another special-case: SRL is basically zero-extending a narrower value.
5243     ExtType = ISD::ZEXTLOAD;
5244     N0 = SDValue(N, 0);
5245     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5246     if (!N01) return SDValue();
5247     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5248                               VT.getSizeInBits() - N01->getZExtValue());
5249   }
5250   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5251     return SDValue();
5252
5253   unsigned EVTBits = ExtVT.getSizeInBits();
5254
5255   // Do not generate loads of non-round integer types since these can
5256   // be expensive (and would be wrong if the type is not byte sized).
5257   if (!ExtVT.isRound())
5258     return SDValue();
5259
5260   unsigned ShAmt = 0;
5261   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5262     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5263       ShAmt = N01->getZExtValue();
5264       // Is the shift amount a multiple of size of VT?
5265       if ((ShAmt & (EVTBits-1)) == 0) {
5266         N0 = N0.getOperand(0);
5267         // Is the load width a multiple of size of VT?
5268         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5269           return SDValue();
5270       }
5271
5272       // At this point, we must have a load or else we can't do the transform.
5273       if (!isa<LoadSDNode>(N0)) return SDValue();
5274
5275       // Because a SRL must be assumed to *need* to zero-extend the high bits
5276       // (as opposed to anyext the high bits), we can't combine the zextload
5277       // lowering of SRL and an sextload.
5278       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5279         return SDValue();
5280
5281       // If the shift amount is larger than the input type then we're not
5282       // accessing any of the loaded bytes.  If the load was a zextload/extload
5283       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5284       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5285         return SDValue();
5286     }
5287   }
5288
5289   // If the load is shifted left (and the result isn't shifted back right),
5290   // we can fold the truncate through the shift.
5291   unsigned ShLeftAmt = 0;
5292   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5293       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5294     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5295       ShLeftAmt = N01->getZExtValue();
5296       N0 = N0.getOperand(0);
5297     }
5298   }
5299
5300   // If we haven't found a load, we can't narrow it.  Don't transform one with
5301   // multiple uses, this would require adding a new load.
5302   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5303     return SDValue();
5304
5305   // Don't change the width of a volatile load.
5306   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5307   if (LN0->isVolatile())
5308     return SDValue();
5309
5310   // Verify that we are actually reducing a load width here.
5311   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5312     return SDValue();
5313
5314   // For the transform to be legal, the load must produce only two values
5315   // (the value loaded and the chain).  Don't transform a pre-increment
5316   // load, for example, which produces an extra value.  Otherwise the
5317   // transformation is not equivalent, and the downstream logic to replace
5318   // uses gets things wrong.
5319   if (LN0->getNumValues() > 2)
5320     return SDValue();
5321
5322   // If the load that we're shrinking is an extload and we're not just
5323   // discarding the extension we can't simply shrink the load. Bail.
5324   // TODO: It would be possible to merge the extensions in some cases.
5325   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5326       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5327     return SDValue();
5328
5329   EVT PtrType = N0.getOperand(1).getValueType();
5330
5331   if (PtrType == MVT::Untyped || PtrType.isExtended())
5332     // It's not possible to generate a constant of extended or untyped type.
5333     return SDValue();
5334
5335   // For big endian targets, we need to adjust the offset to the pointer to
5336   // load the correct bytes.
5337   if (TLI.isBigEndian()) {
5338     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5339     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5340     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5341   }
5342
5343   uint64_t PtrOff = ShAmt / 8;
5344   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5345   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5346                                PtrType, LN0->getBasePtr(),
5347                                DAG.getConstant(PtrOff, PtrType));
5348   AddToWorkList(NewPtr.getNode());
5349
5350   SDValue Load;
5351   if (ExtType == ISD::NON_EXTLOAD)
5352     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5353                         LN0->getPointerInfo().getWithOffset(PtrOff),
5354                         LN0->isVolatile(), LN0->isNonTemporal(),
5355                         LN0->isInvariant(), NewAlign);
5356   else
5357     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5358                           LN0->getPointerInfo().getWithOffset(PtrOff),
5359                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5360                           NewAlign);
5361
5362   // Replace the old load's chain with the new load's chain.
5363   WorkListRemover DeadNodes(*this);
5364   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5365
5366   // Shift the result left, if we've swallowed a left shift.
5367   SDValue Result = Load;
5368   if (ShLeftAmt != 0) {
5369     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5370     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5371       ShImmTy = VT;
5372     // If the shift amount is as large as the result size (but, presumably,
5373     // no larger than the source) then the useful bits of the result are
5374     // zero; we can't simply return the shortened shift, because the result
5375     // of that operation is undefined.
5376     if (ShLeftAmt >= VT.getSizeInBits())
5377       Result = DAG.getConstant(0, VT);
5378     else
5379       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5380                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5381   }
5382
5383   // Return the new loaded value.
5384   return Result;
5385 }
5386
5387 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5388   SDValue N0 = N->getOperand(0);
5389   SDValue N1 = N->getOperand(1);
5390   EVT VT = N->getValueType(0);
5391   EVT EVT = cast<VTSDNode>(N1)->getVT();
5392   unsigned VTBits = VT.getScalarType().getSizeInBits();
5393   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5394
5395   // fold (sext_in_reg c1) -> c1
5396   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5397     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5398
5399   // If the input is already sign extended, just drop the extension.
5400   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5401     return N0;
5402
5403   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5404   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5405       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5406     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5407                        N0.getOperand(0), N1);
5408
5409   // fold (sext_in_reg (sext x)) -> (sext x)
5410   // fold (sext_in_reg (aext x)) -> (sext x)
5411   // if x is small enough.
5412   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5413     SDValue N00 = N0.getOperand(0);
5414     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5415         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5416       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5417   }
5418
5419   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5420   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5421     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5422
5423   // fold operands of sext_in_reg based on knowledge that the top bits are not
5424   // demanded.
5425   if (SimplifyDemandedBits(SDValue(N, 0)))
5426     return SDValue(N, 0);
5427
5428   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5429   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5430   SDValue NarrowLoad = ReduceLoadWidth(N);
5431   if (NarrowLoad.getNode())
5432     return NarrowLoad;
5433
5434   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5435   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5436   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5437   if (N0.getOpcode() == ISD::SRL) {
5438     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5439       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5440         // We can turn this into an SRA iff the input to the SRL is already sign
5441         // extended enough.
5442         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5443         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5444           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5445                              N0.getOperand(0), N0.getOperand(1));
5446       }
5447   }
5448
5449   // fold (sext_inreg (extload x)) -> (sextload x)
5450   if (ISD::isEXTLoad(N0.getNode()) &&
5451       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5452       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5453       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5454        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5455     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5456     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5457                                      LN0->getChain(),
5458                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5459                                      EVT,
5460                                      LN0->isVolatile(), LN0->isNonTemporal(),
5461                                      LN0->getAlignment());
5462     CombineTo(N, ExtLoad);
5463     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5464     AddToWorkList(ExtLoad.getNode());
5465     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5466   }
5467   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5468   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5469       N0.hasOneUse() &&
5470       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5471       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5472        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5473     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5474     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5475                                      LN0->getChain(),
5476                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5477                                      EVT,
5478                                      LN0->isVolatile(), LN0->isNonTemporal(),
5479                                      LN0->getAlignment());
5480     CombineTo(N, ExtLoad);
5481     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5482     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5483   }
5484
5485   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5486   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5487     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5488                                        N0.getOperand(1), false);
5489     if (BSwap.getNode() != 0)
5490       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5491                          BSwap, N1);
5492   }
5493
5494   return SDValue();
5495 }
5496
5497 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5498   SDValue N0 = N->getOperand(0);
5499   EVT VT = N->getValueType(0);
5500   bool isLE = TLI.isLittleEndian();
5501
5502   // noop truncate
5503   if (N0.getValueType() == N->getValueType(0))
5504     return N0;
5505   // fold (truncate c1) -> c1
5506   if (isa<ConstantSDNode>(N0))
5507     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5508   // fold (truncate (truncate x)) -> (truncate x)
5509   if (N0.getOpcode() == ISD::TRUNCATE)
5510     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5511   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5512   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5513       N0.getOpcode() == ISD::SIGN_EXTEND ||
5514       N0.getOpcode() == ISD::ANY_EXTEND) {
5515     if (N0.getOperand(0).getValueType().bitsLT(VT))
5516       // if the source is smaller than the dest, we still need an extend
5517       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5518                          N0.getOperand(0));
5519     if (N0.getOperand(0).getValueType().bitsGT(VT))
5520       // if the source is larger than the dest, than we just need the truncate
5521       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5522     // if the source and dest are the same type, we can drop both the extend
5523     // and the truncate.
5524     return N0.getOperand(0);
5525   }
5526
5527   // Fold extract-and-trunc into a narrow extract. For example:
5528   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5529   //   i32 y = TRUNCATE(i64 x)
5530   //        -- becomes --
5531   //   v16i8 b = BITCAST (v2i64 val)
5532   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5533   //
5534   // Note: We only run this optimization after type legalization (which often
5535   // creates this pattern) and before operation legalization after which
5536   // we need to be more careful about the vector instructions that we generate.
5537   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5538       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5539
5540     EVT VecTy = N0.getOperand(0).getValueType();
5541     EVT ExTy = N0.getValueType();
5542     EVT TrTy = N->getValueType(0);
5543
5544     unsigned NumElem = VecTy.getVectorNumElements();
5545     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5546
5547     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5548     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5549
5550     SDValue EltNo = N0->getOperand(1);
5551     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5552       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5553       EVT IndexTy = TLI.getVectorIdxTy();
5554       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5555
5556       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5557                               NVT, N0.getOperand(0));
5558
5559       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5560                          SDLoc(N), TrTy, V,
5561                          DAG.getConstant(Index, IndexTy));
5562     }
5563   }
5564
5565   // Fold a series of buildvector, bitcast, and truncate if possible.
5566   // For example fold
5567   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5568   //   (2xi32 (buildvector x, y)).
5569   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5570       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5571       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5572       N0.getOperand(0).hasOneUse()) {
5573
5574     SDValue BuildVect = N0.getOperand(0);
5575     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5576     EVT TruncVecEltTy = VT.getVectorElementType();
5577
5578     // Check that the element types match.
5579     if (BuildVectEltTy == TruncVecEltTy) {
5580       // Now we only need to compute the offset of the truncated elements.
5581       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5582       unsigned TruncVecNumElts = VT.getVectorNumElements();
5583       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5584
5585       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5586              "Invalid number of elements");
5587
5588       SmallVector<SDValue, 8> Opnds;
5589       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5590         Opnds.push_back(BuildVect.getOperand(i));
5591
5592       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5593                          Opnds.size());
5594     }
5595   }
5596
5597   // See if we can simplify the input to this truncate through knowledge that
5598   // only the low bits are being used.
5599   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5600   // Currently we only perform this optimization on scalars because vectors
5601   // may have different active low bits.
5602   if (!VT.isVector()) {
5603     SDValue Shorter =
5604       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5605                                                VT.getSizeInBits()));
5606     if (Shorter.getNode())
5607       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5608   }
5609   // fold (truncate (load x)) -> (smaller load x)
5610   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5611   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5612     SDValue Reduced = ReduceLoadWidth(N);
5613     if (Reduced.getNode())
5614       return Reduced;
5615   }
5616   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5617   // where ... are all 'undef'.
5618   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5619     SmallVector<EVT, 8> VTs;
5620     SDValue V;
5621     unsigned Idx = 0;
5622     unsigned NumDefs = 0;
5623
5624     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5625       SDValue X = N0.getOperand(i);
5626       if (X.getOpcode() != ISD::UNDEF) {
5627         V = X;
5628         Idx = i;
5629         NumDefs++;
5630       }
5631       // Stop if more than one members are non-undef.
5632       if (NumDefs > 1)
5633         break;
5634       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5635                                      VT.getVectorElementType(),
5636                                      X.getValueType().getVectorNumElements()));
5637     }
5638
5639     if (NumDefs == 0)
5640       return DAG.getUNDEF(VT);
5641
5642     if (NumDefs == 1) {
5643       assert(V.getNode() && "The single defined operand is empty!");
5644       SmallVector<SDValue, 8> Opnds;
5645       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5646         if (i != Idx) {
5647           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5648           continue;
5649         }
5650         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5651         AddToWorkList(NV.getNode());
5652         Opnds.push_back(NV);
5653       }
5654       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5655                          &Opnds[0], Opnds.size());
5656     }
5657   }
5658
5659   // Simplify the operands using demanded-bits information.
5660   if (!VT.isVector() &&
5661       SimplifyDemandedBits(SDValue(N, 0)))
5662     return SDValue(N, 0);
5663
5664   return SDValue();
5665 }
5666
5667 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5668   SDValue Elt = N->getOperand(i);
5669   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5670     return Elt.getNode();
5671   return Elt.getOperand(Elt.getResNo()).getNode();
5672 }
5673
5674 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5675 /// if load locations are consecutive.
5676 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5677   assert(N->getOpcode() == ISD::BUILD_PAIR);
5678
5679   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5680   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5681   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5682       LD1->getPointerInfo().getAddrSpace() !=
5683          LD2->getPointerInfo().getAddrSpace())
5684     return SDValue();
5685   EVT LD1VT = LD1->getValueType(0);
5686
5687   if (ISD::isNON_EXTLoad(LD2) &&
5688       LD2->hasOneUse() &&
5689       // If both are volatile this would reduce the number of volatile loads.
5690       // If one is volatile it might be ok, but play conservative and bail out.
5691       !LD1->isVolatile() &&
5692       !LD2->isVolatile() &&
5693       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5694     unsigned Align = LD1->getAlignment();
5695     unsigned NewAlign = TLI.getDataLayout()->
5696       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5697
5698     if (NewAlign <= Align &&
5699         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5700       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5701                          LD1->getBasePtr(), LD1->getPointerInfo(),
5702                          false, false, false, Align);
5703   }
5704
5705   return SDValue();
5706 }
5707
5708 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5709   SDValue N0 = N->getOperand(0);
5710   EVT VT = N->getValueType(0);
5711
5712   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5713   // Only do this before legalize, since afterward the target may be depending
5714   // on the bitconvert.
5715   // First check to see if this is all constant.
5716   if (!LegalTypes &&
5717       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5718       VT.isVector()) {
5719     bool isSimple = true;
5720     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5721       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5722           N0.getOperand(i).getOpcode() != ISD::Constant &&
5723           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5724         isSimple = false;
5725         break;
5726       }
5727
5728     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5729     assert(!DestEltVT.isVector() &&
5730            "Element type of vector ValueType must not be vector!");
5731     if (isSimple)
5732       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5733   }
5734
5735   // If the input is a constant, let getNode fold it.
5736   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5737     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5738     if (Res.getNode() != N) {
5739       if (!LegalOperations ||
5740           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5741         return Res;
5742
5743       // Folding it resulted in an illegal node, and it's too late to
5744       // do that. Clean up the old node and forego the transformation.
5745       // Ideally this won't happen very often, because instcombine
5746       // and the earlier dagcombine runs (where illegal nodes are
5747       // permitted) should have folded most of them already.
5748       DAG.DeleteNode(Res.getNode());
5749     }
5750   }
5751
5752   // (conv (conv x, t1), t2) -> (conv x, t2)
5753   if (N0.getOpcode() == ISD::BITCAST)
5754     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5755                        N0.getOperand(0));
5756
5757   // fold (conv (load x)) -> (load (conv*)x)
5758   // If the resultant load doesn't need a higher alignment than the original!
5759   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5760       // Do not change the width of a volatile load.
5761       !cast<LoadSDNode>(N0)->isVolatile() &&
5762       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5763     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5764     unsigned Align = TLI.getDataLayout()->
5765       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5766     unsigned OrigAlign = LN0->getAlignment();
5767
5768     if (Align <= OrigAlign) {
5769       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5770                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5771                                  LN0->isVolatile(), LN0->isNonTemporal(),
5772                                  LN0->isInvariant(), OrigAlign);
5773       AddToWorkList(N);
5774       CombineTo(N0.getNode(),
5775                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5776                             N0.getValueType(), Load),
5777                 Load.getValue(1));
5778       return Load;
5779     }
5780   }
5781
5782   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5783   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5784   // This often reduces constant pool loads.
5785   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5786        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5787       N0.getNode()->hasOneUse() && VT.isInteger() &&
5788       !VT.isVector() && !N0.getValueType().isVector()) {
5789     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5790                                   N0.getOperand(0));
5791     AddToWorkList(NewConv.getNode());
5792
5793     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5794     if (N0.getOpcode() == ISD::FNEG)
5795       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5796                          NewConv, DAG.getConstant(SignBit, VT));
5797     assert(N0.getOpcode() == ISD::FABS);
5798     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5799                        NewConv, DAG.getConstant(~SignBit, VT));
5800   }
5801
5802   // fold (bitconvert (fcopysign cst, x)) ->
5803   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5804   // Note that we don't handle (copysign x, cst) because this can always be
5805   // folded to an fneg or fabs.
5806   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5807       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5808       VT.isInteger() && !VT.isVector()) {
5809     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5810     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5811     if (isTypeLegal(IntXVT)) {
5812       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5813                               IntXVT, N0.getOperand(1));
5814       AddToWorkList(X.getNode());
5815
5816       // If X has a different width than the result/lhs, sext it or truncate it.
5817       unsigned VTWidth = VT.getSizeInBits();
5818       if (OrigXWidth < VTWidth) {
5819         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5820         AddToWorkList(X.getNode());
5821       } else if (OrigXWidth > VTWidth) {
5822         // To get the sign bit in the right place, we have to shift it right
5823         // before truncating.
5824         X = DAG.getNode(ISD::SRL, SDLoc(X),
5825                         X.getValueType(), X,
5826                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5827         AddToWorkList(X.getNode());
5828         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5829         AddToWorkList(X.getNode());
5830       }
5831
5832       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5833       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5834                       X, DAG.getConstant(SignBit, VT));
5835       AddToWorkList(X.getNode());
5836
5837       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5838                                 VT, N0.getOperand(0));
5839       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5840                         Cst, DAG.getConstant(~SignBit, VT));
5841       AddToWorkList(Cst.getNode());
5842
5843       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5844     }
5845   }
5846
5847   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5848   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5849     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5850     if (CombineLD.getNode())
5851       return CombineLD;
5852   }
5853
5854   return SDValue();
5855 }
5856
5857 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5858   EVT VT = N->getValueType(0);
5859   return CombineConsecutiveLoads(N, VT);
5860 }
5861
5862 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5863 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5864 /// destination element value type.
5865 SDValue DAGCombiner::
5866 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5867   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5868
5869   // If this is already the right type, we're done.
5870   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5871
5872   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5873   unsigned DstBitSize = DstEltVT.getSizeInBits();
5874
5875   // If this is a conversion of N elements of one type to N elements of another
5876   // type, convert each element.  This handles FP<->INT cases.
5877   if (SrcBitSize == DstBitSize) {
5878     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5879                               BV->getValueType(0).getVectorNumElements());
5880
5881     // Due to the FP element handling below calling this routine recursively,
5882     // we can end up with a scalar-to-vector node here.
5883     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5884       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5885                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5886                                      DstEltVT, BV->getOperand(0)));
5887
5888     SmallVector<SDValue, 8> Ops;
5889     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5890       SDValue Op = BV->getOperand(i);
5891       // If the vector element type is not legal, the BUILD_VECTOR operands
5892       // are promoted and implicitly truncated.  Make that explicit here.
5893       if (Op.getValueType() != SrcEltVT)
5894         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5895       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5896                                 DstEltVT, Op));
5897       AddToWorkList(Ops.back().getNode());
5898     }
5899     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5900                        &Ops[0], Ops.size());
5901   }
5902
5903   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5904   // handle annoying details of growing/shrinking FP values, we convert them to
5905   // int first.
5906   if (SrcEltVT.isFloatingPoint()) {
5907     // Convert the input float vector to a int vector where the elements are the
5908     // same sizes.
5909     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5910     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5911     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5912     SrcEltVT = IntVT;
5913   }
5914
5915   // Now we know the input is an integer vector.  If the output is a FP type,
5916   // convert to integer first, then to FP of the right size.
5917   if (DstEltVT.isFloatingPoint()) {
5918     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5919     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5920     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5921
5922     // Next, convert to FP elements of the same size.
5923     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5924   }
5925
5926   // Okay, we know the src/dst types are both integers of differing types.
5927   // Handling growing first.
5928   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5929   if (SrcBitSize < DstBitSize) {
5930     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5931
5932     SmallVector<SDValue, 8> Ops;
5933     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5934          i += NumInputsPerOutput) {
5935       bool isLE = TLI.isLittleEndian();
5936       APInt NewBits = APInt(DstBitSize, 0);
5937       bool EltIsUndef = true;
5938       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5939         // Shift the previously computed bits over.
5940         NewBits <<= SrcBitSize;
5941         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5942         if (Op.getOpcode() == ISD::UNDEF) continue;
5943         EltIsUndef = false;
5944
5945         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5946                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5947       }
5948
5949       if (EltIsUndef)
5950         Ops.push_back(DAG.getUNDEF(DstEltVT));
5951       else
5952         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5953     }
5954
5955     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5956     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5957                        &Ops[0], Ops.size());
5958   }
5959
5960   // Finally, this must be the case where we are shrinking elements: each input
5961   // turns into multiple outputs.
5962   bool isS2V = ISD::isScalarToVector(BV);
5963   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5964   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5965                             NumOutputsPerInput*BV->getNumOperands());
5966   SmallVector<SDValue, 8> Ops;
5967
5968   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5969     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5970       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5971         Ops.push_back(DAG.getUNDEF(DstEltVT));
5972       continue;
5973     }
5974
5975     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5976                   getAPIntValue().zextOrTrunc(SrcBitSize);
5977
5978     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5979       APInt ThisVal = OpVal.trunc(DstBitSize);
5980       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5981       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5982         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5983         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5984                            Ops[0]);
5985       OpVal = OpVal.lshr(DstBitSize);
5986     }
5987
5988     // For big endian targets, swap the order of the pieces of each element.
5989     if (TLI.isBigEndian())
5990       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5991   }
5992
5993   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5994                      &Ops[0], Ops.size());
5995 }
5996
5997 SDValue DAGCombiner::visitFADD(SDNode *N) {
5998   SDValue N0 = N->getOperand(0);
5999   SDValue N1 = N->getOperand(1);
6000   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6001   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6002   EVT VT = N->getValueType(0);
6003
6004   // fold vector ops
6005   if (VT.isVector()) {
6006     SDValue FoldedVOp = SimplifyVBinOp(N);
6007     if (FoldedVOp.getNode()) return FoldedVOp;
6008   }
6009
6010   // fold (fadd c1, c2) -> c1 + c2
6011   if (N0CFP && N1CFP)
6012     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6013   // canonicalize constant to RHS
6014   if (N0CFP && !N1CFP)
6015     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6016   // fold (fadd A, 0) -> A
6017   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6018       N1CFP->getValueAPF().isZero())
6019     return N0;
6020   // fold (fadd A, (fneg B)) -> (fsub A, B)
6021   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6022     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6023     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6024                        GetNegatedExpression(N1, DAG, LegalOperations));
6025   // fold (fadd (fneg A), B) -> (fsub B, A)
6026   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6027     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6028     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6029                        GetNegatedExpression(N0, DAG, LegalOperations));
6030
6031   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6032   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6033       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6034       isa<ConstantFPSDNode>(N0.getOperand(1)))
6035     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6036                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6037                                    N0.getOperand(1), N1));
6038
6039   // No FP constant should be created after legalization as Instruction
6040   // Selection pass has hard time in dealing with FP constant.
6041   //
6042   // We don't need test this condition for transformation like following, as
6043   // the DAG being transformed implies it is legal to take FP constant as
6044   // operand.
6045   //
6046   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6047   //
6048   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6049
6050   // If allow, fold (fadd (fneg x), x) -> 0.0
6051   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6052       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6053     return DAG.getConstantFP(0.0, VT);
6054
6055     // If allow, fold (fadd x, (fneg x)) -> 0.0
6056   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6057       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6058     return DAG.getConstantFP(0.0, VT);
6059
6060   // In unsafe math mode, we can fold chains of FADD's of the same value
6061   // into multiplications.  This transform is not safe in general because
6062   // we are reducing the number of rounding steps.
6063   if (DAG.getTarget().Options.UnsafeFPMath &&
6064       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6065       !N0CFP && !N1CFP) {
6066     if (N0.getOpcode() == ISD::FMUL) {
6067       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6068       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6069
6070       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6071       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6072         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6073                                      SDValue(CFP00, 0),
6074                                      DAG.getConstantFP(1.0, VT));
6075         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6076                            N1, NewCFP);
6077       }
6078
6079       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6080       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6081         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6082                                      SDValue(CFP01, 0),
6083                                      DAG.getConstantFP(1.0, VT));
6084         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6085                            N1, NewCFP);
6086       }
6087
6088       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6089       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6090           N1.getOperand(0) == N1.getOperand(1) &&
6091           N0.getOperand(1) == N1.getOperand(0)) {
6092         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6093                                      SDValue(CFP00, 0),
6094                                      DAG.getConstantFP(2.0, VT));
6095         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6096                            N0.getOperand(1), NewCFP);
6097       }
6098
6099       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6100       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6101           N1.getOperand(0) == N1.getOperand(1) &&
6102           N0.getOperand(0) == N1.getOperand(0)) {
6103         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6104                                      SDValue(CFP01, 0),
6105                                      DAG.getConstantFP(2.0, VT));
6106         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6107                            N0.getOperand(0), NewCFP);
6108       }
6109     }
6110
6111     if (N1.getOpcode() == ISD::FMUL) {
6112       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6113       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6114
6115       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6116       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6117         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6118                                      SDValue(CFP10, 0),
6119                                      DAG.getConstantFP(1.0, VT));
6120         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6121                            N0, NewCFP);
6122       }
6123
6124       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6125       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6126         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6127                                      SDValue(CFP11, 0),
6128                                      DAG.getConstantFP(1.0, VT));
6129         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6130                            N0, NewCFP);
6131       }
6132
6133
6134       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6135       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6136           N0.getOperand(0) == N0.getOperand(1) &&
6137           N1.getOperand(1) == N0.getOperand(0)) {
6138         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6139                                      SDValue(CFP10, 0),
6140                                      DAG.getConstantFP(2.0, VT));
6141         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6142                            N1.getOperand(1), NewCFP);
6143       }
6144
6145       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6146       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6147           N0.getOperand(0) == N0.getOperand(1) &&
6148           N1.getOperand(0) == N0.getOperand(0)) {
6149         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6150                                      SDValue(CFP11, 0),
6151                                      DAG.getConstantFP(2.0, VT));
6152         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6153                            N1.getOperand(0), NewCFP);
6154       }
6155     }
6156
6157     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6158       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6159       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6160       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6161           (N0.getOperand(0) == N1))
6162         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6163                            N1, DAG.getConstantFP(3.0, VT));
6164     }
6165
6166     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6167       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6168       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6169       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6170           N1.getOperand(0) == N0)
6171         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6172                            N0, DAG.getConstantFP(3.0, VT));
6173     }
6174
6175     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6176     if (AllowNewFpConst &&
6177         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6178         N0.getOperand(0) == N0.getOperand(1) &&
6179         N1.getOperand(0) == N1.getOperand(1) &&
6180         N0.getOperand(0) == N1.getOperand(0))
6181       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6182                          N0.getOperand(0),
6183                          DAG.getConstantFP(4.0, VT));
6184   }
6185
6186   // FADD -> FMA combines:
6187   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6188        DAG.getTarget().Options.UnsafeFPMath) &&
6189       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6190       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6191
6192     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6193     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6194       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6195                          N0.getOperand(0), N0.getOperand(1), N1);
6196
6197     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6198     // Note: Commutes FADD operands.
6199     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6200       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6201                          N1.getOperand(0), N1.getOperand(1), N0);
6202   }
6203
6204   return SDValue();
6205 }
6206
6207 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6208   SDValue N0 = N->getOperand(0);
6209   SDValue N1 = N->getOperand(1);
6210   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6211   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6212   EVT VT = N->getValueType(0);
6213   SDLoc dl(N);
6214
6215   // fold vector ops
6216   if (VT.isVector()) {
6217     SDValue FoldedVOp = SimplifyVBinOp(N);
6218     if (FoldedVOp.getNode()) return FoldedVOp;
6219   }
6220
6221   // fold (fsub c1, c2) -> c1-c2
6222   if (N0CFP && N1CFP)
6223     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6224   // fold (fsub A, 0) -> A
6225   if (DAG.getTarget().Options.UnsafeFPMath &&
6226       N1CFP && N1CFP->getValueAPF().isZero())
6227     return N0;
6228   // fold (fsub 0, B) -> -B
6229   if (DAG.getTarget().Options.UnsafeFPMath &&
6230       N0CFP && N0CFP->getValueAPF().isZero()) {
6231     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6232       return GetNegatedExpression(N1, DAG, LegalOperations);
6233     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6234       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6235   }
6236   // fold (fsub A, (fneg B)) -> (fadd A, B)
6237   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6238     return DAG.getNode(ISD::FADD, dl, VT, N0,
6239                        GetNegatedExpression(N1, DAG, LegalOperations));
6240
6241   // If 'unsafe math' is enabled, fold
6242   //    (fsub x, x) -> 0.0 &
6243   //    (fsub x, (fadd x, y)) -> (fneg y) &
6244   //    (fsub x, (fadd y, x)) -> (fneg y)
6245   if (DAG.getTarget().Options.UnsafeFPMath) {
6246     if (N0 == N1)
6247       return DAG.getConstantFP(0.0f, VT);
6248
6249     if (N1.getOpcode() == ISD::FADD) {
6250       SDValue N10 = N1->getOperand(0);
6251       SDValue N11 = N1->getOperand(1);
6252
6253       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6254                                           &DAG.getTarget().Options))
6255         return GetNegatedExpression(N11, DAG, LegalOperations);
6256
6257       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6258                                           &DAG.getTarget().Options))
6259         return GetNegatedExpression(N10, DAG, LegalOperations);
6260     }
6261   }
6262
6263   // FSUB -> FMA combines:
6264   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6265        DAG.getTarget().Options.UnsafeFPMath) &&
6266       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6267       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6268
6269     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6270     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6271       return DAG.getNode(ISD::FMA, dl, VT,
6272                          N0.getOperand(0), N0.getOperand(1),
6273                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6274
6275     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6276     // Note: Commutes FSUB operands.
6277     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6278       return DAG.getNode(ISD::FMA, dl, VT,
6279                          DAG.getNode(ISD::FNEG, dl, VT,
6280                          N1.getOperand(0)),
6281                          N1.getOperand(1), N0);
6282
6283     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6284     if (N0.getOpcode() == ISD::FNEG &&
6285         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6286         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6287       SDValue N00 = N0.getOperand(0).getOperand(0);
6288       SDValue N01 = N0.getOperand(0).getOperand(1);
6289       return DAG.getNode(ISD::FMA, dl, VT,
6290                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6291                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6292     }
6293   }
6294
6295   return SDValue();
6296 }
6297
6298 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6299   SDValue N0 = N->getOperand(0);
6300   SDValue N1 = N->getOperand(1);
6301   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6302   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6303   EVT VT = N->getValueType(0);
6304   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6305
6306   // fold vector ops
6307   if (VT.isVector()) {
6308     SDValue FoldedVOp = SimplifyVBinOp(N);
6309     if (FoldedVOp.getNode()) return FoldedVOp;
6310   }
6311
6312   // fold (fmul c1, c2) -> c1*c2
6313   if (N0CFP && N1CFP)
6314     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6315   // canonicalize constant to RHS
6316   if (N0CFP && !N1CFP)
6317     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6318   // fold (fmul A, 0) -> 0
6319   if (DAG.getTarget().Options.UnsafeFPMath &&
6320       N1CFP && N1CFP->getValueAPF().isZero())
6321     return N1;
6322   // fold (fmul A, 0) -> 0, vector edition.
6323   if (DAG.getTarget().Options.UnsafeFPMath &&
6324       ISD::isBuildVectorAllZeros(N1.getNode()))
6325     return N1;
6326   // fold (fmul A, 1.0) -> A
6327   if (N1CFP && N1CFP->isExactlyValue(1.0))
6328     return N0;
6329   // fold (fmul X, 2.0) -> (fadd X, X)
6330   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6331     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6332   // fold (fmul X, -1.0) -> (fneg X)
6333   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6334     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6335       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6336
6337   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6338   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6339                                        &DAG.getTarget().Options)) {
6340     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6341                                          &DAG.getTarget().Options)) {
6342       // Both can be negated for free, check to see if at least one is cheaper
6343       // negated.
6344       if (LHSNeg == 2 || RHSNeg == 2)
6345         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6346                            GetNegatedExpression(N0, DAG, LegalOperations),
6347                            GetNegatedExpression(N1, DAG, LegalOperations));
6348     }
6349   }
6350
6351   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6352   if (DAG.getTarget().Options.UnsafeFPMath &&
6353       N1CFP && N0.getOpcode() == ISD::FMUL &&
6354       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6355     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6356                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6357                                    N0.getOperand(1), N1));
6358
6359   return SDValue();
6360 }
6361
6362 SDValue DAGCombiner::visitFMA(SDNode *N) {
6363   SDValue N0 = N->getOperand(0);
6364   SDValue N1 = N->getOperand(1);
6365   SDValue N2 = N->getOperand(2);
6366   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6367   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6368   EVT VT = N->getValueType(0);
6369   SDLoc dl(N);
6370
6371   if (DAG.getTarget().Options.UnsafeFPMath) {
6372     if (N0CFP && N0CFP->isZero())
6373       return N2;
6374     if (N1CFP && N1CFP->isZero())
6375       return N2;
6376   }
6377   if (N0CFP && N0CFP->isExactlyValue(1.0))
6378     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6379   if (N1CFP && N1CFP->isExactlyValue(1.0))
6380     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6381
6382   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6383   if (N0CFP && !N1CFP)
6384     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6385
6386   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6387   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6388       N2.getOpcode() == ISD::FMUL &&
6389       N0 == N2.getOperand(0) &&
6390       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6391     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6392                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6393   }
6394
6395
6396   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6397   if (DAG.getTarget().Options.UnsafeFPMath &&
6398       N0.getOpcode() == ISD::FMUL && N1CFP &&
6399       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6400     return DAG.getNode(ISD::FMA, dl, VT,
6401                        N0.getOperand(0),
6402                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6403                        N2);
6404   }
6405
6406   // (fma x, 1, y) -> (fadd x, y)
6407   // (fma x, -1, y) -> (fadd (fneg x), y)
6408   if (N1CFP) {
6409     if (N1CFP->isExactlyValue(1.0))
6410       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6411
6412     if (N1CFP->isExactlyValue(-1.0) &&
6413         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6414       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6415       AddToWorkList(RHSNeg.getNode());
6416       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6417     }
6418   }
6419
6420   // (fma x, c, x) -> (fmul x, (c+1))
6421   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6422     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6423                        DAG.getNode(ISD::FADD, dl, VT,
6424                                    N1, DAG.getConstantFP(1.0, VT)));
6425
6426   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6427   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6428       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6429     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6430                        DAG.getNode(ISD::FADD, dl, VT,
6431                                    N1, DAG.getConstantFP(-1.0, VT)));
6432
6433
6434   return SDValue();
6435 }
6436
6437 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6438   SDValue N0 = N->getOperand(0);
6439   SDValue N1 = N->getOperand(1);
6440   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6441   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6442   EVT VT = N->getValueType(0);
6443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6444
6445   // fold vector ops
6446   if (VT.isVector()) {
6447     SDValue FoldedVOp = SimplifyVBinOp(N);
6448     if (FoldedVOp.getNode()) return FoldedVOp;
6449   }
6450
6451   // fold (fdiv c1, c2) -> c1/c2
6452   if (N0CFP && N1CFP)
6453     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6454
6455   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6456   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6457     // Compute the reciprocal 1.0 / c2.
6458     APFloat N1APF = N1CFP->getValueAPF();
6459     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6460     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6461     // Only do the transform if the reciprocal is a legal fp immediate that
6462     // isn't too nasty (eg NaN, denormal, ...).
6463     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6464         (!LegalOperations ||
6465          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6466          // backend)... we should handle this gracefully after Legalize.
6467          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6468          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6469          TLI.isFPImmLegal(Recip, VT)))
6470       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6471                          DAG.getConstantFP(Recip, VT));
6472   }
6473
6474   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6475   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6476                                        &DAG.getTarget().Options)) {
6477     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6478                                          &DAG.getTarget().Options)) {
6479       // Both can be negated for free, check to see if at least one is cheaper
6480       // negated.
6481       if (LHSNeg == 2 || RHSNeg == 2)
6482         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6483                            GetNegatedExpression(N0, DAG, LegalOperations),
6484                            GetNegatedExpression(N1, DAG, LegalOperations));
6485     }
6486   }
6487
6488   return SDValue();
6489 }
6490
6491 SDValue DAGCombiner::visitFREM(SDNode *N) {
6492   SDValue N0 = N->getOperand(0);
6493   SDValue N1 = N->getOperand(1);
6494   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6495   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6496   EVT VT = N->getValueType(0);
6497
6498   // fold (frem c1, c2) -> fmod(c1,c2)
6499   if (N0CFP && N1CFP)
6500     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6501
6502   return SDValue();
6503 }
6504
6505 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6506   SDValue N0 = N->getOperand(0);
6507   SDValue N1 = N->getOperand(1);
6508   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6509   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6510   EVT VT = N->getValueType(0);
6511
6512   if (N0CFP && N1CFP)  // Constant fold
6513     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6514
6515   if (N1CFP) {
6516     const APFloat& V = N1CFP->getValueAPF();
6517     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6518     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6519     if (!V.isNegative()) {
6520       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6521         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6522     } else {
6523       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6524         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6525                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6526     }
6527   }
6528
6529   // copysign(fabs(x), y) -> copysign(x, y)
6530   // copysign(fneg(x), y) -> copysign(x, y)
6531   // copysign(copysign(x,z), y) -> copysign(x, y)
6532   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6533       N0.getOpcode() == ISD::FCOPYSIGN)
6534     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6535                        N0.getOperand(0), N1);
6536
6537   // copysign(x, abs(y)) -> abs(x)
6538   if (N1.getOpcode() == ISD::FABS)
6539     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6540
6541   // copysign(x, copysign(y,z)) -> copysign(x, z)
6542   if (N1.getOpcode() == ISD::FCOPYSIGN)
6543     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6544                        N0, N1.getOperand(1));
6545
6546   // copysign(x, fp_extend(y)) -> copysign(x, y)
6547   // copysign(x, fp_round(y)) -> copysign(x, y)
6548   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6549     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6550                        N0, N1.getOperand(0));
6551
6552   return SDValue();
6553 }
6554
6555 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6556   SDValue N0 = N->getOperand(0);
6557   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6558   EVT VT = N->getValueType(0);
6559   EVT OpVT = N0.getValueType();
6560
6561   // fold (sint_to_fp c1) -> c1fp
6562   if (N0C &&
6563       // ...but only if the target supports immediate floating-point values
6564       (!LegalOperations ||
6565        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6566     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6567
6568   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6569   // but UINT_TO_FP is legal on this target, try to convert.
6570   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6571       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6572     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6573     if (DAG.SignBitIsZero(N0))
6574       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6575   }
6576
6577   // The next optimizations are desireable only if SELECT_CC can be lowered.
6578   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6579   // having to say they don't support SELECT_CC on every type the DAG knows
6580   // about, since there is no way to mark an opcode illegal at all value types
6581   // (See also visitSELECT)
6582   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6583     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6584     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6585         !VT.isVector() &&
6586         (!LegalOperations ||
6587          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6588       SDValue Ops[] =
6589         { N0.getOperand(0), N0.getOperand(1),
6590           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6591           N0.getOperand(2) };
6592       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6593     }
6594
6595     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6596     //      (select_cc x, y, 1.0, 0.0,, cc)
6597     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6598         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6599         (!LegalOperations ||
6600          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6601       SDValue Ops[] =
6602         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6603           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6604           N0.getOperand(0).getOperand(2) };
6605       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6606     }
6607   }
6608
6609   return SDValue();
6610 }
6611
6612 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6613   SDValue N0 = N->getOperand(0);
6614   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6615   EVT VT = N->getValueType(0);
6616   EVT OpVT = N0.getValueType();
6617
6618   // fold (uint_to_fp c1) -> c1fp
6619   if (N0C &&
6620       // ...but only if the target supports immediate floating-point values
6621       (!LegalOperations ||
6622        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6623     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6624
6625   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6626   // but SINT_TO_FP is legal on this target, try to convert.
6627   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6628       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6629     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6630     if (DAG.SignBitIsZero(N0))
6631       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6632   }
6633
6634   // The next optimizations are desireable only if SELECT_CC can be lowered.
6635   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6636   // having to say they don't support SELECT_CC on every type the DAG knows
6637   // about, since there is no way to mark an opcode illegal at all value types
6638   // (See also visitSELECT)
6639   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6640     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6641
6642     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6643         (!LegalOperations ||
6644          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6645       SDValue Ops[] =
6646         { N0.getOperand(0), N0.getOperand(1),
6647           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6648           N0.getOperand(2) };
6649       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6650     }
6651   }
6652
6653   return SDValue();
6654 }
6655
6656 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6657   SDValue N0 = N->getOperand(0);
6658   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6659   EVT VT = N->getValueType(0);
6660
6661   // fold (fp_to_sint c1fp) -> c1
6662   if (N0CFP)
6663     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6664
6665   return SDValue();
6666 }
6667
6668 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6669   SDValue N0 = N->getOperand(0);
6670   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6671   EVT VT = N->getValueType(0);
6672
6673   // fold (fp_to_uint c1fp) -> c1
6674   if (N0CFP)
6675     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6676
6677   return SDValue();
6678 }
6679
6680 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6681   SDValue N0 = N->getOperand(0);
6682   SDValue N1 = N->getOperand(1);
6683   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6684   EVT VT = N->getValueType(0);
6685
6686   // fold (fp_round c1fp) -> c1fp
6687   if (N0CFP)
6688     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6689
6690   // fold (fp_round (fp_extend x)) -> x
6691   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6692     return N0.getOperand(0);
6693
6694   // fold (fp_round (fp_round x)) -> (fp_round x)
6695   if (N0.getOpcode() == ISD::FP_ROUND) {
6696     // This is a value preserving truncation if both round's are.
6697     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6698                    N0.getNode()->getConstantOperandVal(1) == 1;
6699     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6700                        DAG.getIntPtrConstant(IsTrunc));
6701   }
6702
6703   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6704   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6705     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6706                               N0.getOperand(0), N1);
6707     AddToWorkList(Tmp.getNode());
6708     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6709                        Tmp, N0.getOperand(1));
6710   }
6711
6712   return SDValue();
6713 }
6714
6715 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6716   SDValue N0 = N->getOperand(0);
6717   EVT VT = N->getValueType(0);
6718   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6719   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6720
6721   // fold (fp_round_inreg c1fp) -> c1fp
6722   if (N0CFP && isTypeLegal(EVT)) {
6723     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6724     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6725   }
6726
6727   return SDValue();
6728 }
6729
6730 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6731   SDValue N0 = N->getOperand(0);
6732   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6733   EVT VT = N->getValueType(0);
6734
6735   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6736   if (N->hasOneUse() &&
6737       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6738     return SDValue();
6739
6740   // fold (fp_extend c1fp) -> c1fp
6741   if (N0CFP)
6742     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6743
6744   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6745   // value of X.
6746   if (N0.getOpcode() == ISD::FP_ROUND
6747       && N0.getNode()->getConstantOperandVal(1) == 1) {
6748     SDValue In = N0.getOperand(0);
6749     if (In.getValueType() == VT) return In;
6750     if (VT.bitsLT(In.getValueType()))
6751       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6752                          In, N0.getOperand(1));
6753     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6754   }
6755
6756   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6757   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6758       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6759        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6760     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6761     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6762                                      LN0->getChain(),
6763                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6764                                      N0.getValueType(),
6765                                      LN0->isVolatile(), LN0->isNonTemporal(),
6766                                      LN0->getAlignment());
6767     CombineTo(N, ExtLoad);
6768     CombineTo(N0.getNode(),
6769               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6770                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6771               ExtLoad.getValue(1));
6772     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6773   }
6774
6775   return SDValue();
6776 }
6777
6778 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6779   SDValue N0 = N->getOperand(0);
6780   EVT VT = N->getValueType(0);
6781
6782   if (VT.isVector()) {
6783     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6784     if (FoldedVOp.getNode()) return FoldedVOp;
6785   }
6786
6787   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6788                          &DAG.getTarget().Options))
6789     return GetNegatedExpression(N0, DAG, LegalOperations);
6790
6791   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6792   // constant pool values.
6793   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6794       !VT.isVector() &&
6795       N0.getNode()->hasOneUse() &&
6796       N0.getOperand(0).getValueType().isInteger()) {
6797     SDValue Int = N0.getOperand(0);
6798     EVT IntVT = Int.getValueType();
6799     if (IntVT.isInteger() && !IntVT.isVector()) {
6800       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6801               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6802       AddToWorkList(Int.getNode());
6803       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6804                          VT, Int);
6805     }
6806   }
6807
6808   // (fneg (fmul c, x)) -> (fmul -c, x)
6809   if (N0.getOpcode() == ISD::FMUL) {
6810     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6811     if (CFP1)
6812       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6813                          N0.getOperand(0),
6814                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6815                                      N0.getOperand(1)));
6816   }
6817
6818   return SDValue();
6819 }
6820
6821 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6822   SDValue N0 = N->getOperand(0);
6823   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6824   EVT VT = N->getValueType(0);
6825
6826   // fold (fceil c1) -> fceil(c1)
6827   if (N0CFP)
6828     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6829
6830   return SDValue();
6831 }
6832
6833 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6834   SDValue N0 = N->getOperand(0);
6835   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6836   EVT VT = N->getValueType(0);
6837
6838   // fold (ftrunc c1) -> ftrunc(c1)
6839   if (N0CFP)
6840     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6841
6842   return SDValue();
6843 }
6844
6845 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6846   SDValue N0 = N->getOperand(0);
6847   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6848   EVT VT = N->getValueType(0);
6849
6850   // fold (ffloor c1) -> ffloor(c1)
6851   if (N0CFP)
6852     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6853
6854   return SDValue();
6855 }
6856
6857 SDValue DAGCombiner::visitFABS(SDNode *N) {
6858   SDValue N0 = N->getOperand(0);
6859   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6860   EVT VT = N->getValueType(0);
6861
6862   if (VT.isVector()) {
6863     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6864     if (FoldedVOp.getNode()) return FoldedVOp;
6865   }
6866
6867   // fold (fabs c1) -> fabs(c1)
6868   if (N0CFP)
6869     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6870   // fold (fabs (fabs x)) -> (fabs x)
6871   if (N0.getOpcode() == ISD::FABS)
6872     return N->getOperand(0);
6873   // fold (fabs (fneg x)) -> (fabs x)
6874   // fold (fabs (fcopysign x, y)) -> (fabs x)
6875   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6876     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6877
6878   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6879   // constant pool values.
6880   if (!TLI.isFAbsFree(VT) &&
6881       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6882       N0.getOperand(0).getValueType().isInteger() &&
6883       !N0.getOperand(0).getValueType().isVector()) {
6884     SDValue Int = N0.getOperand(0);
6885     EVT IntVT = Int.getValueType();
6886     if (IntVT.isInteger() && !IntVT.isVector()) {
6887       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6888              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6889       AddToWorkList(Int.getNode());
6890       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6891                          N->getValueType(0), Int);
6892     }
6893   }
6894
6895   return SDValue();
6896 }
6897
6898 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6899   SDValue Chain = N->getOperand(0);
6900   SDValue N1 = N->getOperand(1);
6901   SDValue N2 = N->getOperand(2);
6902
6903   // If N is a constant we could fold this into a fallthrough or unconditional
6904   // branch. However that doesn't happen very often in normal code, because
6905   // Instcombine/SimplifyCFG should have handled the available opportunities.
6906   // If we did this folding here, it would be necessary to update the
6907   // MachineBasicBlock CFG, which is awkward.
6908
6909   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6910   // on the target.
6911   if (N1.getOpcode() == ISD::SETCC &&
6912       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6913                                    N1.getOperand(0).getValueType())) {
6914     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6915                        Chain, N1.getOperand(2),
6916                        N1.getOperand(0), N1.getOperand(1), N2);
6917   }
6918
6919   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6920       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6921        (N1.getOperand(0).hasOneUse() &&
6922         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6923     SDNode *Trunc = 0;
6924     if (N1.getOpcode() == ISD::TRUNCATE) {
6925       // Look pass the truncate.
6926       Trunc = N1.getNode();
6927       N1 = N1.getOperand(0);
6928     }
6929
6930     // Match this pattern so that we can generate simpler code:
6931     //
6932     //   %a = ...
6933     //   %b = and i32 %a, 2
6934     //   %c = srl i32 %b, 1
6935     //   brcond i32 %c ...
6936     //
6937     // into
6938     //
6939     //   %a = ...
6940     //   %b = and i32 %a, 2
6941     //   %c = setcc eq %b, 0
6942     //   brcond %c ...
6943     //
6944     // This applies only when the AND constant value has one bit set and the
6945     // SRL constant is equal to the log2 of the AND constant. The back-end is
6946     // smart enough to convert the result into a TEST/JMP sequence.
6947     SDValue Op0 = N1.getOperand(0);
6948     SDValue Op1 = N1.getOperand(1);
6949
6950     if (Op0.getOpcode() == ISD::AND &&
6951         Op1.getOpcode() == ISD::Constant) {
6952       SDValue AndOp1 = Op0.getOperand(1);
6953
6954       if (AndOp1.getOpcode() == ISD::Constant) {
6955         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6956
6957         if (AndConst.isPowerOf2() &&
6958             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6959           SDValue SetCC =
6960             DAG.getSetCC(SDLoc(N),
6961                          getSetCCResultType(Op0.getValueType()),
6962                          Op0, DAG.getConstant(0, Op0.getValueType()),
6963                          ISD::SETNE);
6964
6965           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6966                                           MVT::Other, Chain, SetCC, N2);
6967           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6968           // will convert it back to (X & C1) >> C2.
6969           CombineTo(N, NewBRCond, false);
6970           // Truncate is dead.
6971           if (Trunc) {
6972             removeFromWorkList(Trunc);
6973             DAG.DeleteNode(Trunc);
6974           }
6975           // Replace the uses of SRL with SETCC
6976           WorkListRemover DeadNodes(*this);
6977           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6978           removeFromWorkList(N1.getNode());
6979           DAG.DeleteNode(N1.getNode());
6980           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6981         }
6982       }
6983     }
6984
6985     if (Trunc)
6986       // Restore N1 if the above transformation doesn't match.
6987       N1 = N->getOperand(1);
6988   }
6989
6990   // Transform br(xor(x, y)) -> br(x != y)
6991   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6992   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6993     SDNode *TheXor = N1.getNode();
6994     SDValue Op0 = TheXor->getOperand(0);
6995     SDValue Op1 = TheXor->getOperand(1);
6996     if (Op0.getOpcode() == Op1.getOpcode()) {
6997       // Avoid missing important xor optimizations.
6998       SDValue Tmp = visitXOR(TheXor);
6999       if (Tmp.getNode()) {
7000         if (Tmp.getNode() != TheXor) {
7001           DEBUG(dbgs() << "\nReplacing.8 ";
7002                 TheXor->dump(&DAG);
7003                 dbgs() << "\nWith: ";
7004                 Tmp.getNode()->dump(&DAG);
7005                 dbgs() << '\n');
7006           WorkListRemover DeadNodes(*this);
7007           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7008           removeFromWorkList(TheXor);
7009           DAG.DeleteNode(TheXor);
7010           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7011                              MVT::Other, Chain, Tmp, N2);
7012         }
7013
7014         // visitXOR has changed XOR's operands or replaced the XOR completely,
7015         // bail out.
7016         return SDValue(N, 0);
7017       }
7018     }
7019
7020     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7021       bool Equal = false;
7022       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7023         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7024             Op0.getOpcode() == ISD::XOR) {
7025           TheXor = Op0.getNode();
7026           Equal = true;
7027         }
7028
7029       EVT SetCCVT = N1.getValueType();
7030       if (LegalTypes)
7031         SetCCVT = getSetCCResultType(SetCCVT);
7032       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7033                                    SetCCVT,
7034                                    Op0, Op1,
7035                                    Equal ? ISD::SETEQ : ISD::SETNE);
7036       // Replace the uses of XOR with SETCC
7037       WorkListRemover DeadNodes(*this);
7038       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7039       removeFromWorkList(N1.getNode());
7040       DAG.DeleteNode(N1.getNode());
7041       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7042                          MVT::Other, Chain, SetCC, N2);
7043     }
7044   }
7045
7046   return SDValue();
7047 }
7048
7049 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7050 //
7051 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7052   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7053   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7054
7055   // If N is a constant we could fold this into a fallthrough or unconditional
7056   // branch. However that doesn't happen very often in normal code, because
7057   // Instcombine/SimplifyCFG should have handled the available opportunities.
7058   // If we did this folding here, it would be necessary to update the
7059   // MachineBasicBlock CFG, which is awkward.
7060
7061   // Use SimplifySetCC to simplify SETCC's.
7062   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7063                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7064                                false);
7065   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7066
7067   // fold to a simpler setcc
7068   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7069     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7070                        N->getOperand(0), Simp.getOperand(2),
7071                        Simp.getOperand(0), Simp.getOperand(1),
7072                        N->getOperand(4));
7073
7074   return SDValue();
7075 }
7076
7077 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7078 /// uses N as its base pointer and that N may be folded in the load / store
7079 /// addressing mode.
7080 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7081                                     SelectionDAG &DAG,
7082                                     const TargetLowering &TLI) {
7083   EVT VT;
7084   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7085     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7086       return false;
7087     VT = Use->getValueType(0);
7088   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7089     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7090       return false;
7091     VT = ST->getValue().getValueType();
7092   } else
7093     return false;
7094
7095   TargetLowering::AddrMode AM;
7096   if (N->getOpcode() == ISD::ADD) {
7097     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7098     if (Offset)
7099       // [reg +/- imm]
7100       AM.BaseOffs = Offset->getSExtValue();
7101     else
7102       // [reg +/- reg]
7103       AM.Scale = 1;
7104   } else if (N->getOpcode() == ISD::SUB) {
7105     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7106     if (Offset)
7107       // [reg +/- imm]
7108       AM.BaseOffs = -Offset->getSExtValue();
7109     else
7110       // [reg +/- reg]
7111       AM.Scale = 1;
7112   } else
7113     return false;
7114
7115   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7116 }
7117
7118 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7119 /// pre-indexed load / store when the base pointer is an add or subtract
7120 /// and it has other uses besides the load / store. After the
7121 /// transformation, the new indexed load / store has effectively folded
7122 /// the add / subtract in and all of its other uses are redirected to the
7123 /// new load / store.
7124 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7125   if (Level < AfterLegalizeDAG)
7126     return false;
7127
7128   bool isLoad = true;
7129   SDValue Ptr;
7130   EVT VT;
7131   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7132     if (LD->isIndexed())
7133       return false;
7134     VT = LD->getMemoryVT();
7135     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7136         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7137       return false;
7138     Ptr = LD->getBasePtr();
7139   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7140     if (ST->isIndexed())
7141       return false;
7142     VT = ST->getMemoryVT();
7143     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7144         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7145       return false;
7146     Ptr = ST->getBasePtr();
7147     isLoad = false;
7148   } else {
7149     return false;
7150   }
7151
7152   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7153   // out.  There is no reason to make this a preinc/predec.
7154   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7155       Ptr.getNode()->hasOneUse())
7156     return false;
7157
7158   // Ask the target to do addressing mode selection.
7159   SDValue BasePtr;
7160   SDValue Offset;
7161   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7162   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7163     return false;
7164
7165   // Backends without true r+i pre-indexed forms may need to pass a
7166   // constant base with a variable offset so that constant coercion
7167   // will work with the patterns in canonical form.
7168   bool Swapped = false;
7169   if (isa<ConstantSDNode>(BasePtr)) {
7170     std::swap(BasePtr, Offset);
7171     Swapped = true;
7172   }
7173
7174   // Don't create a indexed load / store with zero offset.
7175   if (isa<ConstantSDNode>(Offset) &&
7176       cast<ConstantSDNode>(Offset)->isNullValue())
7177     return false;
7178
7179   // Try turning it into a pre-indexed load / store except when:
7180   // 1) The new base ptr is a frame index.
7181   // 2) If N is a store and the new base ptr is either the same as or is a
7182   //    predecessor of the value being stored.
7183   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7184   //    that would create a cycle.
7185   // 4) All uses are load / store ops that use it as old base ptr.
7186
7187   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7188   // (plus the implicit offset) to a register to preinc anyway.
7189   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7190     return false;
7191
7192   // Check #2.
7193   if (!isLoad) {
7194     SDValue Val = cast<StoreSDNode>(N)->getValue();
7195     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7196       return false;
7197   }
7198
7199   // If the offset is a constant, there may be other adds of constants that
7200   // can be folded with this one. We should do this to avoid having to keep
7201   // a copy of the original base pointer.
7202   SmallVector<SDNode *, 16> OtherUses;
7203   if (isa<ConstantSDNode>(Offset))
7204     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7205          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7206       SDNode *Use = *I;
7207       if (Use == Ptr.getNode())
7208         continue;
7209
7210       if (Use->isPredecessorOf(N))
7211         continue;
7212
7213       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7214         OtherUses.clear();
7215         break;
7216       }
7217
7218       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7219       if (Op1.getNode() == BasePtr.getNode())
7220         std::swap(Op0, Op1);
7221       assert(Op0.getNode() == BasePtr.getNode() &&
7222              "Use of ADD/SUB but not an operand");
7223
7224       if (!isa<ConstantSDNode>(Op1)) {
7225         OtherUses.clear();
7226         break;
7227       }
7228
7229       // FIXME: In some cases, we can be smarter about this.
7230       if (Op1.getValueType() != Offset.getValueType()) {
7231         OtherUses.clear();
7232         break;
7233       }
7234
7235       OtherUses.push_back(Use);
7236     }
7237
7238   if (Swapped)
7239     std::swap(BasePtr, Offset);
7240
7241   // Now check for #3 and #4.
7242   bool RealUse = false;
7243
7244   // Caches for hasPredecessorHelper
7245   SmallPtrSet<const SDNode *, 32> Visited;
7246   SmallVector<const SDNode *, 16> Worklist;
7247
7248   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7249          E = Ptr.getNode()->use_end(); I != E; ++I) {
7250     SDNode *Use = *I;
7251     if (Use == N)
7252       continue;
7253     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7254       return false;
7255
7256     // If Ptr may be folded in addressing mode of other use, then it's
7257     // not profitable to do this transformation.
7258     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7259       RealUse = true;
7260   }
7261
7262   if (!RealUse)
7263     return false;
7264
7265   SDValue Result;
7266   if (isLoad)
7267     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7268                                 BasePtr, Offset, AM);
7269   else
7270     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7271                                  BasePtr, Offset, AM);
7272   ++PreIndexedNodes;
7273   ++NodesCombined;
7274   DEBUG(dbgs() << "\nReplacing.4 ";
7275         N->dump(&DAG);
7276         dbgs() << "\nWith: ";
7277         Result.getNode()->dump(&DAG);
7278         dbgs() << '\n');
7279   WorkListRemover DeadNodes(*this);
7280   if (isLoad) {
7281     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7282     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7283   } else {
7284     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7285   }
7286
7287   // Finally, since the node is now dead, remove it from the graph.
7288   DAG.DeleteNode(N);
7289
7290   if (Swapped)
7291     std::swap(BasePtr, Offset);
7292
7293   // Replace other uses of BasePtr that can be updated to use Ptr
7294   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7295     unsigned OffsetIdx = 1;
7296     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7297       OffsetIdx = 0;
7298     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7299            BasePtr.getNode() && "Expected BasePtr operand");
7300
7301     // We need to replace ptr0 in the following expression:
7302     //   x0 * offset0 + y0 * ptr0 = t0
7303     // knowing that
7304     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7305     //
7306     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7307     // indexed load/store and the expresion that needs to be re-written.
7308     //
7309     // Therefore, we have:
7310     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7311
7312     ConstantSDNode *CN =
7313       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7314     int X0, X1, Y0, Y1;
7315     APInt Offset0 = CN->getAPIntValue();
7316     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7317
7318     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7319     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7320     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7321     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7322
7323     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7324
7325     APInt CNV = Offset0;
7326     if (X0 < 0) CNV = -CNV;
7327     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7328     else CNV = CNV - Offset1;
7329
7330     // We can now generate the new expression.
7331     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7332     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7333
7334     SDValue NewUse = DAG.getNode(Opcode,
7335                                  SDLoc(OtherUses[i]),
7336                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7337     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7338     removeFromWorkList(OtherUses[i]);
7339     DAG.DeleteNode(OtherUses[i]);
7340   }
7341
7342   // Replace the uses of Ptr with uses of the updated base value.
7343   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7344   removeFromWorkList(Ptr.getNode());
7345   DAG.DeleteNode(Ptr.getNode());
7346
7347   return true;
7348 }
7349
7350 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7351 /// add / sub of the base pointer node into a post-indexed load / store.
7352 /// The transformation folded the add / subtract into the new indexed
7353 /// load / store effectively and all of its uses are redirected to the
7354 /// new load / store.
7355 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7356   if (Level < AfterLegalizeDAG)
7357     return false;
7358
7359   bool isLoad = true;
7360   SDValue Ptr;
7361   EVT VT;
7362   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7363     if (LD->isIndexed())
7364       return false;
7365     VT = LD->getMemoryVT();
7366     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7367         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7368       return false;
7369     Ptr = LD->getBasePtr();
7370   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7371     if (ST->isIndexed())
7372       return false;
7373     VT = ST->getMemoryVT();
7374     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7375         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7376       return false;
7377     Ptr = ST->getBasePtr();
7378     isLoad = false;
7379   } else {
7380     return false;
7381   }
7382
7383   if (Ptr.getNode()->hasOneUse())
7384     return false;
7385
7386   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7387          E = Ptr.getNode()->use_end(); I != E; ++I) {
7388     SDNode *Op = *I;
7389     if (Op == N ||
7390         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7391       continue;
7392
7393     SDValue BasePtr;
7394     SDValue Offset;
7395     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7396     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7397       // Don't create a indexed load / store with zero offset.
7398       if (isa<ConstantSDNode>(Offset) &&
7399           cast<ConstantSDNode>(Offset)->isNullValue())
7400         continue;
7401
7402       // Try turning it into a post-indexed load / store except when
7403       // 1) All uses are load / store ops that use it as base ptr (and
7404       //    it may be folded as addressing mmode).
7405       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7406       //    nor a successor of N. Otherwise, if Op is folded that would
7407       //    create a cycle.
7408
7409       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7410         continue;
7411
7412       // Check for #1.
7413       bool TryNext = false;
7414       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7415              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7416         SDNode *Use = *II;
7417         if (Use == Ptr.getNode())
7418           continue;
7419
7420         // If all the uses are load / store addresses, then don't do the
7421         // transformation.
7422         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7423           bool RealUse = false;
7424           for (SDNode::use_iterator III = Use->use_begin(),
7425                  EEE = Use->use_end(); III != EEE; ++III) {
7426             SDNode *UseUse = *III;
7427             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7428               RealUse = true;
7429           }
7430
7431           if (!RealUse) {
7432             TryNext = true;
7433             break;
7434           }
7435         }
7436       }
7437
7438       if (TryNext)
7439         continue;
7440
7441       // Check for #2
7442       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7443         SDValue Result = isLoad
7444           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7445                                BasePtr, Offset, AM)
7446           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7447                                 BasePtr, Offset, AM);
7448         ++PostIndexedNodes;
7449         ++NodesCombined;
7450         DEBUG(dbgs() << "\nReplacing.5 ";
7451               N->dump(&DAG);
7452               dbgs() << "\nWith: ";
7453               Result.getNode()->dump(&DAG);
7454               dbgs() << '\n');
7455         WorkListRemover DeadNodes(*this);
7456         if (isLoad) {
7457           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7458           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7459         } else {
7460           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7461         }
7462
7463         // Finally, since the node is now dead, remove it from the graph.
7464         DAG.DeleteNode(N);
7465
7466         // Replace the uses of Use with uses of the updated base value.
7467         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7468                                       Result.getValue(isLoad ? 1 : 0));
7469         removeFromWorkList(Op);
7470         DAG.DeleteNode(Op);
7471         return true;
7472       }
7473     }
7474   }
7475
7476   return false;
7477 }
7478
7479 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7480   LoadSDNode *LD  = cast<LoadSDNode>(N);
7481   SDValue Chain = LD->getChain();
7482   SDValue Ptr   = LD->getBasePtr();
7483
7484   // If load is not volatile and there are no uses of the loaded value (and
7485   // the updated indexed value in case of indexed loads), change uses of the
7486   // chain value into uses of the chain input (i.e. delete the dead load).
7487   if (!LD->isVolatile()) {
7488     if (N->getValueType(1) == MVT::Other) {
7489       // Unindexed loads.
7490       if (!N->hasAnyUseOfValue(0)) {
7491         // It's not safe to use the two value CombineTo variant here. e.g.
7492         // v1, chain2 = load chain1, loc
7493         // v2, chain3 = load chain2, loc
7494         // v3         = add v2, c
7495         // Now we replace use of chain2 with chain1.  This makes the second load
7496         // isomorphic to the one we are deleting, and thus makes this load live.
7497         DEBUG(dbgs() << "\nReplacing.6 ";
7498               N->dump(&DAG);
7499               dbgs() << "\nWith chain: ";
7500               Chain.getNode()->dump(&DAG);
7501               dbgs() << "\n");
7502         WorkListRemover DeadNodes(*this);
7503         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7504
7505         if (N->use_empty()) {
7506           removeFromWorkList(N);
7507           DAG.DeleteNode(N);
7508         }
7509
7510         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7511       }
7512     } else {
7513       // Indexed loads.
7514       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7515       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7516         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7517         DEBUG(dbgs() << "\nReplacing.7 ";
7518               N->dump(&DAG);
7519               dbgs() << "\nWith: ";
7520               Undef.getNode()->dump(&DAG);
7521               dbgs() << " and 2 other values\n");
7522         WorkListRemover DeadNodes(*this);
7523         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7524         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7525                                       DAG.getUNDEF(N->getValueType(1)));
7526         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7527         removeFromWorkList(N);
7528         DAG.DeleteNode(N);
7529         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7530       }
7531     }
7532   }
7533
7534   // If this load is directly stored, replace the load value with the stored
7535   // value.
7536   // TODO: Handle store large -> read small portion.
7537   // TODO: Handle TRUNCSTORE/LOADEXT
7538   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7539     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7540       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7541       if (PrevST->getBasePtr() == Ptr &&
7542           PrevST->getValue().getValueType() == N->getValueType(0))
7543       return CombineTo(N, Chain.getOperand(1), Chain);
7544     }
7545   }
7546
7547   // Try to infer better alignment information than the load already has.
7548   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7549     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7550       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7551         SDValue NewLoad =
7552                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7553                               LD->getValueType(0),
7554                               Chain, Ptr, LD->getPointerInfo(),
7555                               LD->getMemoryVT(),
7556                               LD->isVolatile(), LD->isNonTemporal(), Align);
7557         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7558       }
7559     }
7560   }
7561
7562   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7563     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7564   if (UseAA) {
7565     // Walk up chain skipping non-aliasing memory nodes.
7566     SDValue BetterChain = FindBetterChain(N, Chain);
7567
7568     // If there is a better chain.
7569     if (Chain != BetterChain) {
7570       SDValue ReplLoad;
7571
7572       // Replace the chain to void dependency.
7573       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7574         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7575                                BetterChain, Ptr, LD->getPointerInfo(),
7576                                LD->isVolatile(), LD->isNonTemporal(),
7577                                LD->isInvariant(), LD->getAlignment());
7578       } else {
7579         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7580                                   LD->getValueType(0),
7581                                   BetterChain, Ptr, LD->getPointerInfo(),
7582                                   LD->getMemoryVT(),
7583                                   LD->isVolatile(),
7584                                   LD->isNonTemporal(),
7585                                   LD->getAlignment());
7586       }
7587
7588       // Create token factor to keep old chain connected.
7589       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7590                                   MVT::Other, Chain, ReplLoad.getValue(1));
7591
7592       // Make sure the new and old chains are cleaned up.
7593       AddToWorkList(Token.getNode());
7594
7595       // Replace uses with load result and token factor. Don't add users
7596       // to work list.
7597       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7598     }
7599   }
7600
7601   // Try transforming N to an indexed load.
7602   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7603     return SDValue(N, 0);
7604
7605   // Try to slice up N to more direct loads if the slices are mapped to
7606   // different register banks or pairing can take place.
7607   if (SliceUpLoad(N))
7608     return SDValue(N, 0);
7609
7610   return SDValue();
7611 }
7612
7613 namespace {
7614 /// \brief Helper structure used to slice a load in smaller loads.
7615 /// Basically a slice is obtained from the following sequence:
7616 /// Origin = load Ty1, Base
7617 /// Shift = srl Ty1 Origin, CstTy Amount
7618 /// Inst = trunc Shift to Ty2
7619 ///
7620 /// Then, it will be rewriten into:
7621 /// Slice = load SliceTy, Base + SliceOffset
7622 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7623 ///
7624 /// SliceTy is deduced from the number of bits that are actually used to
7625 /// build Inst.
7626 struct LoadedSlice {
7627   /// \brief Helper structure used to compute the cost of a slice.
7628   struct Cost {
7629     /// Are we optimizing for code size.
7630     bool ForCodeSize;
7631     /// Various cost.
7632     unsigned Loads;
7633     unsigned Truncates;
7634     unsigned CrossRegisterBanksCopies;
7635     unsigned ZExts;
7636     unsigned Shift;
7637
7638     Cost(bool ForCodeSize = false)
7639         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7640           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7641
7642     /// \brief Get the cost of one isolated slice.
7643     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7644         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7645           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7646       EVT TruncType = LS.Inst->getValueType(0);
7647       EVT LoadedType = LS.getLoadedType();
7648       if (TruncType != LoadedType &&
7649           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7650         ZExts = 1;
7651     }
7652
7653     /// \brief Account for slicing gain in the current cost.
7654     /// Slicing provide a few gains like removing a shift or a
7655     /// truncate. This method allows to grow the cost of the original
7656     /// load with the gain from this slice.
7657     void addSliceGain(const LoadedSlice &LS) {
7658       // Each slice saves a truncate.
7659       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7660       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7661                               LS.Inst->getOperand(0).getValueType()))
7662         ++Truncates;
7663       // If there is a shift amount, this slice gets rid of it.
7664       if (LS.Shift)
7665         ++Shift;
7666       // If this slice can merge a cross register bank copy, account for it.
7667       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7668         ++CrossRegisterBanksCopies;
7669     }
7670
7671     Cost &operator+=(const Cost &RHS) {
7672       Loads += RHS.Loads;
7673       Truncates += RHS.Truncates;
7674       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7675       ZExts += RHS.ZExts;
7676       Shift += RHS.Shift;
7677       return *this;
7678     }
7679
7680     bool operator==(const Cost &RHS) const {
7681       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7682              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7683              ZExts == RHS.ZExts && Shift == RHS.Shift;
7684     }
7685
7686     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7687
7688     bool operator<(const Cost &RHS) const {
7689       // Assume cross register banks copies are as expensive as loads.
7690       // FIXME: Do we want some more target hooks?
7691       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7692       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7693       // Unless we are optimizing for code size, consider the
7694       // expensive operation first.
7695       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7696         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7697       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7698              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7699     }
7700
7701     bool operator>(const Cost &RHS) const { return RHS < *this; }
7702
7703     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7704
7705     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7706   };
7707   // The last instruction that represent the slice. This should be a
7708   // truncate instruction.
7709   SDNode *Inst;
7710   // The original load instruction.
7711   LoadSDNode *Origin;
7712   // The right shift amount in bits from the original load.
7713   unsigned Shift;
7714   // The DAG from which Origin came from.
7715   // This is used to get some contextual information about legal types, etc.
7716   SelectionDAG *DAG;
7717
7718   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7719               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7720       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7721
7722   LoadedSlice(const LoadedSlice &LS)
7723       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7724
7725   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7726   /// \return Result is \p BitWidth and has used bits set to 1 and
7727   ///         not used bits set to 0.
7728   APInt getUsedBits() const {
7729     // Reproduce the trunc(lshr) sequence:
7730     // - Start from the truncated value.
7731     // - Zero extend to the desired bit width.
7732     // - Shift left.
7733     assert(Origin && "No original load to compare against.");
7734     unsigned BitWidth = Origin->getValueSizeInBits(0);
7735     assert(Inst && "This slice is not bound to an instruction");
7736     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7737            "Extracted slice is bigger than the whole type!");
7738     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7739     UsedBits.setAllBits();
7740     UsedBits = UsedBits.zext(BitWidth);
7741     UsedBits <<= Shift;
7742     return UsedBits;
7743   }
7744
7745   /// \brief Get the size of the slice to be loaded in bytes.
7746   unsigned getLoadedSize() const {
7747     unsigned SliceSize = getUsedBits().countPopulation();
7748     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7749     return SliceSize / 8;
7750   }
7751
7752   /// \brief Get the type that will be loaded for this slice.
7753   /// Note: This may not be the final type for the slice.
7754   EVT getLoadedType() const {
7755     assert(DAG && "Missing context");
7756     LLVMContext &Ctxt = *DAG->getContext();
7757     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7758   }
7759
7760   /// \brief Get the alignment of the load used for this slice.
7761   unsigned getAlignment() const {
7762     unsigned Alignment = Origin->getAlignment();
7763     unsigned Offset = getOffsetFromBase();
7764     if (Offset != 0)
7765       Alignment = MinAlign(Alignment, Alignment + Offset);
7766     return Alignment;
7767   }
7768
7769   /// \brief Check if this slice can be rewritten with legal operations.
7770   bool isLegal() const {
7771     // An invalid slice is not legal.
7772     if (!Origin || !Inst || !DAG)
7773       return false;
7774
7775     // Offsets are for indexed load only, we do not handle that.
7776     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7777       return false;
7778
7779     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7780
7781     // Check that the type is legal.
7782     EVT SliceType = getLoadedType();
7783     if (!TLI.isTypeLegal(SliceType))
7784       return false;
7785
7786     // Check that the load is legal for this type.
7787     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7788       return false;
7789
7790     // Check that the offset can be computed.
7791     // 1. Check its type.
7792     EVT PtrType = Origin->getBasePtr().getValueType();
7793     if (PtrType == MVT::Untyped || PtrType.isExtended())
7794       return false;
7795
7796     // 2. Check that it fits in the immediate.
7797     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7798       return false;
7799
7800     // 3. Check that the computation is legal.
7801     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7802       return false;
7803
7804     // Check that the zext is legal if it needs one.
7805     EVT TruncateType = Inst->getValueType(0);
7806     if (TruncateType != SliceType &&
7807         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7808       return false;
7809
7810     return true;
7811   }
7812
7813   /// \brief Get the offset in bytes of this slice in the original chunk of
7814   /// bits.
7815   /// \pre DAG != NULL.
7816   uint64_t getOffsetFromBase() const {
7817     assert(DAG && "Missing context.");
7818     bool IsBigEndian =
7819         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7820     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7821     uint64_t Offset = Shift / 8;
7822     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7823     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7824            "The size of the original loaded type is not a multiple of a"
7825            " byte.");
7826     // If Offset is bigger than TySizeInBytes, it means we are loading all
7827     // zeros. This should have been optimized before in the process.
7828     assert(TySizeInBytes > Offset &&
7829            "Invalid shift amount for given loaded size");
7830     if (IsBigEndian)
7831       Offset = TySizeInBytes - Offset - getLoadedSize();
7832     return Offset;
7833   }
7834
7835   /// \brief Generate the sequence of instructions to load the slice
7836   /// represented by this object and redirect the uses of this slice to
7837   /// this new sequence of instructions.
7838   /// \pre this->Inst && this->Origin are valid Instructions and this
7839   /// object passed the legal check: LoadedSlice::isLegal returned true.
7840   /// \return The last instruction of the sequence used to load the slice.
7841   SDValue loadSlice() const {
7842     assert(Inst && Origin && "Unable to replace a non-existing slice.");
7843     const SDValue &OldBaseAddr = Origin->getBasePtr();
7844     SDValue BaseAddr = OldBaseAddr;
7845     // Get the offset in that chunk of bytes w.r.t. the endianess.
7846     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7847     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7848     if (Offset) {
7849       // BaseAddr = BaseAddr + Offset.
7850       EVT ArithType = BaseAddr.getValueType();
7851       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7852                               DAG->getConstant(Offset, ArithType));
7853     }
7854
7855     // Create the type of the loaded slice according to its size.
7856     EVT SliceType = getLoadedType();
7857
7858     // Create the load for the slice.
7859     SDValue LastInst = DAG->getLoad(
7860         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7861         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7862         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7863     // If the final type is not the same as the loaded type, this means that
7864     // we have to pad with zero. Create a zero extend for that.
7865     EVT FinalType = Inst->getValueType(0);
7866     if (SliceType != FinalType)
7867       LastInst =
7868           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7869     return LastInst;
7870   }
7871
7872   /// \brief Check if this slice can be merged with an expensive cross register
7873   /// bank copy. E.g.,
7874   /// i = load i32
7875   /// f = bitcast i32 i to float
7876   bool canMergeExpensiveCrossRegisterBankCopy() const {
7877     if (!Inst || !Inst->hasOneUse())
7878       return false;
7879     SDNode *Use = *Inst->use_begin();
7880     if (Use->getOpcode() != ISD::BITCAST)
7881       return false;
7882     assert(DAG && "Missing context");
7883     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7884     EVT ResVT = Use->getValueType(0);
7885     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7886     const TargetRegisterClass *ArgRC =
7887         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7888     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7889       return false;
7890
7891     // At this point, we know that we perform a cross-register-bank copy.
7892     // Check if it is expensive.
7893     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7894     // Assume bitcasts are cheap, unless both register classes do not
7895     // explicitly share a common sub class.
7896     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7897       return false;
7898
7899     // Check if it will be merged with the load.
7900     // 1. Check the alignment constraint.
7901     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7902         ResVT.getTypeForEVT(*DAG->getContext()));
7903
7904     if (RequiredAlignment > getAlignment())
7905       return false;
7906
7907     // 2. Check that the load is a legal operation for that type.
7908     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7909       return false;
7910
7911     // 3. Check that we do not have a zext in the way.
7912     if (Inst->getValueType(0) != getLoadedType())
7913       return false;
7914
7915     return true;
7916   }
7917 };
7918 }
7919
7920 /// \brief Sorts LoadedSlice according to their offset.
7921 struct LoadedSliceSorter {
7922   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7923     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7924     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7925   }
7926 };
7927
7928 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7929 /// \p UsedBits looks like 0..0 1..1 0..0.
7930 static bool areUsedBitsDense(const APInt &UsedBits) {
7931   // If all the bits are one, this is dense!
7932   if (UsedBits.isAllOnesValue())
7933     return true;
7934
7935   // Get rid of the unused bits on the right.
7936   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7937   // Get rid of the unused bits on the left.
7938   if (NarrowedUsedBits.countLeadingZeros())
7939     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7940   // Check that the chunk of bits is completely used.
7941   return NarrowedUsedBits.isAllOnesValue();
7942 }
7943
7944 /// \brief Check whether or not \p First and \p Second are next to each other
7945 /// in memory. This means that there is no hole between the bits loaded
7946 /// by \p First and the bits loaded by \p Second.
7947 static bool areSlicesNextToEachOther(const LoadedSlice &First,
7948                                      const LoadedSlice &Second) {
7949   assert(First.Origin == Second.Origin && First.Origin &&
7950          "Unable to match different memory origins.");
7951   APInt UsedBits = First.getUsedBits();
7952   assert((UsedBits & Second.getUsedBits()) == 0 &&
7953          "Slices are not supposed to overlap.");
7954   UsedBits |= Second.getUsedBits();
7955   return areUsedBitsDense(UsedBits);
7956 }
7957
7958 /// \brief Adjust the \p GlobalLSCost according to the target
7959 /// paring capabilities and the layout of the slices.
7960 /// \pre \p GlobalLSCost should account for at least as many loads as
7961 /// there is in the slices in \p LoadedSlices.
7962 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7963                                  LoadedSlice::Cost &GlobalLSCost) {
7964   unsigned NumberOfSlices = LoadedSlices.size();
7965   // If there is less than 2 elements, no pairing is possible.
7966   if (NumberOfSlices < 2)
7967     return;
7968
7969   // Sort the slices so that elements that are likely to be next to each
7970   // other in memory are next to each other in the list.
7971   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
7972   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
7973   // First (resp. Second) is the first (resp. Second) potentially candidate
7974   // to be placed in a paired load.
7975   const LoadedSlice *First = NULL;
7976   const LoadedSlice *Second = NULL;
7977   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
7978                 // Set the beginning of the pair.
7979                                                            First = Second) {
7980
7981     Second = &LoadedSlices[CurrSlice];
7982
7983     // If First is NULL, it means we start a new pair.
7984     // Get to the next slice.
7985     if (!First)
7986       continue;
7987
7988     EVT LoadedType = First->getLoadedType();
7989
7990     // If the types of the slices are different, we cannot pair them.
7991     if (LoadedType != Second->getLoadedType())
7992       continue;
7993
7994     // Check if the target supplies paired loads for this type.
7995     unsigned RequiredAlignment = 0;
7996     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
7997       // move to the next pair, this type is hopeless.
7998       Second = NULL;
7999       continue;
8000     }
8001     // Check if we meet the alignment requirement.
8002     if (RequiredAlignment > First->getAlignment())
8003       continue;
8004
8005     // Check that both loads are next to each other in memory.
8006     if (!areSlicesNextToEachOther(*First, *Second))
8007       continue;
8008
8009     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8010     --GlobalLSCost.Loads;
8011     // Move to the next pair.
8012     Second = NULL;
8013   }
8014 }
8015
8016 /// \brief Check the profitability of all involved LoadedSlice.
8017 /// Currently, it is considered profitable if there is exactly two
8018 /// involved slices (1) which are (2) next to each other in memory, and
8019 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8020 ///
8021 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8022 /// the elements themselves.
8023 ///
8024 /// FIXME: When the cost model will be mature enough, we can relax
8025 /// constraints (1) and (2).
8026 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8027                                 const APInt &UsedBits, bool ForCodeSize) {
8028   unsigned NumberOfSlices = LoadedSlices.size();
8029   if (StressLoadSlicing)
8030     return NumberOfSlices > 1;
8031
8032   // Check (1).
8033   if (NumberOfSlices != 2)
8034     return false;
8035
8036   // Check (2).
8037   if (!areUsedBitsDense(UsedBits))
8038     return false;
8039
8040   // Check (3).
8041   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8042   // The original code has one big load.
8043   OrigCost.Loads = 1;
8044   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8045     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8046     // Accumulate the cost of all the slices.
8047     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8048     GlobalSlicingCost += SliceCost;
8049
8050     // Account as cost in the original configuration the gain obtained
8051     // with the current slices.
8052     OrigCost.addSliceGain(LS);
8053   }
8054
8055   // If the target supports paired load, adjust the cost accordingly.
8056   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8057   return OrigCost > GlobalSlicingCost;
8058 }
8059
8060 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8061 /// operations, split it in the various pieces being extracted.
8062 ///
8063 /// This sort of thing is introduced by SROA.
8064 /// This slicing takes care not to insert overlapping loads.
8065 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8066 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8067   if (Level < AfterLegalizeDAG)
8068     return false;
8069
8070   LoadSDNode *LD = cast<LoadSDNode>(N);
8071   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8072       !LD->getValueType(0).isInteger())
8073     return false;
8074
8075   // Keep track of already used bits to detect overlapping values.
8076   // In that case, we will just abort the transformation.
8077   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8078
8079   SmallVector<LoadedSlice, 4> LoadedSlices;
8080
8081   // Check if this load is used as several smaller chunks of bits.
8082   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8083   // of computation for each trunc.
8084   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8085        UI != UIEnd; ++UI) {
8086     // Skip the uses of the chain.
8087     if (UI.getUse().getResNo() != 0)
8088       continue;
8089
8090     SDNode *User = *UI;
8091     unsigned Shift = 0;
8092
8093     // Check if this is a trunc(lshr).
8094     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8095         isa<ConstantSDNode>(User->getOperand(1))) {
8096       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8097       User = *User->use_begin();
8098     }
8099
8100     // At this point, User is a Truncate, iff we encountered, trunc or
8101     // trunc(lshr).
8102     if (User->getOpcode() != ISD::TRUNCATE)
8103       return false;
8104
8105     // The width of the type must be a power of 2 and greater than 8-bits.
8106     // Otherwise the load cannot be represented in LLVM IR.
8107     // Moreover, if we shifted with a non 8-bits multiple, the slice
8108     // will be accross several bytes. We do not support that.
8109     unsigned Width = User->getValueSizeInBits(0);
8110     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8111       return 0;
8112
8113     // Build the slice for this chain of computations.
8114     LoadedSlice LS(User, LD, Shift, &DAG);
8115     APInt CurrentUsedBits = LS.getUsedBits();
8116
8117     // Check if this slice overlaps with another.
8118     if ((CurrentUsedBits & UsedBits) != 0)
8119       return false;
8120     // Update the bits used globally.
8121     UsedBits |= CurrentUsedBits;
8122
8123     // Check if the new slice would be legal.
8124     if (!LS.isLegal())
8125       return false;
8126
8127     // Record the slice.
8128     LoadedSlices.push_back(LS);
8129   }
8130
8131   // Abort slicing if it does not seem to be profitable.
8132   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8133     return false;
8134
8135   ++SlicedLoads;
8136
8137   // Rewrite each chain to use an independent load.
8138   // By construction, each chain can be represented by a unique load.
8139
8140   // Prepare the argument for the new token factor for all the slices.
8141   SmallVector<SDValue, 8> ArgChains;
8142   for (SmallVectorImpl<LoadedSlice>::const_iterator
8143            LSIt = LoadedSlices.begin(),
8144            LSItEnd = LoadedSlices.end();
8145        LSIt != LSItEnd; ++LSIt) {
8146     SDValue SliceInst = LSIt->loadSlice();
8147     CombineTo(LSIt->Inst, SliceInst, true);
8148     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8149       SliceInst = SliceInst.getOperand(0);
8150     assert(SliceInst->getOpcode() == ISD::LOAD &&
8151            "It takes more than a zext to get to the loaded slice!!");
8152     ArgChains.push_back(SliceInst.getValue(1));
8153   }
8154
8155   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8156                               &ArgChains[0], ArgChains.size());
8157   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8158   return true;
8159 }
8160
8161 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8162 /// load is having specific bytes cleared out.  If so, return the byte size
8163 /// being masked out and the shift amount.
8164 static std::pair<unsigned, unsigned>
8165 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8166   std::pair<unsigned, unsigned> Result(0, 0);
8167
8168   // Check for the structure we're looking for.
8169   if (V->getOpcode() != ISD::AND ||
8170       !isa<ConstantSDNode>(V->getOperand(1)) ||
8171       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8172     return Result;
8173
8174   // Check the chain and pointer.
8175   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8176   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8177
8178   // The store should be chained directly to the load or be an operand of a
8179   // tokenfactor.
8180   if (LD == Chain.getNode())
8181     ; // ok.
8182   else if (Chain->getOpcode() != ISD::TokenFactor)
8183     return Result; // Fail.
8184   else {
8185     bool isOk = false;
8186     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8187       if (Chain->getOperand(i).getNode() == LD) {
8188         isOk = true;
8189         break;
8190       }
8191     if (!isOk) return Result;
8192   }
8193
8194   // This only handles simple types.
8195   if (V.getValueType() != MVT::i16 &&
8196       V.getValueType() != MVT::i32 &&
8197       V.getValueType() != MVT::i64)
8198     return Result;
8199
8200   // Check the constant mask.  Invert it so that the bits being masked out are
8201   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8202   // follow the sign bit for uniformity.
8203   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8204   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8205   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8206   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8207   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8208   if (NotMaskLZ == 64) return Result;  // All zero mask.
8209
8210   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8211   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8212     return Result;
8213
8214   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8215   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8216     NotMaskLZ -= 64-V.getValueSizeInBits();
8217
8218   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8219   switch (MaskedBytes) {
8220   case 1:
8221   case 2:
8222   case 4: break;
8223   default: return Result; // All one mask, or 5-byte mask.
8224   }
8225
8226   // Verify that the first bit starts at a multiple of mask so that the access
8227   // is aligned the same as the access width.
8228   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8229
8230   Result.first = MaskedBytes;
8231   Result.second = NotMaskTZ/8;
8232   return Result;
8233 }
8234
8235
8236 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8237 /// provides a value as specified by MaskInfo.  If so, replace the specified
8238 /// store with a narrower store of truncated IVal.
8239 static SDNode *
8240 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8241                                 SDValue IVal, StoreSDNode *St,
8242                                 DAGCombiner *DC) {
8243   unsigned NumBytes = MaskInfo.first;
8244   unsigned ByteShift = MaskInfo.second;
8245   SelectionDAG &DAG = DC->getDAG();
8246
8247   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8248   // that uses this.  If not, this is not a replacement.
8249   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8250                                   ByteShift*8, (ByteShift+NumBytes)*8);
8251   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8252
8253   // Check that it is legal on the target to do this.  It is legal if the new
8254   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8255   // legalization.
8256   MVT VT = MVT::getIntegerVT(NumBytes*8);
8257   if (!DC->isTypeLegal(VT))
8258     return 0;
8259
8260   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8261   // shifted by ByteShift and truncated down to NumBytes.
8262   if (ByteShift)
8263     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8264                        DAG.getConstant(ByteShift*8,
8265                                     DC->getShiftAmountTy(IVal.getValueType())));
8266
8267   // Figure out the offset for the store and the alignment of the access.
8268   unsigned StOffset;
8269   unsigned NewAlign = St->getAlignment();
8270
8271   if (DAG.getTargetLoweringInfo().isLittleEndian())
8272     StOffset = ByteShift;
8273   else
8274     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8275
8276   SDValue Ptr = St->getBasePtr();
8277   if (StOffset) {
8278     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8279                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8280     NewAlign = MinAlign(NewAlign, StOffset);
8281   }
8282
8283   // Truncate down to the new size.
8284   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8285
8286   ++OpsNarrowed;
8287   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8288                       St->getPointerInfo().getWithOffset(StOffset),
8289                       false, false, NewAlign).getNode();
8290 }
8291
8292
8293 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8294 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8295 /// of the loaded bits, try narrowing the load and store if it would end up
8296 /// being a win for performance or code size.
8297 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8298   StoreSDNode *ST  = cast<StoreSDNode>(N);
8299   if (ST->isVolatile())
8300     return SDValue();
8301
8302   SDValue Chain = ST->getChain();
8303   SDValue Value = ST->getValue();
8304   SDValue Ptr   = ST->getBasePtr();
8305   EVT VT = Value.getValueType();
8306
8307   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8308     return SDValue();
8309
8310   unsigned Opc = Value.getOpcode();
8311
8312   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8313   // is a byte mask indicating a consecutive number of bytes, check to see if
8314   // Y is known to provide just those bytes.  If so, we try to replace the
8315   // load + replace + store sequence with a single (narrower) store, which makes
8316   // the load dead.
8317   if (Opc == ISD::OR) {
8318     std::pair<unsigned, unsigned> MaskedLoad;
8319     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8320     if (MaskedLoad.first)
8321       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8322                                                   Value.getOperand(1), ST,this))
8323         return SDValue(NewST, 0);
8324
8325     // Or is commutative, so try swapping X and Y.
8326     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8327     if (MaskedLoad.first)
8328       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8329                                                   Value.getOperand(0), ST,this))
8330         return SDValue(NewST, 0);
8331   }
8332
8333   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8334       Value.getOperand(1).getOpcode() != ISD::Constant)
8335     return SDValue();
8336
8337   SDValue N0 = Value.getOperand(0);
8338   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8339       Chain == SDValue(N0.getNode(), 1)) {
8340     LoadSDNode *LD = cast<LoadSDNode>(N0);
8341     if (LD->getBasePtr() != Ptr ||
8342         LD->getPointerInfo().getAddrSpace() !=
8343         ST->getPointerInfo().getAddrSpace())
8344       return SDValue();
8345
8346     // Find the type to narrow it the load / op / store to.
8347     SDValue N1 = Value.getOperand(1);
8348     unsigned BitWidth = N1.getValueSizeInBits();
8349     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8350     if (Opc == ISD::AND)
8351       Imm ^= APInt::getAllOnesValue(BitWidth);
8352     if (Imm == 0 || Imm.isAllOnesValue())
8353       return SDValue();
8354     unsigned ShAmt = Imm.countTrailingZeros();
8355     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8356     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8357     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8358     while (NewBW < BitWidth &&
8359            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8360              TLI.isNarrowingProfitable(VT, NewVT))) {
8361       NewBW = NextPowerOf2(NewBW);
8362       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8363     }
8364     if (NewBW >= BitWidth)
8365       return SDValue();
8366
8367     // If the lsb changed does not start at the type bitwidth boundary,
8368     // start at the previous one.
8369     if (ShAmt % NewBW)
8370       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8371     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8372                                    std::min(BitWidth, ShAmt + NewBW));
8373     if ((Imm & Mask) == Imm) {
8374       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8375       if (Opc == ISD::AND)
8376         NewImm ^= APInt::getAllOnesValue(NewBW);
8377       uint64_t PtrOff = ShAmt / 8;
8378       // For big endian targets, we need to adjust the offset to the pointer to
8379       // load the correct bytes.
8380       if (TLI.isBigEndian())
8381         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8382
8383       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8384       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8385       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8386         return SDValue();
8387
8388       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8389                                    Ptr.getValueType(), Ptr,
8390                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8391       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8392                                   LD->getChain(), NewPtr,
8393                                   LD->getPointerInfo().getWithOffset(PtrOff),
8394                                   LD->isVolatile(), LD->isNonTemporal(),
8395                                   LD->isInvariant(), NewAlign);
8396       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8397                                    DAG.getConstant(NewImm, NewVT));
8398       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8399                                    NewVal, NewPtr,
8400                                    ST->getPointerInfo().getWithOffset(PtrOff),
8401                                    false, false, NewAlign);
8402
8403       AddToWorkList(NewPtr.getNode());
8404       AddToWorkList(NewLD.getNode());
8405       AddToWorkList(NewVal.getNode());
8406       WorkListRemover DeadNodes(*this);
8407       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8408       ++OpsNarrowed;
8409       return NewST;
8410     }
8411   }
8412
8413   return SDValue();
8414 }
8415
8416 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8417 /// if the load value isn't used by any other operations, then consider
8418 /// transforming the pair to integer load / store operations if the target
8419 /// deems the transformation profitable.
8420 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8421   StoreSDNode *ST  = cast<StoreSDNode>(N);
8422   SDValue Chain = ST->getChain();
8423   SDValue Value = ST->getValue();
8424   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8425       Value.hasOneUse() &&
8426       Chain == SDValue(Value.getNode(), 1)) {
8427     LoadSDNode *LD = cast<LoadSDNode>(Value);
8428     EVT VT = LD->getMemoryVT();
8429     if (!VT.isFloatingPoint() ||
8430         VT != ST->getMemoryVT() ||
8431         LD->isNonTemporal() ||
8432         ST->isNonTemporal() ||
8433         LD->getPointerInfo().getAddrSpace() != 0 ||
8434         ST->getPointerInfo().getAddrSpace() != 0)
8435       return SDValue();
8436
8437     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8438     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8439         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8440         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8441         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8442       return SDValue();
8443
8444     unsigned LDAlign = LD->getAlignment();
8445     unsigned STAlign = ST->getAlignment();
8446     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8447     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8448     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8449       return SDValue();
8450
8451     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8452                                 LD->getChain(), LD->getBasePtr(),
8453                                 LD->getPointerInfo(),
8454                                 false, false, false, LDAlign);
8455
8456     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8457                                  NewLD, ST->getBasePtr(),
8458                                  ST->getPointerInfo(),
8459                                  false, false, STAlign);
8460
8461     AddToWorkList(NewLD.getNode());
8462     AddToWorkList(NewST.getNode());
8463     WorkListRemover DeadNodes(*this);
8464     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8465     ++LdStFP2Int;
8466     return NewST;
8467   }
8468
8469   return SDValue();
8470 }
8471
8472 /// Helper struct to parse and store a memory address as base + index + offset.
8473 /// We ignore sign extensions when it is safe to do so.
8474 /// The following two expressions are not equivalent. To differentiate we need
8475 /// to store whether there was a sign extension involved in the index
8476 /// computation.
8477 ///  (load (i64 add (i64 copyfromreg %c)
8478 ///                 (i64 signextend (add (i8 load %index)
8479 ///                                      (i8 1))))
8480 /// vs
8481 ///
8482 /// (load (i64 add (i64 copyfromreg %c)
8483 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8484 ///                                         (i32 1)))))
8485 struct BaseIndexOffset {
8486   SDValue Base;
8487   SDValue Index;
8488   int64_t Offset;
8489   bool IsIndexSignExt;
8490
8491   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8492
8493   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8494                   bool IsIndexSignExt) :
8495     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8496
8497   bool equalBaseIndex(const BaseIndexOffset &Other) {
8498     return Other.Base == Base && Other.Index == Index &&
8499       Other.IsIndexSignExt == IsIndexSignExt;
8500   }
8501
8502   /// Parses tree in Ptr for base, index, offset addresses.
8503   static BaseIndexOffset match(SDValue Ptr) {
8504     bool IsIndexSignExt = false;
8505
8506     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8507     // instruction, then it could be just the BASE or everything else we don't
8508     // know how to handle. Just use Ptr as BASE and give up.
8509     if (Ptr->getOpcode() != ISD::ADD)
8510       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8511
8512     // We know that we have at least an ADD instruction. Try to pattern match
8513     // the simple case of BASE + OFFSET.
8514     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8515       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8516       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8517                               IsIndexSignExt);
8518     }
8519
8520     // Inside a loop the current BASE pointer is calculated using an ADD and a
8521     // MUL instruction. In this case Ptr is the actual BASE pointer.
8522     // (i64 add (i64 %array_ptr)
8523     //          (i64 mul (i64 %induction_var)
8524     //                   (i64 %element_size)))
8525     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8526       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8527
8528     // Look at Base + Index + Offset cases.
8529     SDValue Base = Ptr->getOperand(0);
8530     SDValue IndexOffset = Ptr->getOperand(1);
8531
8532     // Skip signextends.
8533     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8534       IndexOffset = IndexOffset->getOperand(0);
8535       IsIndexSignExt = true;
8536     }
8537
8538     // Either the case of Base + Index (no offset) or something else.
8539     if (IndexOffset->getOpcode() != ISD::ADD)
8540       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8541
8542     // Now we have the case of Base + Index + offset.
8543     SDValue Index = IndexOffset->getOperand(0);
8544     SDValue Offset = IndexOffset->getOperand(1);
8545
8546     if (!isa<ConstantSDNode>(Offset))
8547       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8548
8549     // Ignore signextends.
8550     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8551       Index = Index->getOperand(0);
8552       IsIndexSignExt = true;
8553     } else IsIndexSignExt = false;
8554
8555     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8556     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8557   }
8558 };
8559
8560 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8561 /// is located in a sequence of memory operations connected by a chain.
8562 struct MemOpLink {
8563   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8564     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8565   // Ptr to the mem node.
8566   LSBaseSDNode *MemNode;
8567   // Offset from the base ptr.
8568   int64_t OffsetFromBase;
8569   // What is the sequence number of this mem node.
8570   // Lowest mem operand in the DAG starts at zero.
8571   unsigned SequenceNum;
8572 };
8573
8574 /// Sorts store nodes in a link according to their offset from a shared
8575 // base ptr.
8576 struct ConsecutiveMemoryChainSorter {
8577   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8578     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8579   }
8580 };
8581
8582 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8583   EVT MemVT = St->getMemoryVT();
8584   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8585   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8586     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8587
8588   // Don't merge vectors into wider inputs.
8589   if (MemVT.isVector() || !MemVT.isSimple())
8590     return false;
8591
8592   // Perform an early exit check. Do not bother looking at stored values that
8593   // are not constants or loads.
8594   SDValue StoredVal = St->getValue();
8595   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8596   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8597       !IsLoadSrc)
8598     return false;
8599
8600   // Only look at ends of store sequences.
8601   SDValue Chain = SDValue(St, 1);
8602   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8603     return false;
8604
8605   // This holds the base pointer, index, and the offset in bytes from the base
8606   // pointer.
8607   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8608
8609   // We must have a base and an offset.
8610   if (!BasePtr.Base.getNode())
8611     return false;
8612
8613   // Do not handle stores to undef base pointers.
8614   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8615     return false;
8616
8617   // Save the LoadSDNodes that we find in the chain.
8618   // We need to make sure that these nodes do not interfere with
8619   // any of the store nodes.
8620   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8621
8622   // Save the StoreSDNodes that we find in the chain.
8623   SmallVector<MemOpLink, 8> StoreNodes;
8624
8625   // Walk up the chain and look for nodes with offsets from the same
8626   // base pointer. Stop when reaching an instruction with a different kind
8627   // or instruction which has a different base pointer.
8628   unsigned Seq = 0;
8629   StoreSDNode *Index = St;
8630   while (Index) {
8631     // If the chain has more than one use, then we can't reorder the mem ops.
8632     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8633       break;
8634
8635     // Find the base pointer and offset for this memory node.
8636     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8637
8638     // Check that the base pointer is the same as the original one.
8639     if (!Ptr.equalBaseIndex(BasePtr))
8640       break;
8641
8642     // Check that the alignment is the same.
8643     if (Index->getAlignment() != St->getAlignment())
8644       break;
8645
8646     // The memory operands must not be volatile.
8647     if (Index->isVolatile() || Index->isIndexed())
8648       break;
8649
8650     // No truncation.
8651     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8652       if (St->isTruncatingStore())
8653         break;
8654
8655     // The stored memory type must be the same.
8656     if (Index->getMemoryVT() != MemVT)
8657       break;
8658
8659     // We do not allow unaligned stores because we want to prevent overriding
8660     // stores.
8661     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8662       break;
8663
8664     // We found a potential memory operand to merge.
8665     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8666
8667     // Find the next memory operand in the chain. If the next operand in the
8668     // chain is a store then move up and continue the scan with the next
8669     // memory operand. If the next operand is a load save it and use alias
8670     // information to check if it interferes with anything.
8671     SDNode *NextInChain = Index->getChain().getNode();
8672     while (1) {
8673       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8674         // We found a store node. Use it for the next iteration.
8675         Index = STn;
8676         break;
8677       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8678         // Save the load node for later. Continue the scan.
8679         AliasLoadNodes.push_back(Ldn);
8680         NextInChain = Ldn->getChain().getNode();
8681         continue;
8682       } else {
8683         Index = NULL;
8684         break;
8685       }
8686     }
8687   }
8688
8689   // Check if there is anything to merge.
8690   if (StoreNodes.size() < 2)
8691     return false;
8692
8693   // Sort the memory operands according to their distance from the base pointer.
8694   std::sort(StoreNodes.begin(), StoreNodes.end(),
8695             ConsecutiveMemoryChainSorter());
8696
8697   // Scan the memory operations on the chain and find the first non-consecutive
8698   // store memory address.
8699   unsigned LastConsecutiveStore = 0;
8700   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8701   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8702
8703     // Check that the addresses are consecutive starting from the second
8704     // element in the list of stores.
8705     if (i > 0) {
8706       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8707       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8708         break;
8709     }
8710
8711     bool Alias = false;
8712     // Check if this store interferes with any of the loads that we found.
8713     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8714       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8715         Alias = true;
8716         break;
8717       }
8718     // We found a load that alias with this store. Stop the sequence.
8719     if (Alias)
8720       break;
8721
8722     // Mark this node as useful.
8723     LastConsecutiveStore = i;
8724   }
8725
8726   // The node with the lowest store address.
8727   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8728
8729   // Store the constants into memory as one consecutive store.
8730   if (!IsLoadSrc) {
8731     unsigned LastLegalType = 0;
8732     unsigned LastLegalVectorType = 0;
8733     bool NonZero = false;
8734     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8735       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8736       SDValue StoredVal = St->getValue();
8737
8738       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8739         NonZero |= !C->isNullValue();
8740       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8741         NonZero |= !C->getConstantFPValue()->isNullValue();
8742       } else {
8743         // Non constant.
8744         break;
8745       }
8746
8747       // Find a legal type for the constant store.
8748       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8749       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8750       if (TLI.isTypeLegal(StoreTy))
8751         LastLegalType = i+1;
8752       // Or check whether a truncstore is legal.
8753       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8754                TargetLowering::TypePromoteInteger) {
8755         EVT LegalizedStoredValueTy =
8756           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8757         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8758           LastLegalType = i+1;
8759       }
8760
8761       // Find a legal type for the vector store.
8762       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8763       if (TLI.isTypeLegal(Ty))
8764         LastLegalVectorType = i + 1;
8765     }
8766
8767     // We only use vectors if the constant is known to be zero and the
8768     // function is not marked with the noimplicitfloat attribute.
8769     if (NonZero || NoVectors)
8770       LastLegalVectorType = 0;
8771
8772     // Check if we found a legal integer type to store.
8773     if (LastLegalType == 0 && LastLegalVectorType == 0)
8774       return false;
8775
8776     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8777     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8778
8779     // Make sure we have something to merge.
8780     if (NumElem < 2)
8781       return false;
8782
8783     unsigned EarliestNodeUsed = 0;
8784     for (unsigned i=0; i < NumElem; ++i) {
8785       // Find a chain for the new wide-store operand. Notice that some
8786       // of the store nodes that we found may not be selected for inclusion
8787       // in the wide store. The chain we use needs to be the chain of the
8788       // earliest store node which is *used* and replaced by the wide store.
8789       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8790         EarliestNodeUsed = i;
8791     }
8792
8793     // The earliest Node in the DAG.
8794     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8795     SDLoc DL(StoreNodes[0].MemNode);
8796
8797     SDValue StoredVal;
8798     if (UseVector) {
8799       // Find a legal type for the vector store.
8800       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8801       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8802       StoredVal = DAG.getConstant(0, Ty);
8803     } else {
8804       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8805       APInt StoreInt(StoreBW, 0);
8806
8807       // Construct a single integer constant which is made of the smaller
8808       // constant inputs.
8809       bool IsLE = TLI.isLittleEndian();
8810       for (unsigned i = 0; i < NumElem ; ++i) {
8811         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8812         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8813         SDValue Val = St->getValue();
8814         StoreInt<<=ElementSizeBytes*8;
8815         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8816           StoreInt|=C->getAPIntValue().zext(StoreBW);
8817         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8818           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8819         } else {
8820           assert(false && "Invalid constant element type");
8821         }
8822       }
8823
8824       // Create the new Load and Store operations.
8825       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8826       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8827     }
8828
8829     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8830                                     FirstInChain->getBasePtr(),
8831                                     FirstInChain->getPointerInfo(),
8832                                     false, false,
8833                                     FirstInChain->getAlignment());
8834
8835     // Replace the first store with the new store
8836     CombineTo(EarliestOp, NewStore);
8837     // Erase all other stores.
8838     for (unsigned i = 0; i < NumElem ; ++i) {
8839       if (StoreNodes[i].MemNode == EarliestOp)
8840         continue;
8841       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8842       // ReplaceAllUsesWith will replace all uses that existed when it was
8843       // called, but graph optimizations may cause new ones to appear. For
8844       // example, the case in pr14333 looks like
8845       //
8846       //  St's chain -> St -> another store -> X
8847       //
8848       // And the only difference from St to the other store is the chain.
8849       // When we change it's chain to be St's chain they become identical,
8850       // get CSEed and the net result is that X is now a use of St.
8851       // Since we know that St is redundant, just iterate.
8852       while (!St->use_empty())
8853         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8854       removeFromWorkList(St);
8855       DAG.DeleteNode(St);
8856     }
8857
8858     return true;
8859   }
8860
8861   // Below we handle the case of multiple consecutive stores that
8862   // come from multiple consecutive loads. We merge them into a single
8863   // wide load and a single wide store.
8864
8865   // Look for load nodes which are used by the stored values.
8866   SmallVector<MemOpLink, 8> LoadNodes;
8867
8868   // Find acceptable loads. Loads need to have the same chain (token factor),
8869   // must not be zext, volatile, indexed, and they must be consecutive.
8870   BaseIndexOffset LdBasePtr;
8871   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8872     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8873     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8874     if (!Ld) break;
8875
8876     // Loads must only have one use.
8877     if (!Ld->hasNUsesOfValue(1, 0))
8878       break;
8879
8880     // Check that the alignment is the same as the stores.
8881     if (Ld->getAlignment() != St->getAlignment())
8882       break;
8883
8884     // The memory operands must not be volatile.
8885     if (Ld->isVolatile() || Ld->isIndexed())
8886       break;
8887
8888     // We do not accept ext loads.
8889     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8890       break;
8891
8892     // The stored memory type must be the same.
8893     if (Ld->getMemoryVT() != MemVT)
8894       break;
8895
8896     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8897     // If this is not the first ptr that we check.
8898     if (LdBasePtr.Base.getNode()) {
8899       // The base ptr must be the same.
8900       if (!LdPtr.equalBaseIndex(LdBasePtr))
8901         break;
8902     } else {
8903       // Check that all other base pointers are the same as this one.
8904       LdBasePtr = LdPtr;
8905     }
8906
8907     // We found a potential memory operand to merge.
8908     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8909   }
8910
8911   if (LoadNodes.size() < 2)
8912     return false;
8913
8914   // Scan the memory operations on the chain and find the first non-consecutive
8915   // load memory address. These variables hold the index in the store node
8916   // array.
8917   unsigned LastConsecutiveLoad = 0;
8918   // This variable refers to the size and not index in the array.
8919   unsigned LastLegalVectorType = 0;
8920   unsigned LastLegalIntegerType = 0;
8921   StartAddress = LoadNodes[0].OffsetFromBase;
8922   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8923   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8924     // All loads much share the same chain.
8925     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8926       break;
8927
8928     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8929     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8930       break;
8931     LastConsecutiveLoad = i;
8932
8933     // Find a legal type for the vector store.
8934     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8935     if (TLI.isTypeLegal(StoreTy))
8936       LastLegalVectorType = i + 1;
8937
8938     // Find a legal type for the integer store.
8939     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8940     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8941     if (TLI.isTypeLegal(StoreTy))
8942       LastLegalIntegerType = i + 1;
8943     // Or check whether a truncstore and extload is legal.
8944     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8945              TargetLowering::TypePromoteInteger) {
8946       EVT LegalizedStoredValueTy =
8947         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8948       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8949           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8950           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8951           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8952         LastLegalIntegerType = i+1;
8953     }
8954   }
8955
8956   // Only use vector types if the vector type is larger than the integer type.
8957   // If they are the same, use integers.
8958   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8959   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8960
8961   // We add +1 here because the LastXXX variables refer to location while
8962   // the NumElem refers to array/index size.
8963   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8964   NumElem = std::min(LastLegalType, NumElem);
8965
8966   if (NumElem < 2)
8967     return false;
8968
8969   // The earliest Node in the DAG.
8970   unsigned EarliestNodeUsed = 0;
8971   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8972   for (unsigned i=1; i<NumElem; ++i) {
8973     // Find a chain for the new wide-store operand. Notice that some
8974     // of the store nodes that we found may not be selected for inclusion
8975     // in the wide store. The chain we use needs to be the chain of the
8976     // earliest store node which is *used* and replaced by the wide store.
8977     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8978       EarliestNodeUsed = i;
8979   }
8980
8981   // Find if it is better to use vectors or integers to load and store
8982   // to memory.
8983   EVT JointMemOpVT;
8984   if (UseVectorTy) {
8985     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8986   } else {
8987     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8988     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8989   }
8990
8991   SDLoc LoadDL(LoadNodes[0].MemNode);
8992   SDLoc StoreDL(StoreNodes[0].MemNode);
8993
8994   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8995   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8996                                 FirstLoad->getChain(),
8997                                 FirstLoad->getBasePtr(),
8998                                 FirstLoad->getPointerInfo(),
8999                                 false, false, false,
9000                                 FirstLoad->getAlignment());
9001
9002   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9003                                   FirstInChain->getBasePtr(),
9004                                   FirstInChain->getPointerInfo(), false, false,
9005                                   FirstInChain->getAlignment());
9006
9007   // Replace one of the loads with the new load.
9008   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9009   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9010                                 SDValue(NewLoad.getNode(), 1));
9011
9012   // Remove the rest of the load chains.
9013   for (unsigned i = 1; i < NumElem ; ++i) {
9014     // Replace all chain users of the old load nodes with the chain of the new
9015     // load node.
9016     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9017     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9018   }
9019
9020   // Replace the first store with the new store.
9021   CombineTo(EarliestOp, NewStore);
9022   // Erase all other stores.
9023   for (unsigned i = 0; i < NumElem ; ++i) {
9024     // Remove all Store nodes.
9025     if (StoreNodes[i].MemNode == EarliestOp)
9026       continue;
9027     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9028     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9029     removeFromWorkList(St);
9030     DAG.DeleteNode(St);
9031   }
9032
9033   return true;
9034 }
9035
9036 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9037   StoreSDNode *ST  = cast<StoreSDNode>(N);
9038   SDValue Chain = ST->getChain();
9039   SDValue Value = ST->getValue();
9040   SDValue Ptr   = ST->getBasePtr();
9041
9042   // If this is a store of a bit convert, store the input value if the
9043   // resultant store does not need a higher alignment than the original.
9044   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9045       ST->isUnindexed()) {
9046     unsigned OrigAlign = ST->getAlignment();
9047     EVT SVT = Value.getOperand(0).getValueType();
9048     unsigned Align = TLI.getDataLayout()->
9049       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9050     if (Align <= OrigAlign &&
9051         ((!LegalOperations && !ST->isVolatile()) ||
9052          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9053       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9054                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9055                           ST->isNonTemporal(), OrigAlign);
9056   }
9057
9058   // Turn 'store undef, Ptr' -> nothing.
9059   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9060     return Chain;
9061
9062   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9063   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9064     // NOTE: If the original store is volatile, this transform must not increase
9065     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9066     // processor operation but an i64 (which is not legal) requires two.  So the
9067     // transform should not be done in this case.
9068     if (Value.getOpcode() != ISD::TargetConstantFP) {
9069       SDValue Tmp;
9070       switch (CFP->getSimpleValueType(0).SimpleTy) {
9071       default: llvm_unreachable("Unknown FP type");
9072       case MVT::f16:    // We don't do this for these yet.
9073       case MVT::f80:
9074       case MVT::f128:
9075       case MVT::ppcf128:
9076         break;
9077       case MVT::f32:
9078         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9079             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9080           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9081                               bitcastToAPInt().getZExtValue(), MVT::i32);
9082           return DAG.getStore(Chain, SDLoc(N), Tmp,
9083                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
9084                               ST->isNonTemporal(), ST->getAlignment());
9085         }
9086         break;
9087       case MVT::f64:
9088         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9089              !ST->isVolatile()) ||
9090             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9091           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9092                                 getZExtValue(), MVT::i64);
9093           return DAG.getStore(Chain, SDLoc(N), Tmp,
9094                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
9095                               ST->isNonTemporal(), ST->getAlignment());
9096         }
9097
9098         if (!ST->isVolatile() &&
9099             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9100           // Many FP stores are not made apparent until after legalize, e.g. for
9101           // argument passing.  Since this is so common, custom legalize the
9102           // 64-bit integer store into two 32-bit stores.
9103           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9104           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9105           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9106           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9107
9108           unsigned Alignment = ST->getAlignment();
9109           bool isVolatile = ST->isVolatile();
9110           bool isNonTemporal = ST->isNonTemporal();
9111
9112           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9113                                      Ptr, ST->getPointerInfo(),
9114                                      isVolatile, isNonTemporal,
9115                                      ST->getAlignment());
9116           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9117                             DAG.getConstant(4, Ptr.getValueType()));
9118           Alignment = MinAlign(Alignment, 4U);
9119           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9120                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9121                                      isVolatile, isNonTemporal,
9122                                      Alignment);
9123           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9124                              St0, St1);
9125         }
9126
9127         break;
9128       }
9129     }
9130   }
9131
9132   // Try to infer better alignment information than the store already has.
9133   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9134     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9135       if (Align > ST->getAlignment())
9136         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9137                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9138                                  ST->isVolatile(), ST->isNonTemporal(), Align);
9139     }
9140   }
9141
9142   // Try transforming a pair floating point load / store ops to integer
9143   // load / store ops.
9144   SDValue NewST = TransformFPLoadStorePair(N);
9145   if (NewST.getNode())
9146     return NewST;
9147
9148   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9149     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9150   if (UseAA) {
9151     // Walk up chain skipping non-aliasing memory nodes.
9152     SDValue BetterChain = FindBetterChain(N, Chain);
9153
9154     // If there is a better chain.
9155     if (Chain != BetterChain) {
9156       SDValue ReplStore;
9157
9158       // Replace the chain to avoid dependency.
9159       if (ST->isTruncatingStore()) {
9160         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9161                                       ST->getPointerInfo(),
9162                                       ST->getMemoryVT(), ST->isVolatile(),
9163                                       ST->isNonTemporal(), ST->getAlignment());
9164       } else {
9165         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9166                                  ST->getPointerInfo(),
9167                                  ST->isVolatile(), ST->isNonTemporal(),
9168                                  ST->getAlignment());
9169       }
9170
9171       // Create token to keep both nodes around.
9172       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9173                                   MVT::Other, Chain, ReplStore);
9174
9175       // Make sure the new and old chains are cleaned up.
9176       AddToWorkList(Token.getNode());
9177
9178       // Don't add users to work list.
9179       return CombineTo(N, Token, false);
9180     }
9181   }
9182
9183   // Try transforming N to an indexed store.
9184   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9185     return SDValue(N, 0);
9186
9187   // FIXME: is there such a thing as a truncating indexed store?
9188   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9189       Value.getValueType().isInteger()) {
9190     // See if we can simplify the input to this truncstore with knowledge that
9191     // only the low bits are being used.  For example:
9192     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9193     SDValue Shorter =
9194       GetDemandedBits(Value,
9195                       APInt::getLowBitsSet(
9196                         Value.getValueType().getScalarType().getSizeInBits(),
9197                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9198     AddToWorkList(Value.getNode());
9199     if (Shorter.getNode())
9200       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9201                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9202                                ST->isVolatile(), ST->isNonTemporal(),
9203                                ST->getAlignment());
9204
9205     // Otherwise, see if we can simplify the operation with
9206     // SimplifyDemandedBits, which only works if the value has a single use.
9207     if (SimplifyDemandedBits(Value,
9208                         APInt::getLowBitsSet(
9209                           Value.getValueType().getScalarType().getSizeInBits(),
9210                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9211       return SDValue(N, 0);
9212   }
9213
9214   // If this is a load followed by a store to the same location, then the store
9215   // is dead/noop.
9216   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9217     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9218         ST->isUnindexed() && !ST->isVolatile() &&
9219         // There can't be any side effects between the load and store, such as
9220         // a call or store.
9221         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9222       // The store is dead, remove it.
9223       return Chain;
9224     }
9225   }
9226
9227   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9228   // truncating store.  We can do this even if this is already a truncstore.
9229   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9230       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9231       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9232                             ST->getMemoryVT())) {
9233     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9234                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9235                              ST->isVolatile(), ST->isNonTemporal(),
9236                              ST->getAlignment());
9237   }
9238
9239   // Only perform this optimization before the types are legal, because we
9240   // don't want to perform this optimization on every DAGCombine invocation.
9241   if (!LegalTypes) {
9242     bool EverChanged = false;
9243
9244     do {
9245       // There can be multiple store sequences on the same chain.
9246       // Keep trying to merge store sequences until we are unable to do so
9247       // or until we merge the last store on the chain.
9248       bool Changed = MergeConsecutiveStores(ST);
9249       EverChanged |= Changed;
9250       if (!Changed) break;
9251     } while (ST->getOpcode() != ISD::DELETED_NODE);
9252
9253     if (EverChanged)
9254       return SDValue(N, 0);
9255   }
9256
9257   return ReduceLoadOpStoreWidth(N);
9258 }
9259
9260 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9261   SDValue InVec = N->getOperand(0);
9262   SDValue InVal = N->getOperand(1);
9263   SDValue EltNo = N->getOperand(2);
9264   SDLoc dl(N);
9265
9266   // If the inserted element is an UNDEF, just use the input vector.
9267   if (InVal.getOpcode() == ISD::UNDEF)
9268     return InVec;
9269
9270   EVT VT = InVec.getValueType();
9271
9272   // If we can't generate a legal BUILD_VECTOR, exit
9273   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9274     return SDValue();
9275
9276   // Check that we know which element is being inserted
9277   if (!isa<ConstantSDNode>(EltNo))
9278     return SDValue();
9279   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9280
9281   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9282   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9283   // vector elements.
9284   SmallVector<SDValue, 8> Ops;
9285   // Do not combine these two vectors if the output vector will not replace
9286   // the input vector.
9287   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9288     Ops.append(InVec.getNode()->op_begin(),
9289                InVec.getNode()->op_end());
9290   } else if (InVec.getOpcode() == ISD::UNDEF) {
9291     unsigned NElts = VT.getVectorNumElements();
9292     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9293   } else {
9294     return SDValue();
9295   }
9296
9297   // Insert the element
9298   if (Elt < Ops.size()) {
9299     // All the operands of BUILD_VECTOR must have the same type;
9300     // we enforce that here.
9301     EVT OpVT = Ops[0].getValueType();
9302     if (InVal.getValueType() != OpVT)
9303       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9304                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9305                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9306     Ops[Elt] = InVal;
9307   }
9308
9309   // Return the new vector
9310   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9311                      VT, &Ops[0], Ops.size());
9312 }
9313
9314 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9315   // (vextract (scalar_to_vector val, 0) -> val
9316   SDValue InVec = N->getOperand(0);
9317   EVT VT = InVec.getValueType();
9318   EVT NVT = N->getValueType(0);
9319
9320   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9321     // Check if the result type doesn't match the inserted element type. A
9322     // SCALAR_TO_VECTOR may truncate the inserted element and the
9323     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9324     SDValue InOp = InVec.getOperand(0);
9325     if (InOp.getValueType() != NVT) {
9326       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9327       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9328     }
9329     return InOp;
9330   }
9331
9332   SDValue EltNo = N->getOperand(1);
9333   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9334
9335   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9336   // We only perform this optimization before the op legalization phase because
9337   // we may introduce new vector instructions which are not backed by TD
9338   // patterns. For example on AVX, extracting elements from a wide vector
9339   // without using extract_subvector.
9340   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9341       && ConstEltNo && !LegalOperations) {
9342     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9343     int NumElem = VT.getVectorNumElements();
9344     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9345     // Find the new index to extract from.
9346     int OrigElt = SVOp->getMaskElt(Elt);
9347
9348     // Extracting an undef index is undef.
9349     if (OrigElt == -1)
9350       return DAG.getUNDEF(NVT);
9351
9352     // Select the right vector half to extract from.
9353     if (OrigElt < NumElem) {
9354       InVec = InVec->getOperand(0);
9355     } else {
9356       InVec = InVec->getOperand(1);
9357       OrigElt -= NumElem;
9358     }
9359
9360     EVT IndexTy = TLI.getVectorIdxTy();
9361     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9362                        InVec, DAG.getConstant(OrigElt, IndexTy));
9363   }
9364
9365   // Perform only after legalization to ensure build_vector / vector_shuffle
9366   // optimizations have already been done.
9367   if (!LegalOperations) return SDValue();
9368
9369   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9370   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9371   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9372
9373   if (ConstEltNo) {
9374     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9375     bool NewLoad = false;
9376     bool BCNumEltsChanged = false;
9377     EVT ExtVT = VT.getVectorElementType();
9378     EVT LVT = ExtVT;
9379
9380     // If the result of load has to be truncated, then it's not necessarily
9381     // profitable.
9382     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9383       return SDValue();
9384
9385     if (InVec.getOpcode() == ISD::BITCAST) {
9386       // Don't duplicate a load with other uses.
9387       if (!InVec.hasOneUse())
9388         return SDValue();
9389
9390       EVT BCVT = InVec.getOperand(0).getValueType();
9391       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9392         return SDValue();
9393       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9394         BCNumEltsChanged = true;
9395       InVec = InVec.getOperand(0);
9396       ExtVT = BCVT.getVectorElementType();
9397       NewLoad = true;
9398     }
9399
9400     LoadSDNode *LN0 = NULL;
9401     const ShuffleVectorSDNode *SVN = NULL;
9402     if (ISD::isNormalLoad(InVec.getNode())) {
9403       LN0 = cast<LoadSDNode>(InVec);
9404     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9405                InVec.getOperand(0).getValueType() == ExtVT &&
9406                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9407       // Don't duplicate a load with other uses.
9408       if (!InVec.hasOneUse())
9409         return SDValue();
9410
9411       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9412     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9413       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9414       // =>
9415       // (load $addr+1*size)
9416
9417       // Don't duplicate a load with other uses.
9418       if (!InVec.hasOneUse())
9419         return SDValue();
9420
9421       // If the bit convert changed the number of elements, it is unsafe
9422       // to examine the mask.
9423       if (BCNumEltsChanged)
9424         return SDValue();
9425
9426       // Select the input vector, guarding against out of range extract vector.
9427       unsigned NumElems = VT.getVectorNumElements();
9428       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9429       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9430
9431       if (InVec.getOpcode() == ISD::BITCAST) {
9432         // Don't duplicate a load with other uses.
9433         if (!InVec.hasOneUse())
9434           return SDValue();
9435
9436         InVec = InVec.getOperand(0);
9437       }
9438       if (ISD::isNormalLoad(InVec.getNode())) {
9439         LN0 = cast<LoadSDNode>(InVec);
9440         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9441       }
9442     }
9443
9444     // Make sure we found a non-volatile load and the extractelement is
9445     // the only use.
9446     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9447       return SDValue();
9448
9449     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9450     if (Elt == -1)
9451       return DAG.getUNDEF(LVT);
9452
9453     unsigned Align = LN0->getAlignment();
9454     if (NewLoad) {
9455       // Check the resultant load doesn't need a higher alignment than the
9456       // original load.
9457       unsigned NewAlign =
9458         TLI.getDataLayout()
9459             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9460
9461       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9462         return SDValue();
9463
9464       Align = NewAlign;
9465     }
9466
9467     SDValue NewPtr = LN0->getBasePtr();
9468     unsigned PtrOff = 0;
9469
9470     if (Elt) {
9471       PtrOff = LVT.getSizeInBits() * Elt / 8;
9472       EVT PtrType = NewPtr.getValueType();
9473       if (TLI.isBigEndian())
9474         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9475       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9476                            DAG.getConstant(PtrOff, PtrType));
9477     }
9478
9479     // The replacement we need to do here is a little tricky: we need to
9480     // replace an extractelement of a load with a load.
9481     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9482     // Note that this replacement assumes that the extractvalue is the only
9483     // use of the load; that's okay because we don't want to perform this
9484     // transformation in other cases anyway.
9485     SDValue Load;
9486     SDValue Chain;
9487     if (NVT.bitsGT(LVT)) {
9488       // If the result type of vextract is wider than the load, then issue an
9489       // extending load instead.
9490       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9491         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9492       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9493                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9494                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
9495       Chain = Load.getValue(1);
9496     } else {
9497       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9498                          LN0->getPointerInfo().getWithOffset(PtrOff),
9499                          LN0->isVolatile(), LN0->isNonTemporal(),
9500                          LN0->isInvariant(), Align);
9501       Chain = Load.getValue(1);
9502       if (NVT.bitsLT(LVT))
9503         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9504       else
9505         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9506     }
9507     WorkListRemover DeadNodes(*this);
9508     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9509     SDValue To[] = { Load, Chain };
9510     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9511     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9512     // worklist explicitly as well.
9513     AddToWorkList(Load.getNode());
9514     AddUsersToWorkList(Load.getNode()); // Add users too
9515     // Make sure to revisit this node to clean it up; it will usually be dead.
9516     AddToWorkList(N);
9517     return SDValue(N, 0);
9518   }
9519
9520   return SDValue();
9521 }
9522
9523 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9524 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9525   // We perform this optimization post type-legalization because
9526   // the type-legalizer often scalarizes integer-promoted vectors.
9527   // Performing this optimization before may create bit-casts which
9528   // will be type-legalized to complex code sequences.
9529   // We perform this optimization only before the operation legalizer because we
9530   // may introduce illegal operations.
9531   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9532     return SDValue();
9533
9534   unsigned NumInScalars = N->getNumOperands();
9535   SDLoc dl(N);
9536   EVT VT = N->getValueType(0);
9537
9538   // Check to see if this is a BUILD_VECTOR of a bunch of values
9539   // which come from any_extend or zero_extend nodes. If so, we can create
9540   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9541   // optimizations. We do not handle sign-extend because we can't fill the sign
9542   // using shuffles.
9543   EVT SourceType = MVT::Other;
9544   bool AllAnyExt = true;
9545
9546   for (unsigned i = 0; i != NumInScalars; ++i) {
9547     SDValue In = N->getOperand(i);
9548     // Ignore undef inputs.
9549     if (In.getOpcode() == ISD::UNDEF) continue;
9550
9551     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9552     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9553
9554     // Abort if the element is not an extension.
9555     if (!ZeroExt && !AnyExt) {
9556       SourceType = MVT::Other;
9557       break;
9558     }
9559
9560     // The input is a ZeroExt or AnyExt. Check the original type.
9561     EVT InTy = In.getOperand(0).getValueType();
9562
9563     // Check that all of the widened source types are the same.
9564     if (SourceType == MVT::Other)
9565       // First time.
9566       SourceType = InTy;
9567     else if (InTy != SourceType) {
9568       // Multiple income types. Abort.
9569       SourceType = MVT::Other;
9570       break;
9571     }
9572
9573     // Check if all of the extends are ANY_EXTENDs.
9574     AllAnyExt &= AnyExt;
9575   }
9576
9577   // In order to have valid types, all of the inputs must be extended from the
9578   // same source type and all of the inputs must be any or zero extend.
9579   // Scalar sizes must be a power of two.
9580   EVT OutScalarTy = VT.getScalarType();
9581   bool ValidTypes = SourceType != MVT::Other &&
9582                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9583                  isPowerOf2_32(SourceType.getSizeInBits());
9584
9585   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9586   // turn into a single shuffle instruction.
9587   if (!ValidTypes)
9588     return SDValue();
9589
9590   bool isLE = TLI.isLittleEndian();
9591   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9592   assert(ElemRatio > 1 && "Invalid element size ratio");
9593   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9594                                DAG.getConstant(0, SourceType);
9595
9596   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9597   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9598
9599   // Populate the new build_vector
9600   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9601     SDValue Cast = N->getOperand(i);
9602     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9603             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9604             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9605     SDValue In;
9606     if (Cast.getOpcode() == ISD::UNDEF)
9607       In = DAG.getUNDEF(SourceType);
9608     else
9609       In = Cast->getOperand(0);
9610     unsigned Index = isLE ? (i * ElemRatio) :
9611                             (i * ElemRatio + (ElemRatio - 1));
9612
9613     assert(Index < Ops.size() && "Invalid index");
9614     Ops[Index] = In;
9615   }
9616
9617   // The type of the new BUILD_VECTOR node.
9618   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9619   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9620          "Invalid vector size");
9621   // Check if the new vector type is legal.
9622   if (!isTypeLegal(VecVT)) return SDValue();
9623
9624   // Make the new BUILD_VECTOR.
9625   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9626
9627   // The new BUILD_VECTOR node has the potential to be further optimized.
9628   AddToWorkList(BV.getNode());
9629   // Bitcast to the desired type.
9630   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9631 }
9632
9633 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9634   EVT VT = N->getValueType(0);
9635
9636   unsigned NumInScalars = N->getNumOperands();
9637   SDLoc dl(N);
9638
9639   EVT SrcVT = MVT::Other;
9640   unsigned Opcode = ISD::DELETED_NODE;
9641   unsigned NumDefs = 0;
9642
9643   for (unsigned i = 0; i != NumInScalars; ++i) {
9644     SDValue In = N->getOperand(i);
9645     unsigned Opc = In.getOpcode();
9646
9647     if (Opc == ISD::UNDEF)
9648       continue;
9649
9650     // If all scalar values are floats and converted from integers.
9651     if (Opcode == ISD::DELETED_NODE &&
9652         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9653       Opcode = Opc;
9654     }
9655
9656     if (Opc != Opcode)
9657       return SDValue();
9658
9659     EVT InVT = In.getOperand(0).getValueType();
9660
9661     // If all scalar values are typed differently, bail out. It's chosen to
9662     // simplify BUILD_VECTOR of integer types.
9663     if (SrcVT == MVT::Other)
9664       SrcVT = InVT;
9665     if (SrcVT != InVT)
9666       return SDValue();
9667     NumDefs++;
9668   }
9669
9670   // If the vector has just one element defined, it's not worth to fold it into
9671   // a vectorized one.
9672   if (NumDefs < 2)
9673     return SDValue();
9674
9675   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9676          && "Should only handle conversion from integer to float.");
9677   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9678
9679   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9680
9681   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9682     return SDValue();
9683
9684   SmallVector<SDValue, 8> Opnds;
9685   for (unsigned i = 0; i != NumInScalars; ++i) {
9686     SDValue In = N->getOperand(i);
9687
9688     if (In.getOpcode() == ISD::UNDEF)
9689       Opnds.push_back(DAG.getUNDEF(SrcVT));
9690     else
9691       Opnds.push_back(In.getOperand(0));
9692   }
9693   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9694                            &Opnds[0], Opnds.size());
9695   AddToWorkList(BV.getNode());
9696
9697   return DAG.getNode(Opcode, dl, VT, BV);
9698 }
9699
9700 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9701   unsigned NumInScalars = N->getNumOperands();
9702   SDLoc dl(N);
9703   EVT VT = N->getValueType(0);
9704
9705   // A vector built entirely of undefs is undef.
9706   if (ISD::allOperandsUndef(N))
9707     return DAG.getUNDEF(VT);
9708
9709   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9710   if (V.getNode())
9711     return V;
9712
9713   V = reduceBuildVecConvertToConvertBuildVec(N);
9714   if (V.getNode())
9715     return V;
9716
9717   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9718   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9719   // at most two distinct vectors, turn this into a shuffle node.
9720
9721   // May only combine to shuffle after legalize if shuffle is legal.
9722   if (LegalOperations &&
9723       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9724     return SDValue();
9725
9726   SDValue VecIn1, VecIn2;
9727   for (unsigned i = 0; i != NumInScalars; ++i) {
9728     // Ignore undef inputs.
9729     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9730
9731     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9732     // constant index, bail out.
9733     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9734         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9735       VecIn1 = VecIn2 = SDValue(0, 0);
9736       break;
9737     }
9738
9739     // We allow up to two distinct input vectors.
9740     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9741     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9742       continue;
9743
9744     if (VecIn1.getNode() == 0) {
9745       VecIn1 = ExtractedFromVec;
9746     } else if (VecIn2.getNode() == 0) {
9747       VecIn2 = ExtractedFromVec;
9748     } else {
9749       // Too many inputs.
9750       VecIn1 = VecIn2 = SDValue(0, 0);
9751       break;
9752     }
9753   }
9754
9755     // If everything is good, we can make a shuffle operation.
9756   if (VecIn1.getNode()) {
9757     SmallVector<int, 8> Mask;
9758     for (unsigned i = 0; i != NumInScalars; ++i) {
9759       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9760         Mask.push_back(-1);
9761         continue;
9762       }
9763
9764       // If extracting from the first vector, just use the index directly.
9765       SDValue Extract = N->getOperand(i);
9766       SDValue ExtVal = Extract.getOperand(1);
9767       if (Extract.getOperand(0) == VecIn1) {
9768         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9769         if (ExtIndex > VT.getVectorNumElements())
9770           return SDValue();
9771
9772         Mask.push_back(ExtIndex);
9773         continue;
9774       }
9775
9776       // Otherwise, use InIdx + VecSize
9777       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9778       Mask.push_back(Idx+NumInScalars);
9779     }
9780
9781     // We can't generate a shuffle node with mismatched input and output types.
9782     // Attempt to transform a single input vector to the correct type.
9783     if ((VT != VecIn1.getValueType())) {
9784       // We don't support shuffeling between TWO values of different types.
9785       if (VecIn2.getNode() != 0)
9786         return SDValue();
9787
9788       // We only support widening of vectors which are half the size of the
9789       // output registers. For example XMM->YMM widening on X86 with AVX.
9790       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9791         return SDValue();
9792
9793       // If the input vector type has a different base type to the output
9794       // vector type, bail out.
9795       if (VecIn1.getValueType().getVectorElementType() !=
9796           VT.getVectorElementType())
9797         return SDValue();
9798
9799       // Widen the input vector by adding undef values.
9800       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9801                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9802     }
9803
9804     // If VecIn2 is unused then change it to undef.
9805     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9806
9807     // Check that we were able to transform all incoming values to the same
9808     // type.
9809     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9810         VecIn1.getValueType() != VT)
9811           return SDValue();
9812
9813     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9814     if (!isTypeLegal(VT))
9815       return SDValue();
9816
9817     // Return the new VECTOR_SHUFFLE node.
9818     SDValue Ops[2];
9819     Ops[0] = VecIn1;
9820     Ops[1] = VecIn2;
9821     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9822   }
9823
9824   return SDValue();
9825 }
9826
9827 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9828   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9829   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9830   // inputs come from at most two distinct vectors, turn this into a shuffle
9831   // node.
9832
9833   // If we only have one input vector, we don't need to do any concatenation.
9834   if (N->getNumOperands() == 1)
9835     return N->getOperand(0);
9836
9837   // Check if all of the operands are undefs.
9838   if (ISD::allOperandsUndef(N))
9839     return DAG.getUNDEF(N->getValueType(0));
9840
9841   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9842   // nodes often generate nop CONCAT_VECTOR nodes.
9843   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9844   // place the incoming vectors at the exact same location.
9845   SDValue SingleSource = SDValue();
9846   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9847
9848   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9849     SDValue Op = N->getOperand(i);
9850
9851     if (Op.getOpcode() == ISD::UNDEF)
9852       continue;
9853
9854     // Check if this is the identity extract:
9855     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9856       return SDValue();
9857
9858     // Find the single incoming vector for the extract_subvector.
9859     if (SingleSource.getNode()) {
9860       if (Op.getOperand(0) != SingleSource)
9861         return SDValue();
9862     } else {
9863       SingleSource = Op.getOperand(0);
9864
9865       // Check the source type is the same as the type of the result.
9866       // If not, this concat may extend the vector, so we can not
9867       // optimize it away.
9868       if (SingleSource.getValueType() != N->getValueType(0))
9869         return SDValue();
9870     }
9871
9872     unsigned IdentityIndex = i * PartNumElem;
9873     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9874     // The extract index must be constant.
9875     if (!CS)
9876       return SDValue();
9877
9878     // Check that we are reading from the identity index.
9879     if (CS->getZExtValue() != IdentityIndex)
9880       return SDValue();
9881   }
9882
9883   if (SingleSource.getNode())
9884     return SingleSource;
9885
9886   return SDValue();
9887 }
9888
9889 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9890   EVT NVT = N->getValueType(0);
9891   SDValue V = N->getOperand(0);
9892
9893   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9894     // Combine:
9895     //    (extract_subvec (concat V1, V2, ...), i)
9896     // Into:
9897     //    Vi if possible
9898     // Only operand 0 is checked as 'concat' assumes all inputs of the same
9899     // type.
9900     if (V->getOperand(0).getValueType() != NVT)
9901       return SDValue();
9902     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9903     unsigned NumElems = NVT.getVectorNumElements();
9904     assert((Idx % NumElems) == 0 &&
9905            "IDX in concat is not a multiple of the result vector length.");
9906     return V->getOperand(Idx / NumElems);
9907   }
9908
9909   // Skip bitcasting
9910   if (V->getOpcode() == ISD::BITCAST)
9911     V = V.getOperand(0);
9912
9913   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9914     SDLoc dl(N);
9915     // Handle only simple case where vector being inserted and vector
9916     // being extracted are of same type, and are half size of larger vectors.
9917     EVT BigVT = V->getOperand(0).getValueType();
9918     EVT SmallVT = V->getOperand(1).getValueType();
9919     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9920       return SDValue();
9921
9922     // Only handle cases where both indexes are constants with the same type.
9923     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9924     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9925
9926     if (InsIdx && ExtIdx &&
9927         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9928         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9929       // Combine:
9930       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9931       // Into:
9932       //    indices are equal or bit offsets are equal => V1
9933       //    otherwise => (extract_subvec V1, ExtIdx)
9934       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9935           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9936         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9937       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9938                          DAG.getNode(ISD::BITCAST, dl,
9939                                      N->getOperand(0).getValueType(),
9940                                      V->getOperand(0)), N->getOperand(1));
9941     }
9942   }
9943
9944   return SDValue();
9945 }
9946
9947 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9948 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9949   EVT VT = N->getValueType(0);
9950   unsigned NumElts = VT.getVectorNumElements();
9951
9952   SDValue N0 = N->getOperand(0);
9953   SDValue N1 = N->getOperand(1);
9954   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9955
9956   SmallVector<SDValue, 4> Ops;
9957   EVT ConcatVT = N0.getOperand(0).getValueType();
9958   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9959   unsigned NumConcats = NumElts / NumElemsPerConcat;
9960
9961   // Look at every vector that's inserted. We're looking for exact
9962   // subvector-sized copies from a concatenated vector
9963   for (unsigned I = 0; I != NumConcats; ++I) {
9964     // Make sure we're dealing with a copy.
9965     unsigned Begin = I * NumElemsPerConcat;
9966     bool AllUndef = true, NoUndef = true;
9967     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9968       if (SVN->getMaskElt(J) >= 0)
9969         AllUndef = false;
9970       else
9971         NoUndef = false;
9972     }
9973
9974     if (NoUndef) {
9975       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9976         return SDValue();
9977
9978       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9979         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9980           return SDValue();
9981
9982       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9983       if (FirstElt < N0.getNumOperands())
9984         Ops.push_back(N0.getOperand(FirstElt));
9985       else
9986         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9987
9988     } else if (AllUndef) {
9989       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9990     } else { // Mixed with general masks and undefs, can't do optimization.
9991       return SDValue();
9992     }
9993   }
9994
9995   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9996                      Ops.size());
9997 }
9998
9999 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10000   EVT VT = N->getValueType(0);
10001   unsigned NumElts = VT.getVectorNumElements();
10002
10003   SDValue N0 = N->getOperand(0);
10004   SDValue N1 = N->getOperand(1);
10005
10006   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10007
10008   // Canonicalize shuffle undef, undef -> undef
10009   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10010     return DAG.getUNDEF(VT);
10011
10012   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10013
10014   // Canonicalize shuffle v, v -> v, undef
10015   if (N0 == N1) {
10016     SmallVector<int, 8> NewMask;
10017     for (unsigned i = 0; i != NumElts; ++i) {
10018       int Idx = SVN->getMaskElt(i);
10019       if (Idx >= (int)NumElts) Idx -= NumElts;
10020       NewMask.push_back(Idx);
10021     }
10022     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10023                                 &NewMask[0]);
10024   }
10025
10026   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10027   if (N0.getOpcode() == ISD::UNDEF) {
10028     SmallVector<int, 8> NewMask;
10029     for (unsigned i = 0; i != NumElts; ++i) {
10030       int Idx = SVN->getMaskElt(i);
10031       if (Idx >= 0) {
10032         if (Idx >= (int)NumElts)
10033           Idx -= NumElts;
10034         else
10035           Idx = -1; // remove reference to lhs
10036       }
10037       NewMask.push_back(Idx);
10038     }
10039     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10040                                 &NewMask[0]);
10041   }
10042
10043   // Remove references to rhs if it is undef
10044   if (N1.getOpcode() == ISD::UNDEF) {
10045     bool Changed = false;
10046     SmallVector<int, 8> NewMask;
10047     for (unsigned i = 0; i != NumElts; ++i) {
10048       int Idx = SVN->getMaskElt(i);
10049       if (Idx >= (int)NumElts) {
10050         Idx = -1;
10051         Changed = true;
10052       }
10053       NewMask.push_back(Idx);
10054     }
10055     if (Changed)
10056       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10057   }
10058
10059   // If it is a splat, check if the argument vector is another splat or a
10060   // build_vector with all scalar elements the same.
10061   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10062     SDNode *V = N0.getNode();
10063
10064     // If this is a bit convert that changes the element type of the vector but
10065     // not the number of vector elements, look through it.  Be careful not to
10066     // look though conversions that change things like v4f32 to v2f64.
10067     if (V->getOpcode() == ISD::BITCAST) {
10068       SDValue ConvInput = V->getOperand(0);
10069       if (ConvInput.getValueType().isVector() &&
10070           ConvInput.getValueType().getVectorNumElements() == NumElts)
10071         V = ConvInput.getNode();
10072     }
10073
10074     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10075       assert(V->getNumOperands() == NumElts &&
10076              "BUILD_VECTOR has wrong number of operands");
10077       SDValue Base;
10078       bool AllSame = true;
10079       for (unsigned i = 0; i != NumElts; ++i) {
10080         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10081           Base = V->getOperand(i);
10082           break;
10083         }
10084       }
10085       // Splat of <u, u, u, u>, return <u, u, u, u>
10086       if (!Base.getNode())
10087         return N0;
10088       for (unsigned i = 0; i != NumElts; ++i) {
10089         if (V->getOperand(i) != Base) {
10090           AllSame = false;
10091           break;
10092         }
10093       }
10094       // Splat of <x, x, x, x>, return <x, x, x, x>
10095       if (AllSame)
10096         return N0;
10097     }
10098   }
10099
10100   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10101       Level < AfterLegalizeVectorOps &&
10102       (N1.getOpcode() == ISD::UNDEF ||
10103       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10104        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10105     SDValue V = partitionShuffleOfConcats(N, DAG);
10106
10107     if (V.getNode())
10108       return V;
10109   }
10110
10111   // If this shuffle node is simply a swizzle of another shuffle node,
10112   // and it reverses the swizzle of the previous shuffle then we can
10113   // optimize shuffle(shuffle(x, undef), undef) -> x.
10114   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10115       N1.getOpcode() == ISD::UNDEF) {
10116
10117     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10118
10119     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10120     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10121       return SDValue();
10122
10123     // The incoming shuffle must be of the same type as the result of the
10124     // current shuffle.
10125     assert(OtherSV->getOperand(0).getValueType() == VT &&
10126            "Shuffle types don't match");
10127
10128     for (unsigned i = 0; i != NumElts; ++i) {
10129       int Idx = SVN->getMaskElt(i);
10130       assert(Idx < (int)NumElts && "Index references undef operand");
10131       // Next, this index comes from the first value, which is the incoming
10132       // shuffle. Adopt the incoming index.
10133       if (Idx >= 0)
10134         Idx = OtherSV->getMaskElt(Idx);
10135
10136       // The combined shuffle must map each index to itself.
10137       if (Idx >= 0 && (unsigned)Idx != i)
10138         return SDValue();
10139     }
10140
10141     return OtherSV->getOperand(0);
10142   }
10143
10144   return SDValue();
10145 }
10146
10147 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10148 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10149 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10150 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10151 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10152   EVT VT = N->getValueType(0);
10153   SDLoc dl(N);
10154   SDValue LHS = N->getOperand(0);
10155   SDValue RHS = N->getOperand(1);
10156   if (N->getOpcode() == ISD::AND) {
10157     if (RHS.getOpcode() == ISD::BITCAST)
10158       RHS = RHS.getOperand(0);
10159     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10160       SmallVector<int, 8> Indices;
10161       unsigned NumElts = RHS.getNumOperands();
10162       for (unsigned i = 0; i != NumElts; ++i) {
10163         SDValue Elt = RHS.getOperand(i);
10164         if (!isa<ConstantSDNode>(Elt))
10165           return SDValue();
10166
10167         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10168           Indices.push_back(i);
10169         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10170           Indices.push_back(NumElts);
10171         else
10172           return SDValue();
10173       }
10174
10175       // Let's see if the target supports this vector_shuffle.
10176       EVT RVT = RHS.getValueType();
10177       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10178         return SDValue();
10179
10180       // Return the new VECTOR_SHUFFLE node.
10181       EVT EltVT = RVT.getVectorElementType();
10182       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10183                                      DAG.getConstant(0, EltVT));
10184       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10185                                  RVT, &ZeroOps[0], ZeroOps.size());
10186       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10187       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10188       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10189     }
10190   }
10191
10192   return SDValue();
10193 }
10194
10195 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10196 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10197   assert(N->getValueType(0).isVector() &&
10198          "SimplifyVBinOp only works on vectors!");
10199
10200   SDValue LHS = N->getOperand(0);
10201   SDValue RHS = N->getOperand(1);
10202   SDValue Shuffle = XformToShuffleWithZero(N);
10203   if (Shuffle.getNode()) return Shuffle;
10204
10205   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10206   // this operation.
10207   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10208       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10209     SmallVector<SDValue, 8> Ops;
10210     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10211       SDValue LHSOp = LHS.getOperand(i);
10212       SDValue RHSOp = RHS.getOperand(i);
10213       // If these two elements can't be folded, bail out.
10214       if ((LHSOp.getOpcode() != ISD::UNDEF &&
10215            LHSOp.getOpcode() != ISD::Constant &&
10216            LHSOp.getOpcode() != ISD::ConstantFP) ||
10217           (RHSOp.getOpcode() != ISD::UNDEF &&
10218            RHSOp.getOpcode() != ISD::Constant &&
10219            RHSOp.getOpcode() != ISD::ConstantFP))
10220         break;
10221
10222       // Can't fold divide by zero.
10223       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10224           N->getOpcode() == ISD::FDIV) {
10225         if ((RHSOp.getOpcode() == ISD::Constant &&
10226              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10227             (RHSOp.getOpcode() == ISD::ConstantFP &&
10228              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10229           break;
10230       }
10231
10232       EVT VT = LHSOp.getValueType();
10233       EVT RVT = RHSOp.getValueType();
10234       if (RVT != VT) {
10235         // Integer BUILD_VECTOR operands may have types larger than the element
10236         // size (e.g., when the element type is not legal).  Prior to type
10237         // legalization, the types may not match between the two BUILD_VECTORS.
10238         // Truncate one of the operands to make them match.
10239         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10240           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10241         } else {
10242           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10243           VT = RVT;
10244         }
10245       }
10246       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10247                                    LHSOp, RHSOp);
10248       if (FoldOp.getOpcode() != ISD::UNDEF &&
10249           FoldOp.getOpcode() != ISD::Constant &&
10250           FoldOp.getOpcode() != ISD::ConstantFP)
10251         break;
10252       Ops.push_back(FoldOp);
10253       AddToWorkList(FoldOp.getNode());
10254     }
10255
10256     if (Ops.size() == LHS.getNumOperands())
10257       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10258                          LHS.getValueType(), &Ops[0], Ops.size());
10259   }
10260
10261   return SDValue();
10262 }
10263
10264 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10265 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10266   assert(N->getValueType(0).isVector() &&
10267          "SimplifyVUnaryOp only works on vectors!");
10268
10269   SDValue N0 = N->getOperand(0);
10270
10271   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10272     return SDValue();
10273
10274   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10275   SmallVector<SDValue, 8> Ops;
10276   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10277     SDValue Op = N0.getOperand(i);
10278     if (Op.getOpcode() != ISD::UNDEF &&
10279         Op.getOpcode() != ISD::ConstantFP)
10280       break;
10281     EVT EltVT = Op.getValueType();
10282     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10283     if (FoldOp.getOpcode() != ISD::UNDEF &&
10284         FoldOp.getOpcode() != ISD::ConstantFP)
10285       break;
10286     Ops.push_back(FoldOp);
10287     AddToWorkList(FoldOp.getNode());
10288   }
10289
10290   if (Ops.size() != N0.getNumOperands())
10291     return SDValue();
10292
10293   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10294                      N0.getValueType(), &Ops[0], Ops.size());
10295 }
10296
10297 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10298                                     SDValue N1, SDValue N2){
10299   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10300
10301   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10302                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10303
10304   // If we got a simplified select_cc node back from SimplifySelectCC, then
10305   // break it down into a new SETCC node, and a new SELECT node, and then return
10306   // the SELECT node, since we were called with a SELECT node.
10307   if (SCC.getNode()) {
10308     // Check to see if we got a select_cc back (to turn into setcc/select).
10309     // Otherwise, just return whatever node we got back, like fabs.
10310     if (SCC.getOpcode() == ISD::SELECT_CC) {
10311       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10312                                   N0.getValueType(),
10313                                   SCC.getOperand(0), SCC.getOperand(1),
10314                                   SCC.getOperand(4));
10315       AddToWorkList(SETCC.getNode());
10316       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10317                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10318     }
10319
10320     return SCC;
10321   }
10322   return SDValue();
10323 }
10324
10325 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10326 /// are the two values being selected between, see if we can simplify the
10327 /// select.  Callers of this should assume that TheSelect is deleted if this
10328 /// returns true.  As such, they should return the appropriate thing (e.g. the
10329 /// node) back to the top-level of the DAG combiner loop to avoid it being
10330 /// looked at.
10331 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10332                                     SDValue RHS) {
10333
10334   // Cannot simplify select with vector condition
10335   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10336
10337   // If this is a select from two identical things, try to pull the operation
10338   // through the select.
10339   if (LHS.getOpcode() != RHS.getOpcode() ||
10340       !LHS.hasOneUse() || !RHS.hasOneUse())
10341     return false;
10342
10343   // If this is a load and the token chain is identical, replace the select
10344   // of two loads with a load through a select of the address to load from.
10345   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10346   // constants have been dropped into the constant pool.
10347   if (LHS.getOpcode() == ISD::LOAD) {
10348     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10349     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10350
10351     // Token chains must be identical.
10352     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10353         // Do not let this transformation reduce the number of volatile loads.
10354         LLD->isVolatile() || RLD->isVolatile() ||
10355         // If this is an EXTLOAD, the VT's must match.
10356         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10357         // If this is an EXTLOAD, the kind of extension must match.
10358         (LLD->getExtensionType() != RLD->getExtensionType() &&
10359          // The only exception is if one of the extensions is anyext.
10360          LLD->getExtensionType() != ISD::EXTLOAD &&
10361          RLD->getExtensionType() != ISD::EXTLOAD) ||
10362         // FIXME: this discards src value information.  This is
10363         // over-conservative. It would be beneficial to be able to remember
10364         // both potential memory locations.  Since we are discarding
10365         // src value info, don't do the transformation if the memory
10366         // locations are not in the default address space.
10367         LLD->getPointerInfo().getAddrSpace() != 0 ||
10368         RLD->getPointerInfo().getAddrSpace() != 0 ||
10369         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10370                                       LLD->getBasePtr().getValueType()))
10371       return false;
10372
10373     // Check that the select condition doesn't reach either load.  If so,
10374     // folding this will induce a cycle into the DAG.  If not, this is safe to
10375     // xform, so create a select of the addresses.
10376     SDValue Addr;
10377     if (TheSelect->getOpcode() == ISD::SELECT) {
10378       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10379       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10380           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10381         return false;
10382       // The loads must not depend on one another.
10383       if (LLD->isPredecessorOf(RLD) ||
10384           RLD->isPredecessorOf(LLD))
10385         return false;
10386       Addr = DAG.getSelect(SDLoc(TheSelect),
10387                            LLD->getBasePtr().getValueType(),
10388                            TheSelect->getOperand(0), LLD->getBasePtr(),
10389                            RLD->getBasePtr());
10390     } else {  // Otherwise SELECT_CC
10391       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10392       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10393
10394       if ((LLD->hasAnyUseOfValue(1) &&
10395            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10396           (RLD->hasAnyUseOfValue(1) &&
10397            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10398         return false;
10399
10400       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10401                          LLD->getBasePtr().getValueType(),
10402                          TheSelect->getOperand(0),
10403                          TheSelect->getOperand(1),
10404                          LLD->getBasePtr(), RLD->getBasePtr(),
10405                          TheSelect->getOperand(4));
10406     }
10407
10408     SDValue Load;
10409     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10410       Load = DAG.getLoad(TheSelect->getValueType(0),
10411                          SDLoc(TheSelect),
10412                          // FIXME: Discards pointer info.
10413                          LLD->getChain(), Addr, MachinePointerInfo(),
10414                          LLD->isVolatile(), LLD->isNonTemporal(),
10415                          LLD->isInvariant(), LLD->getAlignment());
10416     } else {
10417       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10418                             RLD->getExtensionType() : LLD->getExtensionType(),
10419                             SDLoc(TheSelect),
10420                             TheSelect->getValueType(0),
10421                             // FIXME: Discards pointer info.
10422                             LLD->getChain(), Addr, MachinePointerInfo(),
10423                             LLD->getMemoryVT(), LLD->isVolatile(),
10424                             LLD->isNonTemporal(), LLD->getAlignment());
10425     }
10426
10427     // Users of the select now use the result of the load.
10428     CombineTo(TheSelect, Load);
10429
10430     // Users of the old loads now use the new load's chain.  We know the
10431     // old-load value is dead now.
10432     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10433     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10434     return true;
10435   }
10436
10437   return false;
10438 }
10439
10440 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10441 /// where 'cond' is the comparison specified by CC.
10442 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10443                                       SDValue N2, SDValue N3,
10444                                       ISD::CondCode CC, bool NotExtCompare) {
10445   // (x ? y : y) -> y.
10446   if (N2 == N3) return N2;
10447
10448   EVT VT = N2.getValueType();
10449   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10450   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10451   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10452
10453   // Determine if the condition we're dealing with is constant
10454   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10455                               N0, N1, CC, DL, false);
10456   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10457   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10458
10459   // fold select_cc true, x, y -> x
10460   if (SCCC && !SCCC->isNullValue())
10461     return N2;
10462   // fold select_cc false, x, y -> y
10463   if (SCCC && SCCC->isNullValue())
10464     return N3;
10465
10466   // Check to see if we can simplify the select into an fabs node
10467   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10468     // Allow either -0.0 or 0.0
10469     if (CFP->getValueAPF().isZero()) {
10470       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10471       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10472           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10473           N2 == N3.getOperand(0))
10474         return DAG.getNode(ISD::FABS, DL, VT, N0);
10475
10476       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10477       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10478           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10479           N2.getOperand(0) == N3)
10480         return DAG.getNode(ISD::FABS, DL, VT, N3);
10481     }
10482   }
10483
10484   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10485   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10486   // in it.  This is a win when the constant is not otherwise available because
10487   // it replaces two constant pool loads with one.  We only do this if the FP
10488   // type is known to be legal, because if it isn't, then we are before legalize
10489   // types an we want the other legalization to happen first (e.g. to avoid
10490   // messing with soft float) and if the ConstantFP is not legal, because if
10491   // it is legal, we may not need to store the FP constant in a constant pool.
10492   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10493     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10494       if (TLI.isTypeLegal(N2.getValueType()) &&
10495           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10496            TargetLowering::Legal) &&
10497           // If both constants have multiple uses, then we won't need to do an
10498           // extra load, they are likely around in registers for other users.
10499           (TV->hasOneUse() || FV->hasOneUse())) {
10500         Constant *Elts[] = {
10501           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10502           const_cast<ConstantFP*>(TV->getConstantFPValue())
10503         };
10504         Type *FPTy = Elts[0]->getType();
10505         const DataLayout &TD = *TLI.getDataLayout();
10506
10507         // Create a ConstantArray of the two constants.
10508         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10509         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10510                                             TD.getPrefTypeAlignment(FPTy));
10511         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10512
10513         // Get the offsets to the 0 and 1 element of the array so that we can
10514         // select between them.
10515         SDValue Zero = DAG.getIntPtrConstant(0);
10516         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10517         SDValue One = DAG.getIntPtrConstant(EltSize);
10518
10519         SDValue Cond = DAG.getSetCC(DL,
10520                                     getSetCCResultType(N0.getValueType()),
10521                                     N0, N1, CC);
10522         AddToWorkList(Cond.getNode());
10523         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10524                                           Cond, One, Zero);
10525         AddToWorkList(CstOffset.getNode());
10526         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10527                             CstOffset);
10528         AddToWorkList(CPIdx.getNode());
10529         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10530                            MachinePointerInfo::getConstantPool(), false,
10531                            false, false, Alignment);
10532
10533       }
10534     }
10535
10536   // Check to see if we can perform the "gzip trick", transforming
10537   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10538   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10539       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10540        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10541     EVT XType = N0.getValueType();
10542     EVT AType = N2.getValueType();
10543     if (XType.bitsGE(AType)) {
10544       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10545       // single-bit constant.
10546       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10547         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10548         ShCtV = XType.getSizeInBits()-ShCtV-1;
10549         SDValue ShCt = DAG.getConstant(ShCtV,
10550                                        getShiftAmountTy(N0.getValueType()));
10551         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10552                                     XType, N0, ShCt);
10553         AddToWorkList(Shift.getNode());
10554
10555         if (XType.bitsGT(AType)) {
10556           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10557           AddToWorkList(Shift.getNode());
10558         }
10559
10560         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10561       }
10562
10563       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10564                                   XType, N0,
10565                                   DAG.getConstant(XType.getSizeInBits()-1,
10566                                          getShiftAmountTy(N0.getValueType())));
10567       AddToWorkList(Shift.getNode());
10568
10569       if (XType.bitsGT(AType)) {
10570         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10571         AddToWorkList(Shift.getNode());
10572       }
10573
10574       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10575     }
10576   }
10577
10578   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10579   // where y is has a single bit set.
10580   // A plaintext description would be, we can turn the SELECT_CC into an AND
10581   // when the condition can be materialized as an all-ones register.  Any
10582   // single bit-test can be materialized as an all-ones register with
10583   // shift-left and shift-right-arith.
10584   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10585       N0->getValueType(0) == VT &&
10586       N1C && N1C->isNullValue() &&
10587       N2C && N2C->isNullValue()) {
10588     SDValue AndLHS = N0->getOperand(0);
10589     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10590     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10591       // Shift the tested bit over the sign bit.
10592       APInt AndMask = ConstAndRHS->getAPIntValue();
10593       SDValue ShlAmt =
10594         DAG.getConstant(AndMask.countLeadingZeros(),
10595                         getShiftAmountTy(AndLHS.getValueType()));
10596       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10597
10598       // Now arithmetic right shift it all the way over, so the result is either
10599       // all-ones, or zero.
10600       SDValue ShrAmt =
10601         DAG.getConstant(AndMask.getBitWidth()-1,
10602                         getShiftAmountTy(Shl.getValueType()));
10603       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10604
10605       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10606     }
10607   }
10608
10609   // fold select C, 16, 0 -> shl C, 4
10610   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10611     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10612       TargetLowering::ZeroOrOneBooleanContent) {
10613
10614     // If the caller doesn't want us to simplify this into a zext of a compare,
10615     // don't do it.
10616     if (NotExtCompare && N2C->getAPIntValue() == 1)
10617       return SDValue();
10618
10619     // Get a SetCC of the condition
10620     // NOTE: Don't create a SETCC if it's not legal on this target.
10621     if (!LegalOperations ||
10622         TLI.isOperationLegal(ISD::SETCC,
10623           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10624       SDValue Temp, SCC;
10625       // cast from setcc result type to select result type
10626       if (LegalTypes) {
10627         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10628                             N0, N1, CC);
10629         if (N2.getValueType().bitsLT(SCC.getValueType()))
10630           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10631                                         N2.getValueType());
10632         else
10633           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10634                              N2.getValueType(), SCC);
10635       } else {
10636         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10637         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10638                            N2.getValueType(), SCC);
10639       }
10640
10641       AddToWorkList(SCC.getNode());
10642       AddToWorkList(Temp.getNode());
10643
10644       if (N2C->getAPIntValue() == 1)
10645         return Temp;
10646
10647       // shl setcc result by log2 n2c
10648       return DAG.getNode(
10649           ISD::SHL, DL, N2.getValueType(), Temp,
10650           DAG.getConstant(N2C->getAPIntValue().logBase2(),
10651                           getShiftAmountTy(Temp.getValueType())));
10652     }
10653   }
10654
10655   // Check to see if this is the equivalent of setcc
10656   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10657   // otherwise, go ahead with the folds.
10658   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10659     EVT XType = N0.getValueType();
10660     if (!LegalOperations ||
10661         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10662       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10663       if (Res.getValueType() != VT)
10664         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10665       return Res;
10666     }
10667
10668     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10669     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10670         (!LegalOperations ||
10671          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10672       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10673       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10674                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10675                                        getShiftAmountTy(Ctlz.getValueType())));
10676     }
10677     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10678     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10679       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10680                                   XType, DAG.getConstant(0, XType), N0);
10681       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10682       return DAG.getNode(ISD::SRL, DL, XType,
10683                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10684                          DAG.getConstant(XType.getSizeInBits()-1,
10685                                          getShiftAmountTy(XType)));
10686     }
10687     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10688     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10689       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10690                                  DAG.getConstant(XType.getSizeInBits()-1,
10691                                          getShiftAmountTy(N0.getValueType())));
10692       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10693     }
10694   }
10695
10696   // Check to see if this is an integer abs.
10697   // select_cc setg[te] X,  0,  X, -X ->
10698   // select_cc setgt    X, -1,  X, -X ->
10699   // select_cc setl[te] X,  0, -X,  X ->
10700   // select_cc setlt    X,  1, -X,  X ->
10701   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10702   if (N1C) {
10703     ConstantSDNode *SubC = NULL;
10704     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10705          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10706         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10707       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10708     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10709               (N1C->isOne() && CC == ISD::SETLT)) &&
10710              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10711       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10712
10713     EVT XType = N0.getValueType();
10714     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10715       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10716                                   N0,
10717                                   DAG.getConstant(XType.getSizeInBits()-1,
10718                                          getShiftAmountTy(N0.getValueType())));
10719       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10720                                 XType, N0, Shift);
10721       AddToWorkList(Shift.getNode());
10722       AddToWorkList(Add.getNode());
10723       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10724     }
10725   }
10726
10727   return SDValue();
10728 }
10729
10730 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10731 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10732                                    SDValue N1, ISD::CondCode Cond,
10733                                    SDLoc DL, bool foldBooleans) {
10734   TargetLowering::DAGCombinerInfo
10735     DagCombineInfo(DAG, Level, false, this);
10736   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10737 }
10738
10739 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10740 /// return a DAG expression to select that will generate the same value by
10741 /// multiplying by a magic number.  See:
10742 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10743 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10744   std::vector<SDNode*> Built;
10745   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10746
10747   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10748        ii != ee; ++ii)
10749     AddToWorkList(*ii);
10750   return S;
10751 }
10752
10753 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10754 /// return a DAG expression to select that will generate the same value by
10755 /// multiplying by a magic number.  See:
10756 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10757 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10758   std::vector<SDNode*> Built;
10759   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10760
10761   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10762        ii != ee; ++ii)
10763     AddToWorkList(*ii);
10764   return S;
10765 }
10766
10767 /// FindBaseOffset - Return true if base is a frame index, which is known not
10768 // to alias with anything but itself.  Provides base object and offset as
10769 // results.
10770 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10771                            const GlobalValue *&GV, const void *&CV) {
10772   // Assume it is a primitive operation.
10773   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10774
10775   // If it's an adding a simple constant then integrate the offset.
10776   if (Base.getOpcode() == ISD::ADD) {
10777     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10778       Base = Base.getOperand(0);
10779       Offset += C->getZExtValue();
10780     }
10781   }
10782
10783   // Return the underlying GlobalValue, and update the Offset.  Return false
10784   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10785   // by multiple nodes with different offsets.
10786   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10787     GV = G->getGlobal();
10788     Offset += G->getOffset();
10789     return false;
10790   }
10791
10792   // Return the underlying Constant value, and update the Offset.  Return false
10793   // for ConstantSDNodes since the same constant pool entry may be represented
10794   // by multiple nodes with different offsets.
10795   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10796     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10797                                          : (const void *)C->getConstVal();
10798     Offset += C->getOffset();
10799     return false;
10800   }
10801   // If it's any of the following then it can't alias with anything but itself.
10802   return isa<FrameIndexSDNode>(Base);
10803 }
10804
10805 /// isAlias - Return true if there is any possibility that the two addresses
10806 /// overlap.
10807 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10808                           const Value *SrcValue1, int SrcValueOffset1,
10809                           unsigned SrcValueAlign1,
10810                           const MDNode *TBAAInfo1,
10811                           SDValue Ptr2, int64_t Size2,
10812                           const Value *SrcValue2, int SrcValueOffset2,
10813                           unsigned SrcValueAlign2,
10814                           const MDNode *TBAAInfo2) const {
10815   // If they are the same then they must be aliases.
10816   if (Ptr1 == Ptr2) return true;
10817
10818   // Gather base node and offset information.
10819   SDValue Base1, Base2;
10820   int64_t Offset1, Offset2;
10821   const GlobalValue *GV1, *GV2;
10822   const void *CV1, *CV2;
10823   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10824   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10825
10826   // If they have a same base address then check to see if they overlap.
10827   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10828     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10829
10830   // It is possible for different frame indices to alias each other, mostly
10831   // when tail call optimization reuses return address slots for arguments.
10832   // To catch this case, look up the actual index of frame indices to compute
10833   // the real alias relationship.
10834   if (isFrameIndex1 && isFrameIndex2) {
10835     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10836     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10837     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10838     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10839   }
10840
10841   // Otherwise, if we know what the bases are, and they aren't identical, then
10842   // we know they cannot alias.
10843   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10844     return false;
10845
10846   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10847   // compared to the size and offset of the access, we may be able to prove they
10848   // do not alias.  This check is conservative for now to catch cases created by
10849   // splitting vector types.
10850   if ((SrcValueAlign1 == SrcValueAlign2) &&
10851       (SrcValueOffset1 != SrcValueOffset2) &&
10852       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10853     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10854     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10855
10856     // There is no overlap between these relatively aligned accesses of similar
10857     // size, return no alias.
10858     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10859       return false;
10860   }
10861
10862   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10863     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10864   if (UseAA && SrcValue1 && SrcValue2) {
10865     // Use alias analysis information.
10866     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10867     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10868     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10869     AliasAnalysis::AliasResult AAResult =
10870       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10871                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10872     if (AAResult == AliasAnalysis::NoAlias)
10873       return false;
10874   }
10875
10876   // Otherwise we have to assume they alias.
10877   return true;
10878 }
10879
10880 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10881   SDValue Ptr0, Ptr1;
10882   int64_t Size0, Size1;
10883   const Value *SrcValue0, *SrcValue1;
10884   int SrcValueOffset0, SrcValueOffset1;
10885   unsigned SrcValueAlign0, SrcValueAlign1;
10886   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10887   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10888                 SrcValueAlign0, SrcTBAAInfo0);
10889   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10890                 SrcValueAlign1, SrcTBAAInfo1);
10891   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10892                  SrcValueAlign0, SrcTBAAInfo0,
10893                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10894                  SrcValueAlign1, SrcTBAAInfo1);
10895 }
10896
10897 /// FindAliasInfo - Extracts the relevant alias information from the memory
10898 /// node.  Returns true if the operand was a load.
10899 bool DAGCombiner::FindAliasInfo(SDNode *N,
10900                                 SDValue &Ptr, int64_t &Size,
10901                                 const Value *&SrcValue,
10902                                 int &SrcValueOffset,
10903                                 unsigned &SrcValueAlign,
10904                                 const MDNode *&TBAAInfo) const {
10905   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10906
10907   Ptr = LS->getBasePtr();
10908   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10909   SrcValue = LS->getSrcValue();
10910   SrcValueOffset = LS->getSrcValueOffset();
10911   SrcValueAlign = LS->getOriginalAlignment();
10912   TBAAInfo = LS->getTBAAInfo();
10913   return isa<LoadSDNode>(LS);
10914 }
10915
10916 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10917 /// looking for aliasing nodes and adding them to the Aliases vector.
10918 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10919                                    SmallVectorImpl<SDValue> &Aliases) {
10920   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10921   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10922
10923   // Get alias information for node.
10924   SDValue Ptr;
10925   int64_t Size;
10926   const Value *SrcValue;
10927   int SrcValueOffset;
10928   unsigned SrcValueAlign;
10929   const MDNode *SrcTBAAInfo;
10930   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10931                               SrcValueAlign, SrcTBAAInfo);
10932
10933   // Starting off.
10934   Chains.push_back(OriginalChain);
10935   unsigned Depth = 0;
10936
10937   // Look at each chain and determine if it is an alias.  If so, add it to the
10938   // aliases list.  If not, then continue up the chain looking for the next
10939   // candidate.
10940   while (!Chains.empty()) {
10941     SDValue Chain = Chains.back();
10942     Chains.pop_back();
10943
10944     // For TokenFactor nodes, look at each operand and only continue up the
10945     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10946     // find more and revert to original chain since the xform is unlikely to be
10947     // profitable.
10948     //
10949     // FIXME: The depth check could be made to return the last non-aliasing
10950     // chain we found before we hit a tokenfactor rather than the original
10951     // chain.
10952     if (Depth > 6 || Aliases.size() == 2) {
10953       Aliases.clear();
10954       Aliases.push_back(OriginalChain);
10955       break;
10956     }
10957
10958     // Don't bother if we've been before.
10959     if (!Visited.insert(Chain.getNode()))
10960       continue;
10961
10962     switch (Chain.getOpcode()) {
10963     case ISD::EntryToken:
10964       // Entry token is ideal chain operand, but handled in FindBetterChain.
10965       break;
10966
10967     case ISD::LOAD:
10968     case ISD::STORE: {
10969       // Get alias information for Chain.
10970       SDValue OpPtr;
10971       int64_t OpSize;
10972       const Value *OpSrcValue;
10973       int OpSrcValueOffset;
10974       unsigned OpSrcValueAlign;
10975       const MDNode *OpSrcTBAAInfo;
10976       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10977                                     OpSrcValue, OpSrcValueOffset,
10978                                     OpSrcValueAlign,
10979                                     OpSrcTBAAInfo);
10980
10981       // If chain is alias then stop here.
10982       if (!(IsLoad && IsOpLoad) &&
10983           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10984                   SrcTBAAInfo,
10985                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10986                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10987         Aliases.push_back(Chain);
10988       } else {
10989         // Look further up the chain.
10990         Chains.push_back(Chain.getOperand(0));
10991         ++Depth;
10992       }
10993       break;
10994     }
10995
10996     case ISD::TokenFactor:
10997       // We have to check each of the operands of the token factor for "small"
10998       // token factors, so we queue them up.  Adding the operands to the queue
10999       // (stack) in reverse order maintains the original order and increases the
11000       // likelihood that getNode will find a matching token factor (CSE.)
11001       if (Chain.getNumOperands() > 16) {
11002         Aliases.push_back(Chain);
11003         break;
11004       }
11005       for (unsigned n = Chain.getNumOperands(); n;)
11006         Chains.push_back(Chain.getOperand(--n));
11007       ++Depth;
11008       break;
11009
11010     default:
11011       // For all other instructions we will just have to take what we can get.
11012       Aliases.push_back(Chain);
11013       break;
11014     }
11015   }
11016 }
11017
11018 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11019 /// for a better chain (aliasing node.)
11020 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11021   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11022
11023   // Accumulate all the aliases to this node.
11024   GatherAllAliases(N, OldChain, Aliases);
11025
11026   // If no operands then chain to entry token.
11027   if (Aliases.size() == 0)
11028     return DAG.getEntryNode();
11029
11030   // If a single operand then chain to it.  We don't need to revisit it.
11031   if (Aliases.size() == 1)
11032     return Aliases[0];
11033
11034   // Construct a custom tailored token factor.
11035   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11036                      &Aliases[0], Aliases.size());
11037 }
11038
11039 // SelectionDAG::Combine - This is the entry point for the file.
11040 //
11041 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11042                            CodeGenOpt::Level OptLevel) {
11043   /// run - This is the main entry point to this class.
11044   ///
11045   DAGCombiner(*this, AA, OptLevel).Run(Level);
11046 }