[DAGCombiner] Slice a big load in two loads when the element are next to each
[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) : TLI.getPointerTy();
353     }
354
355     /// isTypeLegal - This method returns true if we are running before type
356     /// legalization or if the specified VT is legal.
357     bool isTypeLegal(const EVT &VT) {
358       if (!LegalTypes) return true;
359       return TLI.isTypeLegal(VT);
360     }
361
362     /// getSetCCResultType - Convenience wrapper around
363     /// TargetLowering::getSetCCResultType
364     EVT getSetCCResultType(EVT VT) const {
365       return TLI.getSetCCResultType(*DAG.getContext(), VT);
366     }
367   };
368 }
369
370
371 namespace {
372 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
373 /// nodes from the worklist.
374 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
375   DAGCombiner &DC;
376 public:
377   explicit WorkListRemover(DAGCombiner &dc)
378     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
379
380   virtual void NodeDeleted(SDNode *N, SDNode *E) {
381     DC.removeFromWorkList(N);
382   }
383 };
384 }
385
386 //===----------------------------------------------------------------------===//
387 //  TargetLowering::DAGCombinerInfo implementation
388 //===----------------------------------------------------------------------===//
389
390 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
391   ((DAGCombiner*)DC)->AddToWorkList(N);
392 }
393
394 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
395   ((DAGCombiner*)DC)->removeFromWorkList(N);
396 }
397
398 SDValue TargetLowering::DAGCombinerInfo::
399 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
400   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
401 }
402
403 SDValue TargetLowering::DAGCombinerInfo::
404 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
405   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
406 }
407
408
409 SDValue TargetLowering::DAGCombinerInfo::
410 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
411   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
412 }
413
414 void TargetLowering::DAGCombinerInfo::
415 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
416   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
417 }
418
419 //===----------------------------------------------------------------------===//
420 // Helper Functions
421 //===----------------------------------------------------------------------===//
422
423 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
424 /// specified expression for the same cost as the expression itself, or 2 if we
425 /// can compute the negated form more cheaply than the expression itself.
426 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
427                                const TargetLowering &TLI,
428                                const TargetOptions *Options,
429                                unsigned Depth = 0) {
430   // fneg is removable even if it has multiple uses.
431   if (Op.getOpcode() == ISD::FNEG) return 2;
432
433   // Don't allow anything with multiple uses.
434   if (!Op.hasOneUse()) return 0;
435
436   // Don't recurse exponentially.
437   if (Depth > 6) return 0;
438
439   switch (Op.getOpcode()) {
440   default: return false;
441   case ISD::ConstantFP:
442     // Don't invert constant FP values after legalize.  The negated constant
443     // isn't necessarily legal.
444     return LegalOperations ? 0 : 1;
445   case ISD::FADD:
446     // FIXME: determine better conditions for this xform.
447     if (!Options->UnsafeFPMath) return 0;
448
449     // After operation legalization, it might not be legal to create new FSUBs.
450     if (LegalOperations &&
451         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
452       return 0;
453
454     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
455     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
456                                     Options, Depth + 1))
457       return V;
458     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
459     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
460                               Depth + 1);
461   case ISD::FSUB:
462     // We can't turn -(A-B) into B-A when we honor signed zeros.
463     if (!Options->UnsafeFPMath) return 0;
464
465     // fold (fneg (fsub A, B)) -> (fsub B, A)
466     return 1;
467
468   case ISD::FMUL:
469   case ISD::FDIV:
470     if (Options->HonorSignDependentRoundingFPMath()) return 0;
471
472     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
473     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
474                                     Options, Depth + 1))
475       return V;
476
477     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
478                               Depth + 1);
479
480   case ISD::FP_EXTEND:
481   case ISD::FP_ROUND:
482   case ISD::FSIN:
483     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
484                               Depth + 1);
485   }
486 }
487
488 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
489 /// returns the newly negated expression.
490 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
491                                     bool LegalOperations, unsigned Depth = 0) {
492   // fneg is removable even if it has multiple uses.
493   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
494
495   // Don't allow anything with multiple uses.
496   assert(Op.hasOneUse() && "Unknown reuse!");
497
498   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
499   switch (Op.getOpcode()) {
500   default: llvm_unreachable("Unknown code");
501   case ISD::ConstantFP: {
502     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
503     V.changeSign();
504     return DAG.getConstantFP(V, Op.getValueType());
505   }
506   case ISD::FADD:
507     // FIXME: determine better conditions for this xform.
508     assert(DAG.getTarget().Options.UnsafeFPMath);
509
510     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
511     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
512                            DAG.getTargetLoweringInfo(),
513                            &DAG.getTarget().Options, Depth+1))
514       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
515                          GetNegatedExpression(Op.getOperand(0), DAG,
516                                               LegalOperations, Depth+1),
517                          Op.getOperand(1));
518     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
519     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
520                        GetNegatedExpression(Op.getOperand(1), DAG,
521                                             LegalOperations, Depth+1),
522                        Op.getOperand(0));
523   case ISD::FSUB:
524     // We can't turn -(A-B) into B-A when we honor signed zeros.
525     assert(DAG.getTarget().Options.UnsafeFPMath);
526
527     // fold (fneg (fsub 0, B)) -> B
528     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
529       if (N0CFP->getValueAPF().isZero())
530         return Op.getOperand(1);
531
532     // fold (fneg (fsub A, B)) -> (fsub B, A)
533     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
534                        Op.getOperand(1), Op.getOperand(0));
535
536   case ISD::FMUL:
537   case ISD::FDIV:
538     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
539
540     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
541     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
542                            DAG.getTargetLoweringInfo(),
543                            &DAG.getTarget().Options, Depth+1))
544       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
545                          GetNegatedExpression(Op.getOperand(0), DAG,
546                                               LegalOperations, Depth+1),
547                          Op.getOperand(1));
548
549     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
550     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
551                        Op.getOperand(0),
552                        GetNegatedExpression(Op.getOperand(1), DAG,
553                                             LegalOperations, Depth+1));
554
555   case ISD::FP_EXTEND:
556   case ISD::FSIN:
557     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
558                        GetNegatedExpression(Op.getOperand(0), DAG,
559                                             LegalOperations, Depth+1));
560   case ISD::FP_ROUND:
561       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
562                          GetNegatedExpression(Op.getOperand(0), DAG,
563                                               LegalOperations, Depth+1),
564                          Op.getOperand(1));
565   }
566 }
567
568
569 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
570 // that selects between the values 1 and 0, making it equivalent to a setcc.
571 // Also, set the incoming LHS, RHS, and CC references to the appropriate
572 // nodes based on the type of node we are checking.  This simplifies life a
573 // bit for the callers.
574 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
575                               SDValue &CC) {
576   if (N.getOpcode() == ISD::SETCC) {
577     LHS = N.getOperand(0);
578     RHS = N.getOperand(1);
579     CC  = N.getOperand(2);
580     return true;
581   }
582   if (N.getOpcode() == ISD::SELECT_CC &&
583       N.getOperand(2).getOpcode() == ISD::Constant &&
584       N.getOperand(3).getOpcode() == ISD::Constant &&
585       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
586       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
587     LHS = N.getOperand(0);
588     RHS = N.getOperand(1);
589     CC  = N.getOperand(4);
590     return true;
591   }
592   return false;
593 }
594
595 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
596 // one use.  If this is true, it allows the users to invert the operation for
597 // free when it is profitable to do so.
598 static bool isOneUseSetCC(SDValue N) {
599   SDValue N0, N1, N2;
600   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
601     return true;
602   return false;
603 }
604
605 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
606                                     SDValue N0, SDValue N1) {
607   EVT VT = N0.getValueType();
608   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
609     if (isa<ConstantSDNode>(N1)) {
610       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
611       SDValue OpNode =
612         DAG.FoldConstantArithmetic(Opc, VT,
613                                    cast<ConstantSDNode>(N0.getOperand(1)),
614                                    cast<ConstantSDNode>(N1));
615       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
616     }
617     if (N0.hasOneUse()) {
618       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
619       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
620                                    N0.getOperand(0), N1);
621       AddToWorkList(OpNode.getNode());
622       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
623     }
624   }
625
626   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
627     if (isa<ConstantSDNode>(N0)) {
628       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
629       SDValue OpNode =
630         DAG.FoldConstantArithmetic(Opc, VT,
631                                    cast<ConstantSDNode>(N1.getOperand(1)),
632                                    cast<ConstantSDNode>(N0));
633       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
634     }
635     if (N1.hasOneUse()) {
636       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
637       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
638                                    N1.getOperand(0), N0);
639       AddToWorkList(OpNode.getNode());
640       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
641     }
642   }
643
644   return SDValue();
645 }
646
647 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
648                                bool AddTo) {
649   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
650   ++NodesCombined;
651   DEBUG(dbgs() << "\nReplacing.1 ";
652         N->dump(&DAG);
653         dbgs() << "\nWith: ";
654         To[0].getNode()->dump(&DAG);
655         dbgs() << " and " << NumTo-1 << " other values\n";
656         for (unsigned i = 0, e = NumTo; i != e; ++i)
657           assert((!To[i].getNode() ||
658                   N->getValueType(i) == To[i].getValueType()) &&
659                  "Cannot combine value to value of different type!"));
660   WorkListRemover DeadNodes(*this);
661   DAG.ReplaceAllUsesWith(N, To);
662   if (AddTo) {
663     // Push the new nodes and any users onto the worklist
664     for (unsigned i = 0, e = NumTo; i != e; ++i) {
665       if (To[i].getNode()) {
666         AddToWorkList(To[i].getNode());
667         AddUsersToWorkList(To[i].getNode());
668       }
669     }
670   }
671
672   // Finally, if the node is now dead, remove it from the graph.  The node
673   // may not be dead if the replacement process recursively simplified to
674   // something else needing this node.
675   if (N->use_empty()) {
676     // Nodes can be reintroduced into the worklist.  Make sure we do not
677     // process a node that has been replaced.
678     removeFromWorkList(N);
679
680     // Finally, since the node is now dead, remove it from the graph.
681     DAG.DeleteNode(N);
682   }
683   return SDValue(N, 0);
684 }
685
686 void DAGCombiner::
687 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
688   // Replace all uses.  If any nodes become isomorphic to other nodes and
689   // are deleted, make sure to remove them from our worklist.
690   WorkListRemover DeadNodes(*this);
691   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
692
693   // Push the new node and any (possibly new) users onto the worklist.
694   AddToWorkList(TLO.New.getNode());
695   AddUsersToWorkList(TLO.New.getNode());
696
697   // Finally, if the node is now dead, remove it from the graph.  The node
698   // may not be dead if the replacement process recursively simplified to
699   // something else needing this node.
700   if (TLO.Old.getNode()->use_empty()) {
701     removeFromWorkList(TLO.Old.getNode());
702
703     // If the operands of this node are only used by the node, they will now
704     // be dead.  Make sure to visit them first to delete dead nodes early.
705     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
706       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
707         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
708
709     DAG.DeleteNode(TLO.Old.getNode());
710   }
711 }
712
713 /// SimplifyDemandedBits - Check the specified integer node value to see if
714 /// it can be simplified or if things it uses can be simplified by bit
715 /// propagation.  If so, return true.
716 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
717   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
718   APInt KnownZero, KnownOne;
719   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
720     return false;
721
722   // Revisit the node.
723   AddToWorkList(Op.getNode());
724
725   // Replace the old value with the new one.
726   ++NodesCombined;
727   DEBUG(dbgs() << "\nReplacing.2 ";
728         TLO.Old.getNode()->dump(&DAG);
729         dbgs() << "\nWith: ";
730         TLO.New.getNode()->dump(&DAG);
731         dbgs() << '\n');
732
733   CommitTargetLoweringOpt(TLO);
734   return true;
735 }
736
737 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
738   SDLoc dl(Load);
739   EVT VT = Load->getValueType(0);
740   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
741
742   DEBUG(dbgs() << "\nReplacing.9 ";
743         Load->dump(&DAG);
744         dbgs() << "\nWith: ";
745         Trunc.getNode()->dump(&DAG);
746         dbgs() << '\n');
747   WorkListRemover DeadNodes(*this);
748   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
749   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
750   removeFromWorkList(Load);
751   DAG.DeleteNode(Load);
752   AddToWorkList(Trunc.getNode());
753 }
754
755 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
756   Replace = false;
757   SDLoc dl(Op);
758   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
759     EVT MemVT = LD->getMemoryVT();
760     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
761       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
762                                                   : ISD::EXTLOAD)
763       : LD->getExtensionType();
764     Replace = true;
765     return DAG.getExtLoad(ExtType, dl, PVT,
766                           LD->getChain(), LD->getBasePtr(),
767                           LD->getPointerInfo(),
768                           MemVT, LD->isVolatile(),
769                           LD->isNonTemporal(), LD->getAlignment());
770   }
771
772   unsigned Opc = Op.getOpcode();
773   switch (Opc) {
774   default: break;
775   case ISD::AssertSext:
776     return DAG.getNode(ISD::AssertSext, dl, PVT,
777                        SExtPromoteOperand(Op.getOperand(0), PVT),
778                        Op.getOperand(1));
779   case ISD::AssertZext:
780     return DAG.getNode(ISD::AssertZext, dl, PVT,
781                        ZExtPromoteOperand(Op.getOperand(0), PVT),
782                        Op.getOperand(1));
783   case ISD::Constant: {
784     unsigned ExtOpc =
785       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
786     return DAG.getNode(ExtOpc, dl, PVT, Op);
787   }
788   }
789
790   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
791     return SDValue();
792   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
793 }
794
795 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
796   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
797     return SDValue();
798   EVT OldVT = Op.getValueType();
799   SDLoc dl(Op);
800   bool Replace = false;
801   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
802   if (NewOp.getNode() == 0)
803     return SDValue();
804   AddToWorkList(NewOp.getNode());
805
806   if (Replace)
807     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
808   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
809                      DAG.getValueType(OldVT));
810 }
811
812 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
813   EVT OldVT = Op.getValueType();
814   SDLoc dl(Op);
815   bool Replace = false;
816   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
817   if (NewOp.getNode() == 0)
818     return SDValue();
819   AddToWorkList(NewOp.getNode());
820
821   if (Replace)
822     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
823   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
824 }
825
826 /// PromoteIntBinOp - Promote the specified integer binary operation if the
827 /// target indicates it is beneficial. e.g. On x86, it's usually better to
828 /// promote i16 operations to i32 since i16 instructions are longer.
829 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
830   if (!LegalOperations)
831     return SDValue();
832
833   EVT VT = Op.getValueType();
834   if (VT.isVector() || !VT.isInteger())
835     return SDValue();
836
837   // If operation type is 'undesirable', e.g. i16 on x86, consider
838   // promoting it.
839   unsigned Opc = Op.getOpcode();
840   if (TLI.isTypeDesirableForOp(Opc, VT))
841     return SDValue();
842
843   EVT PVT = VT;
844   // Consult target whether it is a good idea to promote this operation and
845   // what's the right type to promote it to.
846   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
847     assert(PVT != VT && "Don't know what type to promote to!");
848
849     bool Replace0 = false;
850     SDValue N0 = Op.getOperand(0);
851     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
852     if (NN0.getNode() == 0)
853       return SDValue();
854
855     bool Replace1 = false;
856     SDValue N1 = Op.getOperand(1);
857     SDValue NN1;
858     if (N0 == N1)
859       NN1 = NN0;
860     else {
861       NN1 = PromoteOperand(N1, PVT, Replace1);
862       if (NN1.getNode() == 0)
863         return SDValue();
864     }
865
866     AddToWorkList(NN0.getNode());
867     if (NN1.getNode())
868       AddToWorkList(NN1.getNode());
869
870     if (Replace0)
871       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
872     if (Replace1)
873       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
874
875     DEBUG(dbgs() << "\nPromoting ";
876           Op.getNode()->dump(&DAG));
877     SDLoc dl(Op);
878     return DAG.getNode(ISD::TRUNCATE, dl, VT,
879                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
880   }
881   return SDValue();
882 }
883
884 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
885 /// target indicates it is beneficial. e.g. On x86, it's usually better to
886 /// promote i16 operations to i32 since i16 instructions are longer.
887 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
888   if (!LegalOperations)
889     return SDValue();
890
891   EVT VT = Op.getValueType();
892   if (VT.isVector() || !VT.isInteger())
893     return SDValue();
894
895   // If operation type is 'undesirable', e.g. i16 on x86, consider
896   // promoting it.
897   unsigned Opc = Op.getOpcode();
898   if (TLI.isTypeDesirableForOp(Opc, VT))
899     return SDValue();
900
901   EVT PVT = VT;
902   // Consult target whether it is a good idea to promote this operation and
903   // what's the right type to promote it to.
904   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
905     assert(PVT != VT && "Don't know what type to promote to!");
906
907     bool Replace = false;
908     SDValue N0 = Op.getOperand(0);
909     if (Opc == ISD::SRA)
910       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
911     else if (Opc == ISD::SRL)
912       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
913     else
914       N0 = PromoteOperand(N0, PVT, Replace);
915     if (N0.getNode() == 0)
916       return SDValue();
917
918     AddToWorkList(N0.getNode());
919     if (Replace)
920       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
921
922     DEBUG(dbgs() << "\nPromoting ";
923           Op.getNode()->dump(&DAG));
924     SDLoc dl(Op);
925     return DAG.getNode(ISD::TRUNCATE, dl, VT,
926                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
927   }
928   return SDValue();
929 }
930
931 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
932   if (!LegalOperations)
933     return SDValue();
934
935   EVT VT = Op.getValueType();
936   if (VT.isVector() || !VT.isInteger())
937     return SDValue();
938
939   // If operation type is 'undesirable', e.g. i16 on x86, consider
940   // promoting it.
941   unsigned Opc = Op.getOpcode();
942   if (TLI.isTypeDesirableForOp(Opc, VT))
943     return SDValue();
944
945   EVT PVT = VT;
946   // Consult target whether it is a good idea to promote this operation and
947   // what's the right type to promote it to.
948   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
949     assert(PVT != VT && "Don't know what type to promote to!");
950     // fold (aext (aext x)) -> (aext x)
951     // fold (aext (zext x)) -> (zext x)
952     // fold (aext (sext x)) -> (sext x)
953     DEBUG(dbgs() << "\nPromoting ";
954           Op.getNode()->dump(&DAG));
955     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
956   }
957   return SDValue();
958 }
959
960 bool DAGCombiner::PromoteLoad(SDValue Op) {
961   if (!LegalOperations)
962     return false;
963
964   EVT VT = Op.getValueType();
965   if (VT.isVector() || !VT.isInteger())
966     return false;
967
968   // If operation type is 'undesirable', e.g. i16 on x86, consider
969   // promoting it.
970   unsigned Opc = Op.getOpcode();
971   if (TLI.isTypeDesirableForOp(Opc, VT))
972     return false;
973
974   EVT PVT = VT;
975   // Consult target whether it is a good idea to promote this operation and
976   // what's the right type to promote it to.
977   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
978     assert(PVT != VT && "Don't know what type to promote to!");
979
980     SDLoc dl(Op);
981     SDNode *N = Op.getNode();
982     LoadSDNode *LD = cast<LoadSDNode>(N);
983     EVT MemVT = LD->getMemoryVT();
984     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
985       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
986                                                   : ISD::EXTLOAD)
987       : LD->getExtensionType();
988     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
989                                    LD->getChain(), LD->getBasePtr(),
990                                    LD->getPointerInfo(),
991                                    MemVT, LD->isVolatile(),
992                                    LD->isNonTemporal(), LD->getAlignment());
993     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
994
995     DEBUG(dbgs() << "\nPromoting ";
996           N->dump(&DAG);
997           dbgs() << "\nTo: ";
998           Result.getNode()->dump(&DAG);
999           dbgs() << '\n');
1000     WorkListRemover DeadNodes(*this);
1001     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1002     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1003     removeFromWorkList(N);
1004     DAG.DeleteNode(N);
1005     AddToWorkList(Result.getNode());
1006     return true;
1007   }
1008   return false;
1009 }
1010
1011
1012 //===----------------------------------------------------------------------===//
1013 //  Main DAG Combiner implementation
1014 //===----------------------------------------------------------------------===//
1015
1016 void DAGCombiner::Run(CombineLevel AtLevel) {
1017   // set the instance variables, so that the various visit routines may use it.
1018   Level = AtLevel;
1019   LegalOperations = Level >= AfterLegalizeVectorOps;
1020   LegalTypes = Level >= AfterLegalizeTypes;
1021
1022   // Add all the dag nodes to the worklist.
1023   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1024        E = DAG.allnodes_end(); I != E; ++I)
1025     AddToWorkList(I);
1026
1027   // Create a dummy node (which is not added to allnodes), that adds a reference
1028   // to the root node, preventing it from being deleted, and tracking any
1029   // changes of the root.
1030   HandleSDNode Dummy(DAG.getRoot());
1031
1032   // The root of the dag may dangle to deleted nodes until the dag combiner is
1033   // done.  Set it to null to avoid confusion.
1034   DAG.setRoot(SDValue());
1035
1036   // while the worklist isn't empty, find a node and
1037   // try and combine it.
1038   while (!WorkListContents.empty()) {
1039     SDNode *N;
1040     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1041     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1042     // worklist *should* contain, and check the node we want to visit is should
1043     // actually be visited.
1044     do {
1045       N = WorkListOrder.pop_back_val();
1046     } while (!WorkListContents.erase(N));
1047
1048     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1049     // N is deleted from the DAG, since they too may now be dead or may have a
1050     // reduced number of uses, allowing other xforms.
1051     if (N->use_empty() && N != &Dummy) {
1052       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1053         AddToWorkList(N->getOperand(i).getNode());
1054
1055       DAG.DeleteNode(N);
1056       continue;
1057     }
1058
1059     SDValue RV = combine(N);
1060
1061     if (RV.getNode() == 0)
1062       continue;
1063
1064     ++NodesCombined;
1065
1066     // If we get back the same node we passed in, rather than a new node or
1067     // zero, we know that the node must have defined multiple values and
1068     // CombineTo was used.  Since CombineTo takes care of the worklist
1069     // mechanics for us, we have no work to do in this case.
1070     if (RV.getNode() == N)
1071       continue;
1072
1073     assert(N->getOpcode() != ISD::DELETED_NODE &&
1074            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1075            "Node was deleted but visit returned new node!");
1076
1077     DEBUG(dbgs() << "\nReplacing.3 ";
1078           N->dump(&DAG);
1079           dbgs() << "\nWith: ";
1080           RV.getNode()->dump(&DAG);
1081           dbgs() << '\n');
1082
1083     // Transfer debug value.
1084     DAG.TransferDbgValues(SDValue(N, 0), RV);
1085     WorkListRemover DeadNodes(*this);
1086     if (N->getNumValues() == RV.getNode()->getNumValues())
1087       DAG.ReplaceAllUsesWith(N, RV.getNode());
1088     else {
1089       assert(N->getValueType(0) == RV.getValueType() &&
1090              N->getNumValues() == 1 && "Type mismatch");
1091       SDValue OpV = RV;
1092       DAG.ReplaceAllUsesWith(N, &OpV);
1093     }
1094
1095     // Push the new node and any users onto the worklist
1096     AddToWorkList(RV.getNode());
1097     AddUsersToWorkList(RV.getNode());
1098
1099     // Add any uses of the old node to the worklist in case this node is the
1100     // last one that uses them.  They may become dead after this node is
1101     // deleted.
1102     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1103       AddToWorkList(N->getOperand(i).getNode());
1104
1105     // Finally, if the node is now dead, remove it from the graph.  The node
1106     // may not be dead if the replacement process recursively simplified to
1107     // something else needing this node.
1108     if (N->use_empty()) {
1109       // Nodes can be reintroduced into the worklist.  Make sure we do not
1110       // process a node that has been replaced.
1111       removeFromWorkList(N);
1112
1113       // Finally, since the node is now dead, remove it from the graph.
1114       DAG.DeleteNode(N);
1115     }
1116   }
1117
1118   // If the root changed (e.g. it was a dead load, update the root).
1119   DAG.setRoot(Dummy.getValue());
1120   DAG.RemoveDeadNodes();
1121 }
1122
1123 SDValue DAGCombiner::visit(SDNode *N) {
1124   switch (N->getOpcode()) {
1125   default: break;
1126   case ISD::TokenFactor:        return visitTokenFactor(N);
1127   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1128   case ISD::ADD:                return visitADD(N);
1129   case ISD::SUB:                return visitSUB(N);
1130   case ISD::ADDC:               return visitADDC(N);
1131   case ISD::SUBC:               return visitSUBC(N);
1132   case ISD::ADDE:               return visitADDE(N);
1133   case ISD::SUBE:               return visitSUBE(N);
1134   case ISD::MUL:                return visitMUL(N);
1135   case ISD::SDIV:               return visitSDIV(N);
1136   case ISD::UDIV:               return visitUDIV(N);
1137   case ISD::SREM:               return visitSREM(N);
1138   case ISD::UREM:               return visitUREM(N);
1139   case ISD::MULHU:              return visitMULHU(N);
1140   case ISD::MULHS:              return visitMULHS(N);
1141   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1142   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1143   case ISD::SMULO:              return visitSMULO(N);
1144   case ISD::UMULO:              return visitUMULO(N);
1145   case ISD::SDIVREM:            return visitSDIVREM(N);
1146   case ISD::UDIVREM:            return visitUDIVREM(N);
1147   case ISD::AND:                return visitAND(N);
1148   case ISD::OR:                 return visitOR(N);
1149   case ISD::XOR:                return visitXOR(N);
1150   case ISD::SHL:                return visitSHL(N);
1151   case ISD::SRA:                return visitSRA(N);
1152   case ISD::SRL:                return visitSRL(N);
1153   case ISD::CTLZ:               return visitCTLZ(N);
1154   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1155   case ISD::CTTZ:               return visitCTTZ(N);
1156   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1157   case ISD::CTPOP:              return visitCTPOP(N);
1158   case ISD::SELECT:             return visitSELECT(N);
1159   case ISD::VSELECT:            return visitVSELECT(N);
1160   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1161   case ISD::SETCC:              return visitSETCC(N);
1162   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1163   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1164   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1165   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1166   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1167   case ISD::BITCAST:            return visitBITCAST(N);
1168   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1169   case ISD::FADD:               return visitFADD(N);
1170   case ISD::FSUB:               return visitFSUB(N);
1171   case ISD::FMUL:               return visitFMUL(N);
1172   case ISD::FMA:                return visitFMA(N);
1173   case ISD::FDIV:               return visitFDIV(N);
1174   case ISD::FREM:               return visitFREM(N);
1175   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1176   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1177   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1178   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1179   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1180   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1181   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1182   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1183   case ISD::FNEG:               return visitFNEG(N);
1184   case ISD::FABS:               return visitFABS(N);
1185   case ISD::FFLOOR:             return visitFFLOOR(N);
1186   case ISD::FCEIL:              return visitFCEIL(N);
1187   case ISD::FTRUNC:             return visitFTRUNC(N);
1188   case ISD::BRCOND:             return visitBRCOND(N);
1189   case ISD::BR_CC:              return visitBR_CC(N);
1190   case ISD::LOAD:               return visitLOAD(N);
1191   case ISD::STORE:              return visitSTORE(N);
1192   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1193   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1194   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1195   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1196   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1197   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1198   }
1199   return SDValue();
1200 }
1201
1202 SDValue DAGCombiner::combine(SDNode *N) {
1203   SDValue RV = visit(N);
1204
1205   // If nothing happened, try a target-specific DAG combine.
1206   if (RV.getNode() == 0) {
1207     assert(N->getOpcode() != ISD::DELETED_NODE &&
1208            "Node was deleted but visit returned NULL!");
1209
1210     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1211         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1212
1213       // Expose the DAG combiner to the target combiner impls.
1214       TargetLowering::DAGCombinerInfo
1215         DagCombineInfo(DAG, Level, false, this);
1216
1217       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1218     }
1219   }
1220
1221   // If nothing happened still, try promoting the operation.
1222   if (RV.getNode() == 0) {
1223     switch (N->getOpcode()) {
1224     default: break;
1225     case ISD::ADD:
1226     case ISD::SUB:
1227     case ISD::MUL:
1228     case ISD::AND:
1229     case ISD::OR:
1230     case ISD::XOR:
1231       RV = PromoteIntBinOp(SDValue(N, 0));
1232       break;
1233     case ISD::SHL:
1234     case ISD::SRA:
1235     case ISD::SRL:
1236       RV = PromoteIntShiftOp(SDValue(N, 0));
1237       break;
1238     case ISD::SIGN_EXTEND:
1239     case ISD::ZERO_EXTEND:
1240     case ISD::ANY_EXTEND:
1241       RV = PromoteExtend(SDValue(N, 0));
1242       break;
1243     case ISD::LOAD:
1244       if (PromoteLoad(SDValue(N, 0)))
1245         RV = SDValue(N, 0);
1246       break;
1247     }
1248   }
1249
1250   // If N is a commutative binary node, try commuting it to enable more
1251   // sdisel CSE.
1252   if (RV.getNode() == 0 &&
1253       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1254       N->getNumValues() == 1) {
1255     SDValue N0 = N->getOperand(0);
1256     SDValue N1 = N->getOperand(1);
1257
1258     // Constant operands are canonicalized to RHS.
1259     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1260       SDValue Ops[] = { N1, N0 };
1261       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1262                                             Ops, 2);
1263       if (CSENode)
1264         return SDValue(CSENode, 0);
1265     }
1266   }
1267
1268   return RV;
1269 }
1270
1271 /// getInputChainForNode - Given a node, return its input chain if it has one,
1272 /// otherwise return a null sd operand.
1273 static SDValue getInputChainForNode(SDNode *N) {
1274   if (unsigned NumOps = N->getNumOperands()) {
1275     if (N->getOperand(0).getValueType() == MVT::Other)
1276       return N->getOperand(0);
1277     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1278       return N->getOperand(NumOps-1);
1279     for (unsigned i = 1; i < NumOps-1; ++i)
1280       if (N->getOperand(i).getValueType() == MVT::Other)
1281         return N->getOperand(i);
1282   }
1283   return SDValue();
1284 }
1285
1286 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1287   // If N has two operands, where one has an input chain equal to the other,
1288   // the 'other' chain is redundant.
1289   if (N->getNumOperands() == 2) {
1290     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1291       return N->getOperand(0);
1292     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1293       return N->getOperand(1);
1294   }
1295
1296   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1297   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1298   SmallPtrSet<SDNode*, 16> SeenOps;
1299   bool Changed = false;             // If we should replace this token factor.
1300
1301   // Start out with this token factor.
1302   TFs.push_back(N);
1303
1304   // Iterate through token factors.  The TFs grows when new token factors are
1305   // encountered.
1306   for (unsigned i = 0; i < TFs.size(); ++i) {
1307     SDNode *TF = TFs[i];
1308
1309     // Check each of the operands.
1310     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1311       SDValue Op = TF->getOperand(i);
1312
1313       switch (Op.getOpcode()) {
1314       case ISD::EntryToken:
1315         // Entry tokens don't need to be added to the list. They are
1316         // rededundant.
1317         Changed = true;
1318         break;
1319
1320       case ISD::TokenFactor:
1321         if (Op.hasOneUse() &&
1322             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1323           // Queue up for processing.
1324           TFs.push_back(Op.getNode());
1325           // Clean up in case the token factor is removed.
1326           AddToWorkList(Op.getNode());
1327           Changed = true;
1328           break;
1329         }
1330         // Fall thru
1331
1332       default:
1333         // Only add if it isn't already in the list.
1334         if (SeenOps.insert(Op.getNode()))
1335           Ops.push_back(Op);
1336         else
1337           Changed = true;
1338         break;
1339       }
1340     }
1341   }
1342
1343   SDValue Result;
1344
1345   // If we've change things around then replace token factor.
1346   if (Changed) {
1347     if (Ops.empty()) {
1348       // The entry token is the only possible outcome.
1349       Result = DAG.getEntryNode();
1350     } else {
1351       // New and improved token factor.
1352       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1353                            MVT::Other, &Ops[0], Ops.size());
1354     }
1355
1356     // Don't add users to work list.
1357     return CombineTo(N, Result, false);
1358   }
1359
1360   return Result;
1361 }
1362
1363 /// MERGE_VALUES can always be eliminated.
1364 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1365   WorkListRemover DeadNodes(*this);
1366   // Replacing results may cause a different MERGE_VALUES to suddenly
1367   // be CSE'd with N, and carry its uses with it. Iterate until no
1368   // uses remain, to ensure that the node can be safely deleted.
1369   // First add the users of this node to the work list so that they
1370   // can be tried again once they have new operands.
1371   AddUsersToWorkList(N);
1372   do {
1373     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1374       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1375   } while (!N->use_empty());
1376   removeFromWorkList(N);
1377   DAG.DeleteNode(N);
1378   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1379 }
1380
1381 static
1382 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1383                               SelectionDAG &DAG) {
1384   EVT VT = N0.getValueType();
1385   SDValue N00 = N0.getOperand(0);
1386   SDValue N01 = N0.getOperand(1);
1387   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1388
1389   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1390       isa<ConstantSDNode>(N00.getOperand(1))) {
1391     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1392     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1393                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1394                                  N00.getOperand(0), N01),
1395                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1396                                  N00.getOperand(1), N01));
1397     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1398   }
1399
1400   return SDValue();
1401 }
1402
1403 SDValue DAGCombiner::visitADD(SDNode *N) {
1404   SDValue N0 = N->getOperand(0);
1405   SDValue N1 = N->getOperand(1);
1406   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1407   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1408   EVT VT = N0.getValueType();
1409
1410   // fold vector ops
1411   if (VT.isVector()) {
1412     SDValue FoldedVOp = SimplifyVBinOp(N);
1413     if (FoldedVOp.getNode()) return FoldedVOp;
1414
1415     // fold (add x, 0) -> x, vector edition
1416     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1417       return N0;
1418     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1419       return N1;
1420   }
1421
1422   // fold (add x, undef) -> undef
1423   if (N0.getOpcode() == ISD::UNDEF)
1424     return N0;
1425   if (N1.getOpcode() == ISD::UNDEF)
1426     return N1;
1427   // fold (add c1, c2) -> c1+c2
1428   if (N0C && N1C)
1429     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1430   // canonicalize constant to RHS
1431   if (N0C && !N1C)
1432     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1433   // fold (add x, 0) -> x
1434   if (N1C && N1C->isNullValue())
1435     return N0;
1436   // fold (add Sym, c) -> Sym+c
1437   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1438     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1439         GA->getOpcode() == ISD::GlobalAddress)
1440       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1441                                   GA->getOffset() +
1442                                     (uint64_t)N1C->getSExtValue());
1443   // fold ((c1-A)+c2) -> (c1+c2)-A
1444   if (N1C && N0.getOpcode() == ISD::SUB)
1445     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1446       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1447                          DAG.getConstant(N1C->getAPIntValue()+
1448                                          N0C->getAPIntValue(), VT),
1449                          N0.getOperand(1));
1450   // reassociate add
1451   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1452   if (RADD.getNode() != 0)
1453     return RADD;
1454   // fold ((0-A) + B) -> B-A
1455   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1456       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1457     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1458   // fold (A + (0-B)) -> A-B
1459   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1460       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1461     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1462   // fold (A+(B-A)) -> B
1463   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1464     return N1.getOperand(0);
1465   // fold ((B-A)+A) -> B
1466   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1467     return N0.getOperand(0);
1468   // fold (A+(B-(A+C))) to (B-C)
1469   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1470       N0 == N1.getOperand(1).getOperand(0))
1471     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1472                        N1.getOperand(1).getOperand(1));
1473   // fold (A+(B-(C+A))) to (B-C)
1474   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1475       N0 == N1.getOperand(1).getOperand(1))
1476     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1477                        N1.getOperand(1).getOperand(0));
1478   // fold (A+((B-A)+or-C)) to (B+or-C)
1479   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1480       N1.getOperand(0).getOpcode() == ISD::SUB &&
1481       N0 == N1.getOperand(0).getOperand(1))
1482     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1483                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1484
1485   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1486   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1487     SDValue N00 = N0.getOperand(0);
1488     SDValue N01 = N0.getOperand(1);
1489     SDValue N10 = N1.getOperand(0);
1490     SDValue N11 = N1.getOperand(1);
1491
1492     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1493       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1494                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1495                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1496   }
1497
1498   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1499     return SDValue(N, 0);
1500
1501   // fold (a+b) -> (a|b) iff a and b share no bits.
1502   if (VT.isInteger() && !VT.isVector()) {
1503     APInt LHSZero, LHSOne;
1504     APInt RHSZero, RHSOne;
1505     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1506
1507     if (LHSZero.getBoolValue()) {
1508       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1509
1510       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1511       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1512       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1513         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1514     }
1515   }
1516
1517   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1518   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1519     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1520     if (Result.getNode()) return Result;
1521   }
1522   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1523     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1524     if (Result.getNode()) return Result;
1525   }
1526
1527   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1528   if (N1.getOpcode() == ISD::SHL &&
1529       N1.getOperand(0).getOpcode() == ISD::SUB)
1530     if (ConstantSDNode *C =
1531           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1532       if (C->getAPIntValue() == 0)
1533         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1534                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1535                                        N1.getOperand(0).getOperand(1),
1536                                        N1.getOperand(1)));
1537   if (N0.getOpcode() == ISD::SHL &&
1538       N0.getOperand(0).getOpcode() == ISD::SUB)
1539     if (ConstantSDNode *C =
1540           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1541       if (C->getAPIntValue() == 0)
1542         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1543                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1544                                        N0.getOperand(0).getOperand(1),
1545                                        N0.getOperand(1)));
1546
1547   if (N1.getOpcode() == ISD::AND) {
1548     SDValue AndOp0 = N1.getOperand(0);
1549     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1550     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1551     unsigned DestBits = VT.getScalarType().getSizeInBits();
1552
1553     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1554     // and similar xforms where the inner op is either ~0 or 0.
1555     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1556       SDLoc DL(N);
1557       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1558     }
1559   }
1560
1561   // add (sext i1), X -> sub X, (zext i1)
1562   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1563       N0.getOperand(0).getValueType() == MVT::i1 &&
1564       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1565     SDLoc DL(N);
1566     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1567     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1568   }
1569
1570   return SDValue();
1571 }
1572
1573 SDValue DAGCombiner::visitADDC(SDNode *N) {
1574   SDValue N0 = N->getOperand(0);
1575   SDValue N1 = N->getOperand(1);
1576   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1577   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1578   EVT VT = N0.getValueType();
1579
1580   // If the flag result is dead, turn this into an ADD.
1581   if (!N->hasAnyUseOfValue(1))
1582     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1583                      DAG.getNode(ISD::CARRY_FALSE,
1584                                  SDLoc(N), MVT::Glue));
1585
1586   // canonicalize constant to RHS.
1587   if (N0C && !N1C)
1588     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1589
1590   // fold (addc x, 0) -> x + no carry out
1591   if (N1C && N1C->isNullValue())
1592     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1593                                         SDLoc(N), MVT::Glue));
1594
1595   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1596   APInt LHSZero, LHSOne;
1597   APInt RHSZero, RHSOne;
1598   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1599
1600   if (LHSZero.getBoolValue()) {
1601     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1602
1603     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1604     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1605     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1606       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1607                        DAG.getNode(ISD::CARRY_FALSE,
1608                                    SDLoc(N), MVT::Glue));
1609   }
1610
1611   return SDValue();
1612 }
1613
1614 SDValue DAGCombiner::visitADDE(SDNode *N) {
1615   SDValue N0 = N->getOperand(0);
1616   SDValue N1 = N->getOperand(1);
1617   SDValue CarryIn = N->getOperand(2);
1618   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1619   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1620
1621   // canonicalize constant to RHS
1622   if (N0C && !N1C)
1623     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1624                        N1, N0, CarryIn);
1625
1626   // fold (adde x, y, false) -> (addc x, y)
1627   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1628     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1629
1630   return SDValue();
1631 }
1632
1633 // Since it may not be valid to emit a fold to zero for vector initializers
1634 // check if we can before folding.
1635 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1636                              SelectionDAG &DAG,
1637                              bool LegalOperations, bool LegalTypes) {
1638   if (!VT.isVector())
1639     return DAG.getConstant(0, VT);
1640   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1641     // Produce a vector of zeros.
1642     EVT ElemTy = VT.getVectorElementType();
1643     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1644                       TargetLowering::TypePromoteInteger)
1645       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1646     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1647            "Type for zero vector elements is not legal");
1648     SDValue El = DAG.getConstant(0, ElemTy);
1649     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1650     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1651       &Ops[0], Ops.size());
1652   }
1653   return SDValue();
1654 }
1655
1656 SDValue DAGCombiner::visitSUB(SDNode *N) {
1657   SDValue N0 = N->getOperand(0);
1658   SDValue N1 = N->getOperand(1);
1659   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1660   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1661   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1662     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1663   EVT VT = N0.getValueType();
1664
1665   // fold vector ops
1666   if (VT.isVector()) {
1667     SDValue FoldedVOp = SimplifyVBinOp(N);
1668     if (FoldedVOp.getNode()) return FoldedVOp;
1669
1670     // fold (sub x, 0) -> x, vector edition
1671     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1672       return N0;
1673   }
1674
1675   // fold (sub x, x) -> 0
1676   // FIXME: Refactor this and xor and other similar operations together.
1677   if (N0 == N1)
1678     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1679   // fold (sub c1, c2) -> c1-c2
1680   if (N0C && N1C)
1681     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1682   // fold (sub x, c) -> (add x, -c)
1683   if (N1C)
1684     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1685                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1686   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1687   if (N0C && N0C->isAllOnesValue())
1688     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1689   // fold A-(A-B) -> B
1690   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1691     return N1.getOperand(1);
1692   // fold (A+B)-A -> B
1693   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1694     return N0.getOperand(1);
1695   // fold (A+B)-B -> A
1696   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1697     return N0.getOperand(0);
1698   // fold C2-(A+C1) -> (C2-C1)-A
1699   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1700     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1701                                    VT);
1702     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1703                        N1.getOperand(0));
1704   }
1705   // fold ((A+(B+or-C))-B) -> A+or-C
1706   if (N0.getOpcode() == ISD::ADD &&
1707       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1708        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1709       N0.getOperand(1).getOperand(0) == N1)
1710     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1711                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1712   // fold ((A+(C+B))-B) -> A+C
1713   if (N0.getOpcode() == ISD::ADD &&
1714       N0.getOperand(1).getOpcode() == ISD::ADD &&
1715       N0.getOperand(1).getOperand(1) == N1)
1716     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1717                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1718   // fold ((A-(B-C))-C) -> A-B
1719   if (N0.getOpcode() == ISD::SUB &&
1720       N0.getOperand(1).getOpcode() == ISD::SUB &&
1721       N0.getOperand(1).getOperand(1) == N1)
1722     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1723                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1724
1725   // If either operand of a sub is undef, the result is undef
1726   if (N0.getOpcode() == ISD::UNDEF)
1727     return N0;
1728   if (N1.getOpcode() == ISD::UNDEF)
1729     return N1;
1730
1731   // If the relocation model supports it, consider symbol offsets.
1732   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1733     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1734       // fold (sub Sym, c) -> Sym-c
1735       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1736         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1737                                     GA->getOffset() -
1738                                       (uint64_t)N1C->getSExtValue());
1739       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1740       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1741         if (GA->getGlobal() == GB->getGlobal())
1742           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1743                                  VT);
1744     }
1745
1746   return SDValue();
1747 }
1748
1749 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1750   SDValue N0 = N->getOperand(0);
1751   SDValue N1 = N->getOperand(1);
1752   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1753   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1754   EVT VT = N0.getValueType();
1755
1756   // If the flag result is dead, turn this into an SUB.
1757   if (!N->hasAnyUseOfValue(1))
1758     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1759                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1760                                  MVT::Glue));
1761
1762   // fold (subc x, x) -> 0 + no borrow
1763   if (N0 == N1)
1764     return CombineTo(N, DAG.getConstant(0, VT),
1765                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1766                                  MVT::Glue));
1767
1768   // fold (subc x, 0) -> x + no borrow
1769   if (N1C && N1C->isNullValue())
1770     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1771                                         MVT::Glue));
1772
1773   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1774   if (N0C && N0C->isAllOnesValue())
1775     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1776                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1777                                  MVT::Glue));
1778
1779   return SDValue();
1780 }
1781
1782 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1783   SDValue N0 = N->getOperand(0);
1784   SDValue N1 = N->getOperand(1);
1785   SDValue CarryIn = N->getOperand(2);
1786
1787   // fold (sube x, y, false) -> (subc x, y)
1788   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1789     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1790
1791   return SDValue();
1792 }
1793
1794 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1795 /// all the same constant or undefined.
1796 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1797   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1798   if (!C)
1799     return false;
1800
1801   APInt SplatUndef;
1802   unsigned SplatBitSize;
1803   bool HasAnyUndefs;
1804   EVT EltVT = N->getValueType(0).getVectorElementType();
1805   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1806                              HasAnyUndefs) &&
1807           EltVT.getSizeInBits() >= SplatBitSize);
1808 }
1809
1810 SDValue DAGCombiner::visitMUL(SDNode *N) {
1811   SDValue N0 = N->getOperand(0);
1812   SDValue N1 = N->getOperand(1);
1813   EVT VT = N0.getValueType();
1814
1815   // fold (mul x, undef) -> 0
1816   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1817     return DAG.getConstant(0, VT);
1818
1819   bool N0IsConst = false;
1820   bool N1IsConst = false;
1821   APInt ConstValue0, ConstValue1;
1822   // fold vector ops
1823   if (VT.isVector()) {
1824     SDValue FoldedVOp = SimplifyVBinOp(N);
1825     if (FoldedVOp.getNode()) return FoldedVOp;
1826
1827     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1828     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1829   } else {
1830     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1831     ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1832     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1833     ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1834   }
1835
1836   // fold (mul c1, c2) -> c1*c2
1837   if (N0IsConst && N1IsConst)
1838     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1839
1840   // canonicalize constant to RHS
1841   if (N0IsConst && !N1IsConst)
1842     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1843   // fold (mul x, 0) -> 0
1844   if (N1IsConst && ConstValue1 == 0)
1845     return N1;
1846   // We require a splat of the entire scalar bit width for non-contiguous
1847   // bit patterns.
1848   bool IsFullSplat =
1849     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1850   // fold (mul x, 1) -> x
1851   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1852     return N0;
1853   // fold (mul x, -1) -> 0-x
1854   if (N1IsConst && ConstValue1.isAllOnesValue())
1855     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1856                        DAG.getConstant(0, VT), N0);
1857   // fold (mul x, (1 << c)) -> x << c
1858   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1859     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1860                        DAG.getConstant(ConstValue1.logBase2(),
1861                                        getShiftAmountTy(N0.getValueType())));
1862   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1863   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1864     unsigned Log2Val = (-ConstValue1).logBase2();
1865     // FIXME: If the input is something that is easily negated (e.g. a
1866     // single-use add), we should put the negate there.
1867     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1868                        DAG.getConstant(0, VT),
1869                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1870                             DAG.getConstant(Log2Val,
1871                                       getShiftAmountTy(N0.getValueType()))));
1872   }
1873
1874   APInt Val;
1875   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1876   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1877       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1878                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1879     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1880                              N1, N0.getOperand(1));
1881     AddToWorkList(C3.getNode());
1882     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1883                        N0.getOperand(0), C3);
1884   }
1885
1886   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1887   // use.
1888   {
1889     SDValue Sh(0,0), Y(0,0);
1890     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1891     if (N0.getOpcode() == ISD::SHL &&
1892         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1893                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1894         N0.getNode()->hasOneUse()) {
1895       Sh = N0; Y = N1;
1896     } else if (N1.getOpcode() == ISD::SHL &&
1897                isa<ConstantSDNode>(N1.getOperand(1)) &&
1898                N1.getNode()->hasOneUse()) {
1899       Sh = N1; Y = N0;
1900     }
1901
1902     if (Sh.getNode()) {
1903       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1904                                 Sh.getOperand(0), Y);
1905       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1906                          Mul, Sh.getOperand(1));
1907     }
1908   }
1909
1910   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1911   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1912       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1913                      isa<ConstantSDNode>(N0.getOperand(1))))
1914     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1915                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1916                                    N0.getOperand(0), N1),
1917                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1918                                    N0.getOperand(1), N1));
1919
1920   // reassociate mul
1921   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1922   if (RMUL.getNode() != 0)
1923     return RMUL;
1924
1925   return SDValue();
1926 }
1927
1928 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1932   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1933   EVT VT = N->getValueType(0);
1934
1935   // fold vector ops
1936   if (VT.isVector()) {
1937     SDValue FoldedVOp = SimplifyVBinOp(N);
1938     if (FoldedVOp.getNode()) return FoldedVOp;
1939   }
1940
1941   // fold (sdiv c1, c2) -> c1/c2
1942   if (N0C && N1C && !N1C->isNullValue())
1943     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1944   // fold (sdiv X, 1) -> X
1945   if (N1C && N1C->getAPIntValue() == 1LL)
1946     return N0;
1947   // fold (sdiv X, -1) -> 0-X
1948   if (N1C && N1C->isAllOnesValue())
1949     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1950                        DAG.getConstant(0, VT), N0);
1951   // If we know the sign bits of both operands are zero, strength reduce to a
1952   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1953   if (!VT.isVector()) {
1954     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1955       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1956                          N0, N1);
1957   }
1958   // fold (sdiv X, pow2) -> simple ops after legalize
1959   if (N1C && !N1C->isNullValue() &&
1960       (N1C->getAPIntValue().isPowerOf2() ||
1961        (-N1C->getAPIntValue()).isPowerOf2())) {
1962     // If dividing by powers of two is cheap, then don't perform the following
1963     // fold.
1964     if (TLI.isPow2DivCheap())
1965       return SDValue();
1966
1967     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1968
1969     // Splat the sign bit into the register
1970     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1971                               DAG.getConstant(VT.getSizeInBits()-1,
1972                                        getShiftAmountTy(N0.getValueType())));
1973     AddToWorkList(SGN.getNode());
1974
1975     // Add (N0 < 0) ? abs2 - 1 : 0;
1976     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1977                               DAG.getConstant(VT.getSizeInBits() - lg2,
1978                                        getShiftAmountTy(SGN.getValueType())));
1979     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1980     AddToWorkList(SRL.getNode());
1981     AddToWorkList(ADD.getNode());    // Divide by pow2
1982     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1983                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1984
1985     // If we're dividing by a positive value, we're done.  Otherwise, we must
1986     // negate the result.
1987     if (N1C->getAPIntValue().isNonNegative())
1988       return SRA;
1989
1990     AddToWorkList(SRA.getNode());
1991     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1992                        DAG.getConstant(0, VT), SRA);
1993   }
1994
1995   // if integer divide is expensive and we satisfy the requirements, emit an
1996   // alternate sequence.
1997   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1998     SDValue Op = BuildSDIV(N);
1999     if (Op.getNode()) return Op;
2000   }
2001
2002   // undef / X -> 0
2003   if (N0.getOpcode() == ISD::UNDEF)
2004     return DAG.getConstant(0, VT);
2005   // X / undef -> undef
2006   if (N1.getOpcode() == ISD::UNDEF)
2007     return N1;
2008
2009   return SDValue();
2010 }
2011
2012 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2013   SDValue N0 = N->getOperand(0);
2014   SDValue N1 = N->getOperand(1);
2015   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2016   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2017   EVT VT = N->getValueType(0);
2018
2019   // fold vector ops
2020   if (VT.isVector()) {
2021     SDValue FoldedVOp = SimplifyVBinOp(N);
2022     if (FoldedVOp.getNode()) return FoldedVOp;
2023   }
2024
2025   // fold (udiv c1, c2) -> c1/c2
2026   if (N0C && N1C && !N1C->isNullValue())
2027     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2028   // fold (udiv x, (1 << c)) -> x >>u c
2029   if (N1C && N1C->getAPIntValue().isPowerOf2())
2030     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2031                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2032                                        getShiftAmountTy(N0.getValueType())));
2033   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2034   if (N1.getOpcode() == ISD::SHL) {
2035     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2036       if (SHC->getAPIntValue().isPowerOf2()) {
2037         EVT ADDVT = N1.getOperand(1).getValueType();
2038         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2039                                   N1.getOperand(1),
2040                                   DAG.getConstant(SHC->getAPIntValue()
2041                                                                   .logBase2(),
2042                                                   ADDVT));
2043         AddToWorkList(Add.getNode());
2044         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2045       }
2046     }
2047   }
2048   // fold (udiv x, c) -> alternate
2049   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2050     SDValue Op = BuildUDIV(N);
2051     if (Op.getNode()) return Op;
2052   }
2053
2054   // undef / X -> 0
2055   if (N0.getOpcode() == ISD::UNDEF)
2056     return DAG.getConstant(0, VT);
2057   // X / undef -> undef
2058   if (N1.getOpcode() == ISD::UNDEF)
2059     return N1;
2060
2061   return SDValue();
2062 }
2063
2064 SDValue DAGCombiner::visitSREM(SDNode *N) {
2065   SDValue N0 = N->getOperand(0);
2066   SDValue N1 = N->getOperand(1);
2067   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2068   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2069   EVT VT = N->getValueType(0);
2070
2071   // fold (srem c1, c2) -> c1%c2
2072   if (N0C && N1C && !N1C->isNullValue())
2073     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2074   // If we know the sign bits of both operands are zero, strength reduce to a
2075   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2076   if (!VT.isVector()) {
2077     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2078       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2079   }
2080
2081   // If X/C can be simplified by the division-by-constant logic, lower
2082   // X%C to the equivalent of X-X/C*C.
2083   if (N1C && !N1C->isNullValue()) {
2084     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2085     AddToWorkList(Div.getNode());
2086     SDValue OptimizedDiv = combine(Div.getNode());
2087     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2088       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2089                                 OptimizedDiv, N1);
2090       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2091       AddToWorkList(Mul.getNode());
2092       return Sub;
2093     }
2094   }
2095
2096   // undef % X -> 0
2097   if (N0.getOpcode() == ISD::UNDEF)
2098     return DAG.getConstant(0, VT);
2099   // X % undef -> undef
2100   if (N1.getOpcode() == ISD::UNDEF)
2101     return N1;
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitUREM(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2110   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2111   EVT VT = N->getValueType(0);
2112
2113   // fold (urem c1, c2) -> c1%c2
2114   if (N0C && N1C && !N1C->isNullValue())
2115     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2116   // fold (urem x, pow2) -> (and x, pow2-1)
2117   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2118     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2119                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2120   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2121   if (N1.getOpcode() == ISD::SHL) {
2122     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2123       if (SHC->getAPIntValue().isPowerOf2()) {
2124         SDValue Add =
2125           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2126                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2127                                  VT));
2128         AddToWorkList(Add.getNode());
2129         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2130       }
2131     }
2132   }
2133
2134   // If X/C can be simplified by the division-by-constant logic, lower
2135   // X%C to the equivalent of X-X/C*C.
2136   if (N1C && !N1C->isNullValue()) {
2137     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2138     AddToWorkList(Div.getNode());
2139     SDValue OptimizedDiv = combine(Div.getNode());
2140     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2141       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2142                                 OptimizedDiv, N1);
2143       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2144       AddToWorkList(Mul.getNode());
2145       return Sub;
2146     }
2147   }
2148
2149   // undef % X -> 0
2150   if (N0.getOpcode() == ISD::UNDEF)
2151     return DAG.getConstant(0, VT);
2152   // X % undef -> undef
2153   if (N1.getOpcode() == ISD::UNDEF)
2154     return N1;
2155
2156   return SDValue();
2157 }
2158
2159 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2160   SDValue N0 = N->getOperand(0);
2161   SDValue N1 = N->getOperand(1);
2162   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2163   EVT VT = N->getValueType(0);
2164   SDLoc DL(N);
2165
2166   // fold (mulhs x, 0) -> 0
2167   if (N1C && N1C->isNullValue())
2168     return N1;
2169   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2170   if (N1C && N1C->getAPIntValue() == 1)
2171     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2172                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2173                                        getShiftAmountTy(N0.getValueType())));
2174   // fold (mulhs x, undef) -> 0
2175   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2176     return DAG.getConstant(0, VT);
2177
2178   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2179   // plus a shift.
2180   if (VT.isSimple() && !VT.isVector()) {
2181     MVT Simple = VT.getSimpleVT();
2182     unsigned SimpleSize = Simple.getSizeInBits();
2183     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2184     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2185       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2186       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2187       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2188       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2189             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2190       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2191     }
2192   }
2193
2194   return SDValue();
2195 }
2196
2197 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2198   SDValue N0 = N->getOperand(0);
2199   SDValue N1 = N->getOperand(1);
2200   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2201   EVT VT = N->getValueType(0);
2202   SDLoc DL(N);
2203
2204   // fold (mulhu x, 0) -> 0
2205   if (N1C && N1C->isNullValue())
2206     return N1;
2207   // fold (mulhu x, 1) -> 0
2208   if (N1C && N1C->getAPIntValue() == 1)
2209     return DAG.getConstant(0, N0.getValueType());
2210   // fold (mulhu x, undef) -> 0
2211   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2212     return DAG.getConstant(0, VT);
2213
2214   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2215   // plus a shift.
2216   if (VT.isSimple() && !VT.isVector()) {
2217     MVT Simple = VT.getSimpleVT();
2218     unsigned SimpleSize = Simple.getSizeInBits();
2219     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2220     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2221       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2222       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2223       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2224       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2225             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2226       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2227     }
2228   }
2229
2230   return SDValue();
2231 }
2232
2233 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2234 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2235 /// that are being performed. Return true if a simplification was made.
2236 ///
2237 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2238                                                 unsigned HiOp) {
2239   // If the high half is not needed, just compute the low half.
2240   bool HiExists = N->hasAnyUseOfValue(1);
2241   if (!HiExists &&
2242       (!LegalOperations ||
2243        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2244     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2245                               N->op_begin(), N->getNumOperands());
2246     return CombineTo(N, Res, Res);
2247   }
2248
2249   // If the low half is not needed, just compute the high half.
2250   bool LoExists = N->hasAnyUseOfValue(0);
2251   if (!LoExists &&
2252       (!LegalOperations ||
2253        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2254     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2255                               N->op_begin(), N->getNumOperands());
2256     return CombineTo(N, Res, Res);
2257   }
2258
2259   // If both halves are used, return as it is.
2260   if (LoExists && HiExists)
2261     return SDValue();
2262
2263   // If the two computed results can be simplified separately, separate them.
2264   if (LoExists) {
2265     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2266                              N->op_begin(), N->getNumOperands());
2267     AddToWorkList(Lo.getNode());
2268     SDValue LoOpt = combine(Lo.getNode());
2269     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2270         (!LegalOperations ||
2271          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2272       return CombineTo(N, LoOpt, LoOpt);
2273   }
2274
2275   if (HiExists) {
2276     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2277                              N->op_begin(), N->getNumOperands());
2278     AddToWorkList(Hi.getNode());
2279     SDValue HiOpt = combine(Hi.getNode());
2280     if (HiOpt.getNode() && HiOpt != Hi &&
2281         (!LegalOperations ||
2282          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2283       return CombineTo(N, HiOpt, HiOpt);
2284   }
2285
2286   return SDValue();
2287 }
2288
2289 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2290   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2291   if (Res.getNode()) return Res;
2292
2293   EVT VT = N->getValueType(0);
2294   SDLoc DL(N);
2295
2296   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2297   // plus a shift.
2298   if (VT.isSimple() && !VT.isVector()) {
2299     MVT Simple = VT.getSimpleVT();
2300     unsigned SimpleSize = Simple.getSizeInBits();
2301     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2302     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2303       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2304       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2305       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2306       // Compute the high part as N1.
2307       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2308             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2309       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2310       // Compute the low part as N0.
2311       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2312       return CombineTo(N, Lo, Hi);
2313     }
2314   }
2315
2316   return SDValue();
2317 }
2318
2319 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2320   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2321   if (Res.getNode()) return Res;
2322
2323   EVT VT = N->getValueType(0);
2324   SDLoc DL(N);
2325
2326   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2327   // plus a shift.
2328   if (VT.isSimple() && !VT.isVector()) {
2329     MVT Simple = VT.getSimpleVT();
2330     unsigned SimpleSize = Simple.getSizeInBits();
2331     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2334       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2335       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336       // Compute the high part as N1.
2337       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2338             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2339       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340       // Compute the low part as N0.
2341       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342       return CombineTo(N, Lo, Hi);
2343     }
2344   }
2345
2346   return SDValue();
2347 }
2348
2349 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2350   // (smulo x, 2) -> (saddo x, x)
2351   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2352     if (C2->getAPIntValue() == 2)
2353       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2354                          N->getOperand(0), N->getOperand(0));
2355
2356   return SDValue();
2357 }
2358
2359 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2360   // (umulo x, 2) -> (uaddo x, x)
2361   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2362     if (C2->getAPIntValue() == 2)
2363       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2364                          N->getOperand(0), N->getOperand(0));
2365
2366   return SDValue();
2367 }
2368
2369 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2370   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2371   if (Res.getNode()) return Res;
2372
2373   return SDValue();
2374 }
2375
2376 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2377   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2378   if (Res.getNode()) return Res;
2379
2380   return SDValue();
2381 }
2382
2383 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2384 /// two operands of the same opcode, try to simplify it.
2385 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2386   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2387   EVT VT = N0.getValueType();
2388   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2389
2390   // Bail early if none of these transforms apply.
2391   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2392
2393   // For each of OP in AND/OR/XOR:
2394   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2395   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2396   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2397   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2398   //
2399   // do not sink logical op inside of a vector extend, since it may combine
2400   // into a vsetcc.
2401   EVT Op0VT = N0.getOperand(0).getValueType();
2402   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2403        N0.getOpcode() == ISD::SIGN_EXTEND ||
2404        // Avoid infinite looping with PromoteIntBinOp.
2405        (N0.getOpcode() == ISD::ANY_EXTEND &&
2406         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2407        (N0.getOpcode() == ISD::TRUNCATE &&
2408         (!TLI.isZExtFree(VT, Op0VT) ||
2409          !TLI.isTruncateFree(Op0VT, VT)) &&
2410         TLI.isTypeLegal(Op0VT))) &&
2411       !VT.isVector() &&
2412       Op0VT == N1.getOperand(0).getValueType() &&
2413       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2414     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2415                                  N0.getOperand(0).getValueType(),
2416                                  N0.getOperand(0), N1.getOperand(0));
2417     AddToWorkList(ORNode.getNode());
2418     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2419   }
2420
2421   // For each of OP in SHL/SRL/SRA/AND...
2422   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2423   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2424   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2425   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2426        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2427       N0.getOperand(1) == N1.getOperand(1)) {
2428     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2429                                  N0.getOperand(0).getValueType(),
2430                                  N0.getOperand(0), N1.getOperand(0));
2431     AddToWorkList(ORNode.getNode());
2432     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2433                        ORNode, N0.getOperand(1));
2434   }
2435
2436   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2437   // Only perform this optimization after type legalization and before
2438   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2439   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2440   // we don't want to undo this promotion.
2441   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2442   // on scalars.
2443   if ((N0.getOpcode() == ISD::BITCAST ||
2444        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2445       Level == AfterLegalizeTypes) {
2446     SDValue In0 = N0.getOperand(0);
2447     SDValue In1 = N1.getOperand(0);
2448     EVT In0Ty = In0.getValueType();
2449     EVT In1Ty = In1.getValueType();
2450     SDLoc DL(N);
2451     // If both incoming values are integers, and the original types are the
2452     // same.
2453     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2454       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2455       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2456       AddToWorkList(Op.getNode());
2457       return BC;
2458     }
2459   }
2460
2461   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2462   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2463   // If both shuffles use the same mask, and both shuffle within a single
2464   // vector, then it is worthwhile to move the swizzle after the operation.
2465   // The type-legalizer generates this pattern when loading illegal
2466   // vector types from memory. In many cases this allows additional shuffle
2467   // optimizations.
2468   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2469       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2470       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2471     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2472     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2473
2474     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2475            "Inputs to shuffles are not the same type");
2476
2477     unsigned NumElts = VT.getVectorNumElements();
2478
2479     // Check that both shuffles use the same mask. The masks are known to be of
2480     // the same length because the result vector type is the same.
2481     bool SameMask = true;
2482     for (unsigned i = 0; i != NumElts; ++i) {
2483       int Idx0 = SVN0->getMaskElt(i);
2484       int Idx1 = SVN1->getMaskElt(i);
2485       if (Idx0 != Idx1) {
2486         SameMask = false;
2487         break;
2488       }
2489     }
2490
2491     if (SameMask) {
2492       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2493                                N0.getOperand(0), N1.getOperand(0));
2494       AddToWorkList(Op.getNode());
2495       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2496                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2497     }
2498   }
2499
2500   return SDValue();
2501 }
2502
2503 SDValue DAGCombiner::visitAND(SDNode *N) {
2504   SDValue N0 = N->getOperand(0);
2505   SDValue N1 = N->getOperand(1);
2506   SDValue LL, LR, RL, RR, CC0, CC1;
2507   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2508   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2509   EVT VT = N1.getValueType();
2510   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2511
2512   // fold vector ops
2513   if (VT.isVector()) {
2514     SDValue FoldedVOp = SimplifyVBinOp(N);
2515     if (FoldedVOp.getNode()) return FoldedVOp;
2516
2517     // fold (and x, 0) -> 0, vector edition
2518     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2519       return N0;
2520     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2521       return N1;
2522
2523     // fold (and x, -1) -> x, vector edition
2524     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2525       return N1;
2526     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2527       return N0;
2528   }
2529
2530   // fold (and x, undef) -> 0
2531   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2532     return DAG.getConstant(0, VT);
2533   // fold (and c1, c2) -> c1&c2
2534   if (N0C && N1C)
2535     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2536   // canonicalize constant to RHS
2537   if (N0C && !N1C)
2538     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2539   // fold (and x, -1) -> x
2540   if (N1C && N1C->isAllOnesValue())
2541     return N0;
2542   // if (and x, c) is known to be zero, return 0
2543   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2544                                    APInt::getAllOnesValue(BitWidth)))
2545     return DAG.getConstant(0, VT);
2546   // reassociate and
2547   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2548   if (RAND.getNode() != 0)
2549     return RAND;
2550   // fold (and (or x, C), D) -> D if (C & D) == D
2551   if (N1C && N0.getOpcode() == ISD::OR)
2552     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2553       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2554         return N1;
2555   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2556   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2557     SDValue N0Op0 = N0.getOperand(0);
2558     APInt Mask = ~N1C->getAPIntValue();
2559     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2560     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2561       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2562                                  N0.getValueType(), N0Op0);
2563
2564       // Replace uses of the AND with uses of the Zero extend node.
2565       CombineTo(N, Zext);
2566
2567       // We actually want to replace all uses of the any_extend with the
2568       // zero_extend, to avoid duplicating things.  This will later cause this
2569       // AND to be folded.
2570       CombineTo(N0.getNode(), Zext);
2571       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2572     }
2573   }
2574   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2575   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2576   // already be zero by virtue of the width of the base type of the load.
2577   //
2578   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2579   // more cases.
2580   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2581        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2582       N0.getOpcode() == ISD::LOAD) {
2583     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2584                                          N0 : N0.getOperand(0) );
2585
2586     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2587     // This can be a pure constant or a vector splat, in which case we treat the
2588     // vector as a scalar and use the splat value.
2589     APInt Constant = APInt::getNullValue(1);
2590     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2591       Constant = C->getAPIntValue();
2592     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2593       APInt SplatValue, SplatUndef;
2594       unsigned SplatBitSize;
2595       bool HasAnyUndefs;
2596       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2597                                              SplatBitSize, HasAnyUndefs);
2598       if (IsSplat) {
2599         // Undef bits can contribute to a possible optimisation if set, so
2600         // set them.
2601         SplatValue |= SplatUndef;
2602
2603         // The splat value may be something like "0x00FFFFFF", which means 0 for
2604         // the first vector value and FF for the rest, repeating. We need a mask
2605         // that will apply equally to all members of the vector, so AND all the
2606         // lanes of the constant together.
2607         EVT VT = Vector->getValueType(0);
2608         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2609
2610         // If the splat value has been compressed to a bitlength lower
2611         // than the size of the vector lane, we need to re-expand it to
2612         // the lane size.
2613         if (BitWidth > SplatBitSize)
2614           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2615                SplatBitSize < BitWidth;
2616                SplatBitSize = SplatBitSize * 2)
2617             SplatValue |= SplatValue.shl(SplatBitSize);
2618
2619         Constant = APInt::getAllOnesValue(BitWidth);
2620         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2621           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2622       }
2623     }
2624
2625     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2626     // actually legal and isn't going to get expanded, else this is a false
2627     // optimisation.
2628     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2629                                                     Load->getMemoryVT());
2630
2631     // Resize the constant to the same size as the original memory access before
2632     // extension. If it is still the AllOnesValue then this AND is completely
2633     // unneeded.
2634     Constant =
2635       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2636
2637     bool B;
2638     switch (Load->getExtensionType()) {
2639     default: B = false; break;
2640     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2641     case ISD::ZEXTLOAD:
2642     case ISD::NON_EXTLOAD: B = true; break;
2643     }
2644
2645     if (B && Constant.isAllOnesValue()) {
2646       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2647       // preserve semantics once we get rid of the AND.
2648       SDValue NewLoad(Load, 0);
2649       if (Load->getExtensionType() == ISD::EXTLOAD) {
2650         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2651                               Load->getValueType(0), SDLoc(Load),
2652                               Load->getChain(), Load->getBasePtr(),
2653                               Load->getOffset(), Load->getMemoryVT(),
2654                               Load->getMemOperand());
2655         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2656         if (Load->getNumValues() == 3) {
2657           // PRE/POST_INC loads have 3 values.
2658           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2659                            NewLoad.getValue(2) };
2660           CombineTo(Load, To, 3, true);
2661         } else {
2662           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2663         }
2664       }
2665
2666       // Fold the AND away, taking care not to fold to the old load node if we
2667       // replaced it.
2668       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2669
2670       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2671     }
2672   }
2673   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2674   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2675     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2676     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2677
2678     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2679         LL.getValueType().isInteger()) {
2680       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2681       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2682         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2683                                      LR.getValueType(), LL, RL);
2684         AddToWorkList(ORNode.getNode());
2685         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2686       }
2687       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2688       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2689         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2690                                       LR.getValueType(), LL, RL);
2691         AddToWorkList(ANDNode.getNode());
2692         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2693       }
2694       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2695       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2696         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2697                                      LR.getValueType(), LL, RL);
2698         AddToWorkList(ORNode.getNode());
2699         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2700       }
2701     }
2702     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2703     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2704         Op0 == Op1 && LL.getValueType().isInteger() &&
2705       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2706                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2707                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2708                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2709       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2710                                     LL, DAG.getConstant(1, LL.getValueType()));
2711       AddToWorkList(ADDNode.getNode());
2712       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2713                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2714     }
2715     // canonicalize equivalent to ll == rl
2716     if (LL == RR && LR == RL) {
2717       Op1 = ISD::getSetCCSwappedOperands(Op1);
2718       std::swap(RL, RR);
2719     }
2720     if (LL == RL && LR == RR) {
2721       bool isInteger = LL.getValueType().isInteger();
2722       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2723       if (Result != ISD::SETCC_INVALID &&
2724           (!LegalOperations ||
2725            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2726             TLI.isOperationLegal(ISD::SETCC,
2727                             getSetCCResultType(N0.getSimpleValueType())))))
2728         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2729                             LL, LR, Result);
2730     }
2731   }
2732
2733   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2734   if (N0.getOpcode() == N1.getOpcode()) {
2735     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2736     if (Tmp.getNode()) return Tmp;
2737   }
2738
2739   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2740   // fold (and (sra)) -> (and (srl)) when possible.
2741   if (!VT.isVector() &&
2742       SimplifyDemandedBits(SDValue(N, 0)))
2743     return SDValue(N, 0);
2744
2745   // fold (zext_inreg (extload x)) -> (zextload x)
2746   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2747     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2748     EVT MemVT = LN0->getMemoryVT();
2749     // If we zero all the possible extended bits, then we can turn this into
2750     // a zextload if we are running before legalize or the operation is legal.
2751     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2752     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2753                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2754         ((!LegalOperations && !LN0->isVolatile()) ||
2755          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2756       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2757                                        LN0->getChain(), LN0->getBasePtr(),
2758                                        LN0->getPointerInfo(), MemVT,
2759                                        LN0->isVolatile(), LN0->isNonTemporal(),
2760                                        LN0->getAlignment());
2761       AddToWorkList(N);
2762       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2763       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2764     }
2765   }
2766   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2767   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2768       N0.hasOneUse()) {
2769     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2770     EVT MemVT = LN0->getMemoryVT();
2771     // If we zero all the possible extended bits, then we can turn this into
2772     // a zextload if we are running before legalize or the operation is legal.
2773     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2774     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2775                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2776         ((!LegalOperations && !LN0->isVolatile()) ||
2777          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2778       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2779                                        LN0->getChain(),
2780                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2781                                        MemVT,
2782                                        LN0->isVolatile(), LN0->isNonTemporal(),
2783                                        LN0->getAlignment());
2784       AddToWorkList(N);
2785       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2786       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2787     }
2788   }
2789
2790   // fold (and (load x), 255) -> (zextload x, i8)
2791   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2792   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2793   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2794               (N0.getOpcode() == ISD::ANY_EXTEND &&
2795                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2796     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2797     LoadSDNode *LN0 = HasAnyExt
2798       ? cast<LoadSDNode>(N0.getOperand(0))
2799       : cast<LoadSDNode>(N0);
2800     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2801         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2802       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2803       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2804         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2805         EVT LoadedVT = LN0->getMemoryVT();
2806
2807         if (ExtVT == LoadedVT &&
2808             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2809           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2810
2811           SDValue NewLoad =
2812             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2813                            LN0->getChain(), LN0->getBasePtr(),
2814                            LN0->getPointerInfo(),
2815                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2816                            LN0->getAlignment());
2817           AddToWorkList(N);
2818           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2819           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2820         }
2821
2822         // Do not change the width of a volatile load.
2823         // Do not generate loads of non-round integer types since these can
2824         // be expensive (and would be wrong if the type is not byte sized).
2825         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2826             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2827           EVT PtrType = LN0->getOperand(1).getValueType();
2828
2829           unsigned Alignment = LN0->getAlignment();
2830           SDValue NewPtr = LN0->getBasePtr();
2831
2832           // For big endian targets, we need to add an offset to the pointer
2833           // to load the correct bytes.  For little endian systems, we merely
2834           // need to read fewer bytes from the same pointer.
2835           if (TLI.isBigEndian()) {
2836             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2837             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2838             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2839             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2840                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2841             Alignment = MinAlign(Alignment, PtrOff);
2842           }
2843
2844           AddToWorkList(NewPtr.getNode());
2845
2846           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2847           SDValue Load =
2848             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2849                            LN0->getChain(), NewPtr,
2850                            LN0->getPointerInfo(),
2851                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2852                            Alignment);
2853           AddToWorkList(N);
2854           CombineTo(LN0, Load, Load.getValue(1));
2855           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2856         }
2857       }
2858     }
2859   }
2860
2861   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2862       VT.getSizeInBits() <= 64) {
2863     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2864       APInt ADDC = ADDI->getAPIntValue();
2865       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2866         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2867         // immediate for an add, but it is legal if its top c2 bits are set,
2868         // transform the ADD so the immediate doesn't need to be materialized
2869         // in a register.
2870         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2871           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2872                                              SRLI->getZExtValue());
2873           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2874             ADDC |= Mask;
2875             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2876               SDValue NewAdd =
2877                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2878                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2879               CombineTo(N0.getNode(), NewAdd);
2880               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2881             }
2882           }
2883         }
2884       }
2885     }
2886   }
2887
2888   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2889   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2890     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2891                                        N0.getOperand(1), false);
2892     if (BSwap.getNode())
2893       return BSwap;
2894   }
2895
2896   return SDValue();
2897 }
2898
2899 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2900 ///
2901 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2902                                         bool DemandHighBits) {
2903   if (!LegalOperations)
2904     return SDValue();
2905
2906   EVT VT = N->getValueType(0);
2907   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2908     return SDValue();
2909   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2910     return SDValue();
2911
2912   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2913   bool LookPassAnd0 = false;
2914   bool LookPassAnd1 = false;
2915   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2916       std::swap(N0, N1);
2917   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2918       std::swap(N0, N1);
2919   if (N0.getOpcode() == ISD::AND) {
2920     if (!N0.getNode()->hasOneUse())
2921       return SDValue();
2922     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2923     if (!N01C || N01C->getZExtValue() != 0xFF00)
2924       return SDValue();
2925     N0 = N0.getOperand(0);
2926     LookPassAnd0 = true;
2927   }
2928
2929   if (N1.getOpcode() == ISD::AND) {
2930     if (!N1.getNode()->hasOneUse())
2931       return SDValue();
2932     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2933     if (!N11C || N11C->getZExtValue() != 0xFF)
2934       return SDValue();
2935     N1 = N1.getOperand(0);
2936     LookPassAnd1 = true;
2937   }
2938
2939   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2940     std::swap(N0, N1);
2941   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2942     return SDValue();
2943   if (!N0.getNode()->hasOneUse() ||
2944       !N1.getNode()->hasOneUse())
2945     return SDValue();
2946
2947   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2948   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2949   if (!N01C || !N11C)
2950     return SDValue();
2951   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2952     return SDValue();
2953
2954   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2955   SDValue N00 = N0->getOperand(0);
2956   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2957     if (!N00.getNode()->hasOneUse())
2958       return SDValue();
2959     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2960     if (!N001C || N001C->getZExtValue() != 0xFF)
2961       return SDValue();
2962     N00 = N00.getOperand(0);
2963     LookPassAnd0 = true;
2964   }
2965
2966   SDValue N10 = N1->getOperand(0);
2967   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2968     if (!N10.getNode()->hasOneUse())
2969       return SDValue();
2970     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2971     if (!N101C || N101C->getZExtValue() != 0xFF00)
2972       return SDValue();
2973     N10 = N10.getOperand(0);
2974     LookPassAnd1 = true;
2975   }
2976
2977   if (N00 != N10)
2978     return SDValue();
2979
2980   // Make sure everything beyond the low halfword gets set to zero since the SRL
2981   // 16 will clear the top bits.
2982   unsigned OpSizeInBits = VT.getSizeInBits();
2983   if (DemandHighBits && OpSizeInBits > 16) {
2984     // If the left-shift isn't masked out then the only way this is a bswap is
2985     // if all bits beyond the low 8 are 0. In that case the entire pattern
2986     // reduces to a left shift anyway: leave it for other parts of the combiner.
2987     if (!LookPassAnd0)
2988       return SDValue();
2989
2990     // However, if the right shift isn't masked out then it might be because
2991     // it's not needed. See if we can spot that too.
2992     if (!LookPassAnd1 &&
2993         !DAG.MaskedValueIsZero(
2994             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2995       return SDValue();
2996   }
2997
2998   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2999   if (OpSizeInBits > 16)
3000     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3001                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3002   return Res;
3003 }
3004
3005 /// isBSwapHWordElement - Return true if the specified node is an element
3006 /// that makes up a 32-bit packed halfword byteswap. i.e.
3007 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3008 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3009   if (!N.getNode()->hasOneUse())
3010     return false;
3011
3012   unsigned Opc = N.getOpcode();
3013   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3014     return false;
3015
3016   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3017   if (!N1C)
3018     return false;
3019
3020   unsigned Num;
3021   switch (N1C->getZExtValue()) {
3022   default:
3023     return false;
3024   case 0xFF:       Num = 0; break;
3025   case 0xFF00:     Num = 1; break;
3026   case 0xFF0000:   Num = 2; break;
3027   case 0xFF000000: Num = 3; break;
3028   }
3029
3030   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3031   SDValue N0 = N.getOperand(0);
3032   if (Opc == ISD::AND) {
3033     if (Num == 0 || Num == 2) {
3034       // (x >> 8) & 0xff
3035       // (x >> 8) & 0xff0000
3036       if (N0.getOpcode() != ISD::SRL)
3037         return false;
3038       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3039       if (!C || C->getZExtValue() != 8)
3040         return false;
3041     } else {
3042       // (x << 8) & 0xff00
3043       // (x << 8) & 0xff000000
3044       if (N0.getOpcode() != ISD::SHL)
3045         return false;
3046       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3047       if (!C || C->getZExtValue() != 8)
3048         return false;
3049     }
3050   } else if (Opc == ISD::SHL) {
3051     // (x & 0xff) << 8
3052     // (x & 0xff0000) << 8
3053     if (Num != 0 && Num != 2)
3054       return false;
3055     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3056     if (!C || C->getZExtValue() != 8)
3057       return false;
3058   } else { // Opc == ISD::SRL
3059     // (x & 0xff00) >> 8
3060     // (x & 0xff000000) >> 8
3061     if (Num != 1 && Num != 3)
3062       return false;
3063     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3064     if (!C || C->getZExtValue() != 8)
3065       return false;
3066   }
3067
3068   if (Parts[Num])
3069     return false;
3070
3071   Parts[Num] = N0.getOperand(0).getNode();
3072   return true;
3073 }
3074
3075 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3076 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3077 /// => (rotl (bswap x), 16)
3078 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3079   if (!LegalOperations)
3080     return SDValue();
3081
3082   EVT VT = N->getValueType(0);
3083   if (VT != MVT::i32)
3084     return SDValue();
3085   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3086     return SDValue();
3087
3088   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3089   // Look for either
3090   // (or (or (and), (and)), (or (and), (and)))
3091   // (or (or (or (and), (and)), (and)), (and))
3092   if (N0.getOpcode() != ISD::OR)
3093     return SDValue();
3094   SDValue N00 = N0.getOperand(0);
3095   SDValue N01 = N0.getOperand(1);
3096
3097   if (N1.getOpcode() == ISD::OR &&
3098       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3099     // (or (or (and), (and)), (or (and), (and)))
3100     SDValue N000 = N00.getOperand(0);
3101     if (!isBSwapHWordElement(N000, Parts))
3102       return SDValue();
3103
3104     SDValue N001 = N00.getOperand(1);
3105     if (!isBSwapHWordElement(N001, Parts))
3106       return SDValue();
3107     SDValue N010 = N01.getOperand(0);
3108     if (!isBSwapHWordElement(N010, Parts))
3109       return SDValue();
3110     SDValue N011 = N01.getOperand(1);
3111     if (!isBSwapHWordElement(N011, Parts))
3112       return SDValue();
3113   } else {
3114     // (or (or (or (and), (and)), (and)), (and))
3115     if (!isBSwapHWordElement(N1, Parts))
3116       return SDValue();
3117     if (!isBSwapHWordElement(N01, Parts))
3118       return SDValue();
3119     if (N00.getOpcode() != ISD::OR)
3120       return SDValue();
3121     SDValue N000 = N00.getOperand(0);
3122     if (!isBSwapHWordElement(N000, Parts))
3123       return SDValue();
3124     SDValue N001 = N00.getOperand(1);
3125     if (!isBSwapHWordElement(N001, Parts))
3126       return SDValue();
3127   }
3128
3129   // Make sure the parts are all coming from the same node.
3130   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3131     return SDValue();
3132
3133   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3134                               SDValue(Parts[0],0));
3135
3136   // Result of the bswap should be rotated by 16. If it's not legal, then
3137   // do  (x << 16) | (x >> 16).
3138   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3139   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3140     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3141   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3142     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3143   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3144                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3145                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3146 }
3147
3148 SDValue DAGCombiner::visitOR(SDNode *N) {
3149   SDValue N0 = N->getOperand(0);
3150   SDValue N1 = N->getOperand(1);
3151   SDValue LL, LR, RL, RR, CC0, CC1;
3152   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3153   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3154   EVT VT = N1.getValueType();
3155
3156   // fold vector ops
3157   if (VT.isVector()) {
3158     SDValue FoldedVOp = SimplifyVBinOp(N);
3159     if (FoldedVOp.getNode()) return FoldedVOp;
3160
3161     // fold (or x, 0) -> x, vector edition
3162     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3163       return N1;
3164     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3165       return N0;
3166
3167     // fold (or x, -1) -> -1, vector edition
3168     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3169       return N0;
3170     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3171       return N1;
3172   }
3173
3174   // fold (or x, undef) -> -1
3175   if (!LegalOperations &&
3176       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3177     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3178     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3179   }
3180   // fold (or c1, c2) -> c1|c2
3181   if (N0C && N1C)
3182     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3183   // canonicalize constant to RHS
3184   if (N0C && !N1C)
3185     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3186   // fold (or x, 0) -> x
3187   if (N1C && N1C->isNullValue())
3188     return N0;
3189   // fold (or x, -1) -> -1
3190   if (N1C && N1C->isAllOnesValue())
3191     return N1;
3192   // fold (or x, c) -> c iff (x & ~c) == 0
3193   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3194     return N1;
3195
3196   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3197   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3198   if (BSwap.getNode() != 0)
3199     return BSwap;
3200   BSwap = MatchBSwapHWordLow(N, N0, N1);
3201   if (BSwap.getNode() != 0)
3202     return BSwap;
3203
3204   // reassociate or
3205   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3206   if (ROR.getNode() != 0)
3207     return ROR;
3208   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3209   // iff (c1 & c2) == 0.
3210   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3211              isa<ConstantSDNode>(N0.getOperand(1))) {
3212     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3213     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3214       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3215                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3216                                      N0.getOperand(0), N1),
3217                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3218   }
3219   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3220   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3221     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3222     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3223
3224     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3225         LL.getValueType().isInteger()) {
3226       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3227       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3228       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3229           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3230         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3231                                      LR.getValueType(), LL, RL);
3232         AddToWorkList(ORNode.getNode());
3233         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3234       }
3235       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3236       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3237       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3238           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3239         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3240                                       LR.getValueType(), LL, RL);
3241         AddToWorkList(ANDNode.getNode());
3242         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3243       }
3244     }
3245     // canonicalize equivalent to ll == rl
3246     if (LL == RR && LR == RL) {
3247       Op1 = ISD::getSetCCSwappedOperands(Op1);
3248       std::swap(RL, RR);
3249     }
3250     if (LL == RL && LR == RR) {
3251       bool isInteger = LL.getValueType().isInteger();
3252       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3253       if (Result != ISD::SETCC_INVALID &&
3254           (!LegalOperations ||
3255            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3256             TLI.isOperationLegal(ISD::SETCC,
3257               getSetCCResultType(N0.getValueType())))))
3258         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3259                             LL, LR, Result);
3260     }
3261   }
3262
3263   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3264   if (N0.getOpcode() == N1.getOpcode()) {
3265     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3266     if (Tmp.getNode()) return Tmp;
3267   }
3268
3269   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3270   if (N0.getOpcode() == ISD::AND &&
3271       N1.getOpcode() == ISD::AND &&
3272       N0.getOperand(1).getOpcode() == ISD::Constant &&
3273       N1.getOperand(1).getOpcode() == ISD::Constant &&
3274       // Don't increase # computations.
3275       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3276     // We can only do this xform if we know that bits from X that are set in C2
3277     // but not in C1 are already zero.  Likewise for Y.
3278     const APInt &LHSMask =
3279       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3280     const APInt &RHSMask =
3281       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3282
3283     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3284         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3285       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3286                               N0.getOperand(0), N1.getOperand(0));
3287       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3288                          DAG.getConstant(LHSMask | RHSMask, VT));
3289     }
3290   }
3291
3292   // See if this is some rotate idiom.
3293   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3294     return SDValue(Rot, 0);
3295
3296   // Simplify the operands using demanded-bits information.
3297   if (!VT.isVector() &&
3298       SimplifyDemandedBits(SDValue(N, 0)))
3299     return SDValue(N, 0);
3300
3301   return SDValue();
3302 }
3303
3304 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3305 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3306   if (Op.getOpcode() == ISD::AND) {
3307     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3308       Mask = Op.getOperand(1);
3309       Op = Op.getOperand(0);
3310     } else {
3311       return false;
3312     }
3313   }
3314
3315   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3316     Shift = Op;
3317     return true;
3318   }
3319
3320   return false;
3321 }
3322
3323 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3324 // idioms for rotate, and if the target supports rotation instructions, generate
3325 // a rot[lr].
3326 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3327   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3328   EVT VT = LHS.getValueType();
3329   if (!TLI.isTypeLegal(VT)) return 0;
3330
3331   // The target must have at least one rotate flavor.
3332   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3333   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3334   if (!HasROTL && !HasROTR) return 0;
3335
3336   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3337   SDValue LHSShift;   // The shift.
3338   SDValue LHSMask;    // AND value if any.
3339   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3340     return 0; // Not part of a rotate.
3341
3342   SDValue RHSShift;   // The shift.
3343   SDValue RHSMask;    // AND value if any.
3344   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3345     return 0; // Not part of a rotate.
3346
3347   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3348     return 0;   // Not shifting the same value.
3349
3350   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3351     return 0;   // Shifts must disagree.
3352
3353   // Canonicalize shl to left side in a shl/srl pair.
3354   if (RHSShift.getOpcode() == ISD::SHL) {
3355     std::swap(LHS, RHS);
3356     std::swap(LHSShift, RHSShift);
3357     std::swap(LHSMask , RHSMask );
3358   }
3359
3360   unsigned OpSizeInBits = VT.getSizeInBits();
3361   SDValue LHSShiftArg = LHSShift.getOperand(0);
3362   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3363   SDValue RHSShiftArg = RHSShift.getOperand(0);
3364   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3365
3366   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3367   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3368   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3369       RHSShiftAmt.getOpcode() == ISD::Constant) {
3370     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3371     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3372     if ((LShVal + RShVal) != OpSizeInBits)
3373       return 0;
3374
3375     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3376                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3377
3378     // If there is an AND of either shifted operand, apply it to the result.
3379     if (LHSMask.getNode() || RHSMask.getNode()) {
3380       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3381
3382       if (LHSMask.getNode()) {
3383         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3384         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3385       }
3386       if (RHSMask.getNode()) {
3387         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3388         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3389       }
3390
3391       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3392     }
3393
3394     return Rot.getNode();
3395   }
3396
3397   // If there is a mask here, and we have a variable shift, we can't be sure
3398   // that we're masking out the right stuff.
3399   if (LHSMask.getNode() || RHSMask.getNode())
3400     return 0;
3401
3402   // If the shift amount is sign/zext/any-extended just peel it off.
3403   SDValue LExtOp0 = LHSShiftAmt;
3404   SDValue RExtOp0 = RHSShiftAmt;
3405   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3406        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3407        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3408        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3409       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3410        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3411        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3412        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3413     LExtOp0 = LHSShiftAmt.getOperand(0);
3414     RExtOp0 = RHSShiftAmt.getOperand(0);
3415   }
3416
3417   if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3418     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3419     //   (rotl x, y)
3420     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3421     //   (rotr x, (sub 32, y))
3422     if (ConstantSDNode *SUBC =
3423             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3424       if (SUBC->getAPIntValue() == OpSizeInBits) {
3425         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3426                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3427       } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3428                  LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3429         // fold (or (shl (*ext x), (*ext y)),
3430         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3431         //   (*ext (rotl x, y))
3432         // fold (or (shl (*ext x), (*ext y)),
3433         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3434         //   (*ext (rotr x, (sub 32, y)))
3435         SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3436         EVT LArgVT = LArgExtOp0.getValueType();
3437         bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3438         bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3439         if (HasROTRWithLArg || HasROTLWithLArg) {
3440           if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3441             SDValue V =
3442                 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3443                             LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3444             return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3445           }     
3446         }     
3447       }
3448     }
3449   } else if (LExtOp0.getOpcode() == ISD::SUB &&
3450              RExtOp0 == LExtOp0.getOperand(1)) {
3451     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3452     //   (rotr x, y)
3453     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3454     //   (rotl x, (sub 32, y))
3455     if (ConstantSDNode *SUBC =
3456             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3457       if (SUBC->getAPIntValue() == OpSizeInBits) {
3458         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3459                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3460       } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3461                  RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3462         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3463         //          (srl (*ext x), (*ext y))) ->
3464         //   (*ext (rotl x, y))
3465         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3466         //          (srl (*ext x), (*ext y))) ->
3467         //   (*ext (rotr x, (sub 32, y)))
3468         SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3469         EVT RArgVT = RArgExtOp0.getValueType();
3470         bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3471         bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3472         if (HasROTRWithRArg || HasROTLWithRArg) {
3473           if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3474             SDValue V =
3475                 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3476                             RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3477             return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3478           }
3479         }
3480       }
3481     }
3482   }
3483
3484   return 0;
3485 }
3486
3487 SDValue DAGCombiner::visitXOR(SDNode *N) {
3488   SDValue N0 = N->getOperand(0);
3489   SDValue N1 = N->getOperand(1);
3490   SDValue LHS, RHS, CC;
3491   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3492   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3493   EVT VT = N0.getValueType();
3494
3495   // fold vector ops
3496   if (VT.isVector()) {
3497     SDValue FoldedVOp = SimplifyVBinOp(N);
3498     if (FoldedVOp.getNode()) return FoldedVOp;
3499
3500     // fold (xor x, 0) -> x, vector edition
3501     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3502       return N1;
3503     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3504       return N0;
3505   }
3506
3507   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3508   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3509     return DAG.getConstant(0, VT);
3510   // fold (xor x, undef) -> undef
3511   if (N0.getOpcode() == ISD::UNDEF)
3512     return N0;
3513   if (N1.getOpcode() == ISD::UNDEF)
3514     return N1;
3515   // fold (xor c1, c2) -> c1^c2
3516   if (N0C && N1C)
3517     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3518   // canonicalize constant to RHS
3519   if (N0C && !N1C)
3520     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3521   // fold (xor x, 0) -> x
3522   if (N1C && N1C->isNullValue())
3523     return N0;
3524   // reassociate xor
3525   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3526   if (RXOR.getNode() != 0)
3527     return RXOR;
3528
3529   // fold !(x cc y) -> (x !cc y)
3530   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3531     bool isInt = LHS.getValueType().isInteger();
3532     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3533                                                isInt);
3534
3535     if (!LegalOperations ||
3536         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3537       switch (N0.getOpcode()) {
3538       default:
3539         llvm_unreachable("Unhandled SetCC Equivalent!");
3540       case ISD::SETCC:
3541         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3542       case ISD::SELECT_CC:
3543         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3544                                N0.getOperand(3), NotCC);
3545       }
3546     }
3547   }
3548
3549   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3550   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3551       N0.getNode()->hasOneUse() &&
3552       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3553     SDValue V = N0.getOperand(0);
3554     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3555                     DAG.getConstant(1, V.getValueType()));
3556     AddToWorkList(V.getNode());
3557     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3558   }
3559
3560   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3561   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3562       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3563     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3564     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3565       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3566       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3567       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3568       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3569       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3570     }
3571   }
3572   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3573   if (N1C && N1C->isAllOnesValue() &&
3574       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3575     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3576     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3577       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3578       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3579       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3580       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3581       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3582     }
3583   }
3584   // fold (xor (and x, y), y) -> (and (not x), y)
3585   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3586       N0->getOperand(1) == N1) {
3587     SDValue X = N0->getOperand(0);
3588     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3589     AddToWorkList(NotX.getNode());
3590     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3591   }
3592   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3593   if (N1C && N0.getOpcode() == ISD::XOR) {
3594     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3595     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3596     if (N00C)
3597       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3598                          DAG.getConstant(N1C->getAPIntValue() ^
3599                                          N00C->getAPIntValue(), VT));
3600     if (N01C)
3601       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3602                          DAG.getConstant(N1C->getAPIntValue() ^
3603                                          N01C->getAPIntValue(), VT));
3604   }
3605   // fold (xor x, x) -> 0
3606   if (N0 == N1)
3607     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3608
3609   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3610   if (N0.getOpcode() == N1.getOpcode()) {
3611     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3612     if (Tmp.getNode()) return Tmp;
3613   }
3614
3615   // Simplify the expression using non-local knowledge.
3616   if (!VT.isVector() &&
3617       SimplifyDemandedBits(SDValue(N, 0)))
3618     return SDValue(N, 0);
3619
3620   return SDValue();
3621 }
3622
3623 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3624 /// the shift amount is a constant.
3625 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3626   SDNode *LHS = N->getOperand(0).getNode();
3627   if (!LHS->hasOneUse()) return SDValue();
3628
3629   // We want to pull some binops through shifts, so that we have (and (shift))
3630   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3631   // thing happens with address calculations, so it's important to canonicalize
3632   // it.
3633   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3634
3635   switch (LHS->getOpcode()) {
3636   default: return SDValue();
3637   case ISD::OR:
3638   case ISD::XOR:
3639     HighBitSet = false; // We can only transform sra if the high bit is clear.
3640     break;
3641   case ISD::AND:
3642     HighBitSet = true;  // We can only transform sra if the high bit is set.
3643     break;
3644   case ISD::ADD:
3645     if (N->getOpcode() != ISD::SHL)
3646       return SDValue(); // only shl(add) not sr[al](add).
3647     HighBitSet = false; // We can only transform sra if the high bit is clear.
3648     break;
3649   }
3650
3651   // We require the RHS of the binop to be a constant as well.
3652   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3653   if (!BinOpCst) return SDValue();
3654
3655   // FIXME: disable this unless the input to the binop is a shift by a constant.
3656   // If it is not a shift, it pessimizes some common cases like:
3657   //
3658   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3659   //    int bar(int *X, int i) { return X[i & 255]; }
3660   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3661   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3662        BinOpLHSVal->getOpcode() != ISD::SRA &&
3663        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3664       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3665     return SDValue();
3666
3667   EVT VT = N->getValueType(0);
3668
3669   // If this is a signed shift right, and the high bit is modified by the
3670   // logical operation, do not perform the transformation. The highBitSet
3671   // boolean indicates the value of the high bit of the constant which would
3672   // cause it to be modified for this operation.
3673   if (N->getOpcode() == ISD::SRA) {
3674     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3675     if (BinOpRHSSignSet != HighBitSet)
3676       return SDValue();
3677   }
3678
3679   // Fold the constants, shifting the binop RHS by the shift amount.
3680   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3681                                N->getValueType(0),
3682                                LHS->getOperand(1), N->getOperand(1));
3683
3684   // Create the new shift.
3685   SDValue NewShift = DAG.getNode(N->getOpcode(),
3686                                  SDLoc(LHS->getOperand(0)),
3687                                  VT, LHS->getOperand(0), N->getOperand(1));
3688
3689   // Create the new binop.
3690   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3691 }
3692
3693 SDValue DAGCombiner::visitSHL(SDNode *N) {
3694   SDValue N0 = N->getOperand(0);
3695   SDValue N1 = N->getOperand(1);
3696   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3697   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3698   EVT VT = N0.getValueType();
3699   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3700
3701   // fold (shl c1, c2) -> c1<<c2
3702   if (N0C && N1C)
3703     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3704   // fold (shl 0, x) -> 0
3705   if (N0C && N0C->isNullValue())
3706     return N0;
3707   // fold (shl x, c >= size(x)) -> undef
3708   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3709     return DAG.getUNDEF(VT);
3710   // fold (shl x, 0) -> x
3711   if (N1C && N1C->isNullValue())
3712     return N0;
3713   // fold (shl undef, x) -> 0
3714   if (N0.getOpcode() == ISD::UNDEF)
3715     return DAG.getConstant(0, VT);
3716   // if (shl x, c) is known to be zero, return 0
3717   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3718                             APInt::getAllOnesValue(OpSizeInBits)))
3719     return DAG.getConstant(0, VT);
3720   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3721   if (N1.getOpcode() == ISD::TRUNCATE &&
3722       N1.getOperand(0).getOpcode() == ISD::AND &&
3723       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3724     SDValue N101 = N1.getOperand(0).getOperand(1);
3725     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3726       EVT TruncVT = N1.getValueType();
3727       SDValue N100 = N1.getOperand(0).getOperand(0);
3728       APInt TruncC = N101C->getAPIntValue();
3729       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3730       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3731                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3732                                      DAG.getNode(ISD::TRUNCATE,
3733                                                  SDLoc(N),
3734                                                  TruncVT, N100),
3735                                      DAG.getConstant(TruncC, TruncVT)));
3736     }
3737   }
3738
3739   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3740     return SDValue(N, 0);
3741
3742   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3743   if (N1C && N0.getOpcode() == ISD::SHL &&
3744       N0.getOperand(1).getOpcode() == ISD::Constant) {
3745     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3746     uint64_t c2 = N1C->getZExtValue();
3747     if (c1 + c2 >= OpSizeInBits)
3748       return DAG.getConstant(0, VT);
3749     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3750                        DAG.getConstant(c1 + c2, N1.getValueType()));
3751   }
3752
3753   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3754   // For this to be valid, the second form must not preserve any of the bits
3755   // that are shifted out by the inner shift in the first form.  This means
3756   // the outer shift size must be >= the number of bits added by the ext.
3757   // As a corollary, we don't care what kind of ext it is.
3758   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3759               N0.getOpcode() == ISD::ANY_EXTEND ||
3760               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3761       N0.getOperand(0).getOpcode() == ISD::SHL &&
3762       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3763     uint64_t c1 =
3764       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3765     uint64_t c2 = N1C->getZExtValue();
3766     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3767     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3768     if (c2 >= OpSizeInBits - InnerShiftSize) {
3769       if (c1 + c2 >= OpSizeInBits)
3770         return DAG.getConstant(0, VT);
3771       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3772                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3773                                      N0.getOperand(0)->getOperand(0)),
3774                          DAG.getConstant(c1 + c2, N1.getValueType()));
3775     }
3776   }
3777
3778   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3779   // Only fold this if the inner zext has no other uses to avoid increasing
3780   // the total number of instructions.
3781   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3782       N0.getOperand(0).getOpcode() == ISD::SRL &&
3783       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3784     uint64_t c1 =
3785       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3786     if (c1 < VT.getSizeInBits()) {
3787       uint64_t c2 = N1C->getZExtValue();
3788       if (c1 == c2) {
3789         SDValue NewOp0 = N0.getOperand(0);
3790         EVT CountVT = NewOp0.getOperand(1).getValueType();
3791         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3792                                      NewOp0, DAG.getConstant(c2, CountVT));
3793         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3794       }
3795     }
3796   }
3797
3798   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3799   //                               (and (srl x, (sub c1, c2), MASK)
3800   // Only fold this if the inner shift has no other uses -- if it does, folding
3801   // this will increase the total number of instructions.
3802   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3803       N0.getOperand(1).getOpcode() == ISD::Constant) {
3804     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3805     if (c1 < VT.getSizeInBits()) {
3806       uint64_t c2 = N1C->getZExtValue();
3807       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3808                                          VT.getSizeInBits() - c1);
3809       SDValue Shift;
3810       if (c2 > c1) {
3811         Mask = Mask.shl(c2-c1);
3812         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3813                             DAG.getConstant(c2-c1, N1.getValueType()));
3814       } else {
3815         Mask = Mask.lshr(c1-c2);
3816         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3817                             DAG.getConstant(c1-c2, N1.getValueType()));
3818       }
3819       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3820                          DAG.getConstant(Mask, VT));
3821     }
3822   }
3823   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3824   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3825     SDValue HiBitsMask =
3826       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3827                                             VT.getSizeInBits() -
3828                                               N1C->getZExtValue()),
3829                       VT);
3830     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3831                        HiBitsMask);
3832   }
3833
3834   if (N1C) {
3835     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3836     if (NewSHL.getNode())
3837       return NewSHL;
3838   }
3839
3840   return SDValue();
3841 }
3842
3843 SDValue DAGCombiner::visitSRA(SDNode *N) {
3844   SDValue N0 = N->getOperand(0);
3845   SDValue N1 = N->getOperand(1);
3846   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3848   EVT VT = N0.getValueType();
3849   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3850
3851   // fold (sra c1, c2) -> (sra c1, c2)
3852   if (N0C && N1C)
3853     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3854   // fold (sra 0, x) -> 0
3855   if (N0C && N0C->isNullValue())
3856     return N0;
3857   // fold (sra -1, x) -> -1
3858   if (N0C && N0C->isAllOnesValue())
3859     return N0;
3860   // fold (sra x, (setge c, size(x))) -> undef
3861   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3862     return DAG.getUNDEF(VT);
3863   // fold (sra x, 0) -> x
3864   if (N1C && N1C->isNullValue())
3865     return N0;
3866   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3867   // sext_inreg.
3868   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3869     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3870     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3871     if (VT.isVector())
3872       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3873                                ExtVT, VT.getVectorNumElements());
3874     if ((!LegalOperations ||
3875          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3876       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3877                          N0.getOperand(0), DAG.getValueType(ExtVT));
3878   }
3879
3880   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3881   if (N1C && N0.getOpcode() == ISD::SRA) {
3882     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3883       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3884       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3885       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3886                          DAG.getConstant(Sum, N1C->getValueType(0)));
3887     }
3888   }
3889
3890   // fold (sra (shl X, m), (sub result_size, n))
3891   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3892   // result_size - n != m.
3893   // If truncate is free for the target sext(shl) is likely to result in better
3894   // code.
3895   if (N0.getOpcode() == ISD::SHL) {
3896     // Get the two constanst of the shifts, CN0 = m, CN = n.
3897     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3898     if (N01C && N1C) {
3899       // Determine what the truncate's result bitsize and type would be.
3900       EVT TruncVT =
3901         EVT::getIntegerVT(*DAG.getContext(),
3902                           OpSizeInBits - N1C->getZExtValue());
3903       // Determine the residual right-shift amount.
3904       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3905
3906       // If the shift is not a no-op (in which case this should be just a sign
3907       // extend already), the truncated to type is legal, sign_extend is legal
3908       // on that type, and the truncate to that type is both legal and free,
3909       // perform the transform.
3910       if ((ShiftAmt > 0) &&
3911           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3912           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3913           TLI.isTruncateFree(VT, TruncVT)) {
3914
3915           SDValue Amt = DAG.getConstant(ShiftAmt,
3916               getShiftAmountTy(N0.getOperand(0).getValueType()));
3917           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3918                                       N0.getOperand(0), Amt);
3919           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3920                                       Shift);
3921           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3922                              N->getValueType(0), Trunc);
3923       }
3924     }
3925   }
3926
3927   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3928   if (N1.getOpcode() == ISD::TRUNCATE &&
3929       N1.getOperand(0).getOpcode() == ISD::AND &&
3930       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3931     SDValue N101 = N1.getOperand(0).getOperand(1);
3932     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3933       EVT TruncVT = N1.getValueType();
3934       SDValue N100 = N1.getOperand(0).getOperand(0);
3935       APInt TruncC = N101C->getAPIntValue();
3936       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3937       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3938                          DAG.getNode(ISD::AND, SDLoc(N),
3939                                      TruncVT,
3940                                      DAG.getNode(ISD::TRUNCATE,
3941                                                  SDLoc(N),
3942                                                  TruncVT, N100),
3943                                      DAG.getConstant(TruncC, TruncVT)));
3944     }
3945   }
3946
3947   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3948   //      if c1 is equal to the number of bits the trunc removes
3949   if (N0.getOpcode() == ISD::TRUNCATE &&
3950       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3951        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3952       N0.getOperand(0).hasOneUse() &&
3953       N0.getOperand(0).getOperand(1).hasOneUse() &&
3954       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3955     EVT LargeVT = N0.getOperand(0).getValueType();
3956     ConstantSDNode *LargeShiftAmt =
3957       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3958
3959     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3960         LargeShiftAmt->getZExtValue()) {
3961       SDValue Amt =
3962         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3963               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3964       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3965                                 N0.getOperand(0).getOperand(0), Amt);
3966       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3967     }
3968   }
3969
3970   // Simplify, based on bits shifted out of the LHS.
3971   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3972     return SDValue(N, 0);
3973
3974
3975   // If the sign bit is known to be zero, switch this to a SRL.
3976   if (DAG.SignBitIsZero(N0))
3977     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3978
3979   if (N1C) {
3980     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3981     if (NewSRA.getNode())
3982       return NewSRA;
3983   }
3984
3985   return SDValue();
3986 }
3987
3988 SDValue DAGCombiner::visitSRL(SDNode *N) {
3989   SDValue N0 = N->getOperand(0);
3990   SDValue N1 = N->getOperand(1);
3991   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3992   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3993   EVT VT = N0.getValueType();
3994   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3995
3996   // fold (srl c1, c2) -> c1 >>u c2
3997   if (N0C && N1C)
3998     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3999   // fold (srl 0, x) -> 0
4000   if (N0C && N0C->isNullValue())
4001     return N0;
4002   // fold (srl x, c >= size(x)) -> undef
4003   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4004     return DAG.getUNDEF(VT);
4005   // fold (srl x, 0) -> x
4006   if (N1C && N1C->isNullValue())
4007     return N0;
4008   // if (srl x, c) is known to be zero, return 0
4009   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4010                                    APInt::getAllOnesValue(OpSizeInBits)))
4011     return DAG.getConstant(0, VT);
4012
4013   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4014   if (N1C && N0.getOpcode() == ISD::SRL &&
4015       N0.getOperand(1).getOpcode() == ISD::Constant) {
4016     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4017     uint64_t c2 = N1C->getZExtValue();
4018     if (c1 + c2 >= OpSizeInBits)
4019       return DAG.getConstant(0, VT);
4020     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4021                        DAG.getConstant(c1 + c2, N1.getValueType()));
4022   }
4023
4024   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4025   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4026       N0.getOperand(0).getOpcode() == ISD::SRL &&
4027       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4028     uint64_t c1 =
4029       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4030     uint64_t c2 = N1C->getZExtValue();
4031     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4032     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4033     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4034     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4035     if (c1 + OpSizeInBits == InnerShiftSize) {
4036       if (c1 + c2 >= InnerShiftSize)
4037         return DAG.getConstant(0, VT);
4038       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4039                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4040                                      N0.getOperand(0)->getOperand(0),
4041                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4042     }
4043   }
4044
4045   // fold (srl (shl x, c), c) -> (and x, cst2)
4046   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4047       N0.getValueSizeInBits() <= 64) {
4048     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4049     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4050                        DAG.getConstant(~0ULL >> ShAmt, VT));
4051   }
4052
4053   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4054   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4055     // Shifting in all undef bits?
4056     EVT SmallVT = N0.getOperand(0).getValueType();
4057     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4058       return DAG.getUNDEF(VT);
4059
4060     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4061       uint64_t ShiftAmt = N1C->getZExtValue();
4062       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4063                                        N0.getOperand(0),
4064                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4065       AddToWorkList(SmallShift.getNode());
4066       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4067       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4068                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4069                          DAG.getConstant(Mask, VT));
4070     }
4071   }
4072
4073   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4074   // bit, which is unmodified by sra.
4075   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4076     if (N0.getOpcode() == ISD::SRA)
4077       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4078   }
4079
4080   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4081   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4082       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4083     APInt KnownZero, KnownOne;
4084     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4085
4086     // If any of the input bits are KnownOne, then the input couldn't be all
4087     // zeros, thus the result of the srl will always be zero.
4088     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4089
4090     // If all of the bits input the to ctlz node are known to be zero, then
4091     // the result of the ctlz is "32" and the result of the shift is one.
4092     APInt UnknownBits = ~KnownZero;
4093     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4094
4095     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4096     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4097       // Okay, we know that only that the single bit specified by UnknownBits
4098       // could be set on input to the CTLZ node. If this bit is set, the SRL
4099       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4100       // to an SRL/XOR pair, which is likely to simplify more.
4101       unsigned ShAmt = UnknownBits.countTrailingZeros();
4102       SDValue Op = N0.getOperand(0);
4103
4104       if (ShAmt) {
4105         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4106                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4107         AddToWorkList(Op.getNode());
4108       }
4109
4110       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4111                          Op, DAG.getConstant(1, VT));
4112     }
4113   }
4114
4115   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4116   if (N1.getOpcode() == ISD::TRUNCATE &&
4117       N1.getOperand(0).getOpcode() == ISD::AND &&
4118       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4119     SDValue N101 = N1.getOperand(0).getOperand(1);
4120     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4121       EVT TruncVT = N1.getValueType();
4122       SDValue N100 = N1.getOperand(0).getOperand(0);
4123       APInt TruncC = N101C->getAPIntValue();
4124       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4125       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4126                          DAG.getNode(ISD::AND, SDLoc(N),
4127                                      TruncVT,
4128                                      DAG.getNode(ISD::TRUNCATE,
4129                                                  SDLoc(N),
4130                                                  TruncVT, N100),
4131                                      DAG.getConstant(TruncC, TruncVT)));
4132     }
4133   }
4134
4135   // fold operands of srl based on knowledge that the low bits are not
4136   // demanded.
4137   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4138     return SDValue(N, 0);
4139
4140   if (N1C) {
4141     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4142     if (NewSRL.getNode())
4143       return NewSRL;
4144   }
4145
4146   // Attempt to convert a srl of a load into a narrower zero-extending load.
4147   SDValue NarrowLoad = ReduceLoadWidth(N);
4148   if (NarrowLoad.getNode())
4149     return NarrowLoad;
4150
4151   // Here is a common situation. We want to optimize:
4152   //
4153   //   %a = ...
4154   //   %b = and i32 %a, 2
4155   //   %c = srl i32 %b, 1
4156   //   brcond i32 %c ...
4157   //
4158   // into
4159   //
4160   //   %a = ...
4161   //   %b = and %a, 2
4162   //   %c = setcc eq %b, 0
4163   //   brcond %c ...
4164   //
4165   // However when after the source operand of SRL is optimized into AND, the SRL
4166   // itself may not be optimized further. Look for it and add the BRCOND into
4167   // the worklist.
4168   if (N->hasOneUse()) {
4169     SDNode *Use = *N->use_begin();
4170     if (Use->getOpcode() == ISD::BRCOND)
4171       AddToWorkList(Use);
4172     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4173       // Also look pass the truncate.
4174       Use = *Use->use_begin();
4175       if (Use->getOpcode() == ISD::BRCOND)
4176         AddToWorkList(Use);
4177     }
4178   }
4179
4180   return SDValue();
4181 }
4182
4183 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4184   SDValue N0 = N->getOperand(0);
4185   EVT VT = N->getValueType(0);
4186
4187   // fold (ctlz c1) -> c2
4188   if (isa<ConstantSDNode>(N0))
4189     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4190   return SDValue();
4191 }
4192
4193 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4194   SDValue N0 = N->getOperand(0);
4195   EVT VT = N->getValueType(0);
4196
4197   // fold (ctlz_zero_undef c1) -> c2
4198   if (isa<ConstantSDNode>(N0))
4199     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4200   return SDValue();
4201 }
4202
4203 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4204   SDValue N0 = N->getOperand(0);
4205   EVT VT = N->getValueType(0);
4206
4207   // fold (cttz c1) -> c2
4208   if (isa<ConstantSDNode>(N0))
4209     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4210   return SDValue();
4211 }
4212
4213 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4214   SDValue N0 = N->getOperand(0);
4215   EVT VT = N->getValueType(0);
4216
4217   // fold (cttz_zero_undef c1) -> c2
4218   if (isa<ConstantSDNode>(N0))
4219     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4220   return SDValue();
4221 }
4222
4223 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4224   SDValue N0 = N->getOperand(0);
4225   EVT VT = N->getValueType(0);
4226
4227   // fold (ctpop c1) -> c2
4228   if (isa<ConstantSDNode>(N0))
4229     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4230   return SDValue();
4231 }
4232
4233 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4234   SDValue N0 = N->getOperand(0);
4235   SDValue N1 = N->getOperand(1);
4236   SDValue N2 = N->getOperand(2);
4237   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4238   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4239   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4240   EVT VT = N->getValueType(0);
4241   EVT VT0 = N0.getValueType();
4242
4243   // fold (select C, X, X) -> X
4244   if (N1 == N2)
4245     return N1;
4246   // fold (select true, X, Y) -> X
4247   if (N0C && !N0C->isNullValue())
4248     return N1;
4249   // fold (select false, X, Y) -> Y
4250   if (N0C && N0C->isNullValue())
4251     return N2;
4252   // fold (select C, 1, X) -> (or C, X)
4253   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4254     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4255   // fold (select C, 0, 1) -> (xor C, 1)
4256   if (VT.isInteger() &&
4257       (VT0 == MVT::i1 ||
4258        (VT0.isInteger() &&
4259         TLI.getBooleanContents(false) ==
4260         TargetLowering::ZeroOrOneBooleanContent)) &&
4261       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4262     SDValue XORNode;
4263     if (VT == VT0)
4264       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4265                          N0, DAG.getConstant(1, VT0));
4266     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4267                           N0, DAG.getConstant(1, VT0));
4268     AddToWorkList(XORNode.getNode());
4269     if (VT.bitsGT(VT0))
4270       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4271     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4272   }
4273   // fold (select C, 0, X) -> (and (not C), X)
4274   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4275     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4276     AddToWorkList(NOTNode.getNode());
4277     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4278   }
4279   // fold (select C, X, 1) -> (or (not C), X)
4280   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4281     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4282     AddToWorkList(NOTNode.getNode());
4283     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4284   }
4285   // fold (select C, X, 0) -> (and C, X)
4286   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4287     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4288   // fold (select X, X, Y) -> (or X, Y)
4289   // fold (select X, 1, Y) -> (or X, Y)
4290   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4291     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4292   // fold (select X, Y, X) -> (and X, Y)
4293   // fold (select X, Y, 0) -> (and X, Y)
4294   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4295     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4296
4297   // If we can fold this based on the true/false value, do so.
4298   if (SimplifySelectOps(N, N1, N2))
4299     return SDValue(N, 0);  // Don't revisit N.
4300
4301   // fold selects based on a setcc into other things, such as min/max/abs
4302   if (N0.getOpcode() == ISD::SETCC) {
4303     // FIXME:
4304     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4305     // having to say they don't support SELECT_CC on every type the DAG knows
4306     // about, since there is no way to mark an opcode illegal at all value types
4307     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4308         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4309       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4310                          N0.getOperand(0), N0.getOperand(1),
4311                          N1, N2, N0.getOperand(2));
4312     return SimplifySelect(SDLoc(N), N0, N1, N2);
4313   }
4314
4315   return SDValue();
4316 }
4317
4318 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4319   SDValue N0 = N->getOperand(0);
4320   SDValue N1 = N->getOperand(1);
4321   SDValue N2 = N->getOperand(2);
4322   SDLoc DL(N);
4323
4324   // Canonicalize integer abs.
4325   // vselect (setg[te] X,  0),  X, -X ->
4326   // vselect (setgt    X, -1),  X, -X ->
4327   // vselect (setl[te] X,  0), -X,  X ->
4328   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4329   if (N0.getOpcode() == ISD::SETCC) {
4330     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4331     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4332     bool isAbs = false;
4333     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4334
4335     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4336          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4337         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4338       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4339     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4340              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4341       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4342
4343     if (isAbs) {
4344       EVT VT = LHS.getValueType();
4345       SDValue Shift = DAG.getNode(
4346           ISD::SRA, DL, VT, LHS,
4347           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4348       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4349       AddToWorkList(Shift.getNode());
4350       AddToWorkList(Add.getNode());
4351       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4352     }
4353   }
4354
4355   return SDValue();
4356 }
4357
4358 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4359   SDValue N0 = N->getOperand(0);
4360   SDValue N1 = N->getOperand(1);
4361   SDValue N2 = N->getOperand(2);
4362   SDValue N3 = N->getOperand(3);
4363   SDValue N4 = N->getOperand(4);
4364   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4365
4366   // fold select_cc lhs, rhs, x, x, cc -> x
4367   if (N2 == N3)
4368     return N2;
4369
4370   // Determine if the condition we're dealing with is constant
4371   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4372                               N0, N1, CC, SDLoc(N), false);
4373   if (SCC.getNode()) {
4374     AddToWorkList(SCC.getNode());
4375
4376     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4377       if (!SCCC->isNullValue())
4378         return N2;    // cond always true -> true val
4379       else
4380         return N3;    // cond always false -> false val
4381     }
4382
4383     // Fold to a simpler select_cc
4384     if (SCC.getOpcode() == ISD::SETCC)
4385       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4386                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4387                          SCC.getOperand(2));
4388   }
4389
4390   // If we can fold this based on the true/false value, do so.
4391   if (SimplifySelectOps(N, N2, N3))
4392     return SDValue(N, 0);  // Don't revisit N.
4393
4394   // fold select_cc into other things, such as min/max/abs
4395   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4396 }
4397
4398 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4399   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4400                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4401                        SDLoc(N));
4402 }
4403
4404 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4405 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4406 // transformation. Returns true if extension are possible and the above
4407 // mentioned transformation is profitable.
4408 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4409                                     unsigned ExtOpc,
4410                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4411                                     const TargetLowering &TLI) {
4412   bool HasCopyToRegUses = false;
4413   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4414   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4415                             UE = N0.getNode()->use_end();
4416        UI != UE; ++UI) {
4417     SDNode *User = *UI;
4418     if (User == N)
4419       continue;
4420     if (UI.getUse().getResNo() != N0.getResNo())
4421       continue;
4422     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4423     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4424       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4425       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4426         // Sign bits will be lost after a zext.
4427         return false;
4428       bool Add = false;
4429       for (unsigned i = 0; i != 2; ++i) {
4430         SDValue UseOp = User->getOperand(i);
4431         if (UseOp == N0)
4432           continue;
4433         if (!isa<ConstantSDNode>(UseOp))
4434           return false;
4435         Add = true;
4436       }
4437       if (Add)
4438         ExtendNodes.push_back(User);
4439       continue;
4440     }
4441     // If truncates aren't free and there are users we can't
4442     // extend, it isn't worthwhile.
4443     if (!isTruncFree)
4444       return false;
4445     // Remember if this value is live-out.
4446     if (User->getOpcode() == ISD::CopyToReg)
4447       HasCopyToRegUses = true;
4448   }
4449
4450   if (HasCopyToRegUses) {
4451     bool BothLiveOut = false;
4452     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4453          UI != UE; ++UI) {
4454       SDUse &Use = UI.getUse();
4455       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4456         BothLiveOut = true;
4457         break;
4458       }
4459     }
4460     if (BothLiveOut)
4461       // Both unextended and extended values are live out. There had better be
4462       // a good reason for the transformation.
4463       return ExtendNodes.size();
4464   }
4465   return true;
4466 }
4467
4468 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4469                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4470                                   ISD::NodeType ExtType) {
4471   // Extend SetCC uses if necessary.
4472   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4473     SDNode *SetCC = SetCCs[i];
4474     SmallVector<SDValue, 4> Ops;
4475
4476     for (unsigned j = 0; j != 2; ++j) {
4477       SDValue SOp = SetCC->getOperand(j);
4478       if (SOp == Trunc)
4479         Ops.push_back(ExtLoad);
4480       else
4481         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4482     }
4483
4484     Ops.push_back(SetCC->getOperand(2));
4485     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4486                                  &Ops[0], Ops.size()));
4487   }
4488 }
4489
4490 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4491   SDValue N0 = N->getOperand(0);
4492   EVT VT = N->getValueType(0);
4493
4494   // fold (sext c1) -> c1
4495   if (isa<ConstantSDNode>(N0))
4496     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4497
4498   // fold (sext (sext x)) -> (sext x)
4499   // fold (sext (aext x)) -> (sext x)
4500   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4501     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4502                        N0.getOperand(0));
4503
4504   if (N0.getOpcode() == ISD::TRUNCATE) {
4505     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4506     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4507     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4508     if (NarrowLoad.getNode()) {
4509       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4510       if (NarrowLoad.getNode() != N0.getNode()) {
4511         CombineTo(N0.getNode(), NarrowLoad);
4512         // CombineTo deleted the truncate, if needed, but not what's under it.
4513         AddToWorkList(oye);
4514       }
4515       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4516     }
4517
4518     // See if the value being truncated is already sign extended.  If so, just
4519     // eliminate the trunc/sext pair.
4520     SDValue Op = N0.getOperand(0);
4521     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4522     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4523     unsigned DestBits = VT.getScalarType().getSizeInBits();
4524     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4525
4526     if (OpBits == DestBits) {
4527       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4528       // bits, it is already ready.
4529       if (NumSignBits > DestBits-MidBits)
4530         return Op;
4531     } else if (OpBits < DestBits) {
4532       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4533       // bits, just sext from i32.
4534       if (NumSignBits > OpBits-MidBits)
4535         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4536     } else {
4537       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4538       // bits, just truncate to i32.
4539       if (NumSignBits > OpBits-MidBits)
4540         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4541     }
4542
4543     // fold (sext (truncate x)) -> (sextinreg x).
4544     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4545                                                  N0.getValueType())) {
4546       if (OpBits < DestBits)
4547         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4548       else if (OpBits > DestBits)
4549         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4550       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4551                          DAG.getValueType(N0.getValueType()));
4552     }
4553   }
4554
4555   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4556   // None of the supported targets knows how to perform load and sign extend
4557   // on vectors in one instruction.  We only perform this transformation on
4558   // scalars.
4559   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4560       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4561        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4562     bool DoXform = true;
4563     SmallVector<SDNode*, 4> SetCCs;
4564     if (!N0.hasOneUse())
4565       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4566     if (DoXform) {
4567       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4568       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4569                                        LN0->getChain(),
4570                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4571                                        N0.getValueType(),
4572                                        LN0->isVolatile(), LN0->isNonTemporal(),
4573                                        LN0->getAlignment());
4574       CombineTo(N, ExtLoad);
4575       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4576                                   N0.getValueType(), ExtLoad);
4577       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4578       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4579                       ISD::SIGN_EXTEND);
4580       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4581     }
4582   }
4583
4584   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4585   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4586   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4587       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4588     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4589     EVT MemVT = LN0->getMemoryVT();
4590     if ((!LegalOperations && !LN0->isVolatile()) ||
4591         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4592       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4593                                        LN0->getChain(),
4594                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4595                                        MemVT,
4596                                        LN0->isVolatile(), LN0->isNonTemporal(),
4597                                        LN0->getAlignment());
4598       CombineTo(N, ExtLoad);
4599       CombineTo(N0.getNode(),
4600                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4601                             N0.getValueType(), ExtLoad),
4602                 ExtLoad.getValue(1));
4603       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4604     }
4605   }
4606
4607   // fold (sext (and/or/xor (load x), cst)) ->
4608   //      (and/or/xor (sextload x), (sext cst))
4609   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4610        N0.getOpcode() == ISD::XOR) &&
4611       isa<LoadSDNode>(N0.getOperand(0)) &&
4612       N0.getOperand(1).getOpcode() == ISD::Constant &&
4613       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4614       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4615     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4616     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4617       bool DoXform = true;
4618       SmallVector<SDNode*, 4> SetCCs;
4619       if (!N0.hasOneUse())
4620         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4621                                           SetCCs, TLI);
4622       if (DoXform) {
4623         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4624                                          LN0->getChain(), LN0->getBasePtr(),
4625                                          LN0->getPointerInfo(),
4626                                          LN0->getMemoryVT(),
4627                                          LN0->isVolatile(),
4628                                          LN0->isNonTemporal(),
4629                                          LN0->getAlignment());
4630         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4631         Mask = Mask.sext(VT.getSizeInBits());
4632         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4633                                   ExtLoad, DAG.getConstant(Mask, VT));
4634         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4635                                     SDLoc(N0.getOperand(0)),
4636                                     N0.getOperand(0).getValueType(), ExtLoad);
4637         CombineTo(N, And);
4638         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4639         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4640                         ISD::SIGN_EXTEND);
4641         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4642       }
4643     }
4644   }
4645
4646   if (N0.getOpcode() == ISD::SETCC) {
4647     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4648     // Only do this before legalize for now.
4649     if (VT.isVector() && !LegalOperations &&
4650         TLI.getBooleanContents(true) ==
4651           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4652       EVT N0VT = N0.getOperand(0).getValueType();
4653       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4654       // of the same size as the compared operands. Only optimize sext(setcc())
4655       // if this is the case.
4656       EVT SVT = getSetCCResultType(N0VT);
4657
4658       // We know that the # elements of the results is the same as the
4659       // # elements of the compare (and the # elements of the compare result
4660       // for that matter).  Check to see that they are the same size.  If so,
4661       // we know that the element size of the sext'd result matches the
4662       // element size of the compare operands.
4663       if (VT.getSizeInBits() == SVT.getSizeInBits())
4664         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4665                              N0.getOperand(1),
4666                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4667
4668       // If the desired elements are smaller or larger than the source
4669       // elements we can use a matching integer vector type and then
4670       // truncate/sign extend
4671       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4672       if (SVT == MatchingVectorType) {
4673         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4674                                N0.getOperand(0), N0.getOperand(1),
4675                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4676         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4677       }
4678     }
4679
4680     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4681     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4682     SDValue NegOne =
4683       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4684     SDValue SCC =
4685       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4686                        NegOne, DAG.getConstant(0, VT),
4687                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4688     if (SCC.getNode()) return SCC;
4689     if (!VT.isVector() &&
4690         (!LegalOperations ||
4691          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4692       return DAG.getSelect(SDLoc(N), VT,
4693                            DAG.getSetCC(SDLoc(N),
4694                                         getSetCCResultType(VT),
4695                                         N0.getOperand(0), N0.getOperand(1),
4696                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4697                            NegOne, DAG.getConstant(0, VT));
4698     }
4699   }
4700
4701   // fold (sext x) -> (zext x) if the sign bit is known zero.
4702   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4703       DAG.SignBitIsZero(N0))
4704     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4705
4706   return SDValue();
4707 }
4708
4709 // isTruncateOf - If N is a truncate of some other value, return true, record
4710 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4711 // This function computes KnownZero to avoid a duplicated call to
4712 // ComputeMaskedBits in the caller.
4713 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4714                          APInt &KnownZero) {
4715   APInt KnownOne;
4716   if (N->getOpcode() == ISD::TRUNCATE) {
4717     Op = N->getOperand(0);
4718     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4719     return true;
4720   }
4721
4722   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4723       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4724     return false;
4725
4726   SDValue Op0 = N->getOperand(0);
4727   SDValue Op1 = N->getOperand(1);
4728   assert(Op0.getValueType() == Op1.getValueType());
4729
4730   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4731   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4732   if (COp0 && COp0->isNullValue())
4733     Op = Op1;
4734   else if (COp1 && COp1->isNullValue())
4735     Op = Op0;
4736   else
4737     return false;
4738
4739   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4740
4741   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4742     return false;
4743
4744   return true;
4745 }
4746
4747 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4748   SDValue N0 = N->getOperand(0);
4749   EVT VT = N->getValueType(0);
4750
4751   // fold (zext c1) -> c1
4752   if (isa<ConstantSDNode>(N0))
4753     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4754   // fold (zext (zext x)) -> (zext x)
4755   // fold (zext (aext x)) -> (zext x)
4756   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4757     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4758                        N0.getOperand(0));
4759
4760   // fold (zext (truncate x)) -> (zext x) or
4761   //      (zext (truncate x)) -> (truncate x)
4762   // This is valid when the truncated bits of x are already zero.
4763   // FIXME: We should extend this to work for vectors too.
4764   SDValue Op;
4765   APInt KnownZero;
4766   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4767     APInt TruncatedBits =
4768       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4769       APInt(Op.getValueSizeInBits(), 0) :
4770       APInt::getBitsSet(Op.getValueSizeInBits(),
4771                         N0.getValueSizeInBits(),
4772                         std::min(Op.getValueSizeInBits(),
4773                                  VT.getSizeInBits()));
4774     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4775       if (VT.bitsGT(Op.getValueType()))
4776         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4777       if (VT.bitsLT(Op.getValueType()))
4778         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4779
4780       return Op;
4781     }
4782   }
4783
4784   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4785   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4786   if (N0.getOpcode() == ISD::TRUNCATE) {
4787     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4788     if (NarrowLoad.getNode()) {
4789       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4790       if (NarrowLoad.getNode() != N0.getNode()) {
4791         CombineTo(N0.getNode(), NarrowLoad);
4792         // CombineTo deleted the truncate, if needed, but not what's under it.
4793         AddToWorkList(oye);
4794       }
4795       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4796     }
4797   }
4798
4799   // fold (zext (truncate x)) -> (and x, mask)
4800   if (N0.getOpcode() == ISD::TRUNCATE &&
4801       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4802
4803     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4804     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4805     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4806     if (NarrowLoad.getNode()) {
4807       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4808       if (NarrowLoad.getNode() != N0.getNode()) {
4809         CombineTo(N0.getNode(), NarrowLoad);
4810         // CombineTo deleted the truncate, if needed, but not what's under it.
4811         AddToWorkList(oye);
4812       }
4813       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4814     }
4815
4816     SDValue Op = N0.getOperand(0);
4817     if (Op.getValueType().bitsLT(VT)) {
4818       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4819       AddToWorkList(Op.getNode());
4820     } else if (Op.getValueType().bitsGT(VT)) {
4821       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4822       AddToWorkList(Op.getNode());
4823     }
4824     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4825                                   N0.getValueType().getScalarType());
4826   }
4827
4828   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4829   // if either of the casts is not free.
4830   if (N0.getOpcode() == ISD::AND &&
4831       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4832       N0.getOperand(1).getOpcode() == ISD::Constant &&
4833       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4834                            N0.getValueType()) ||
4835        !TLI.isZExtFree(N0.getValueType(), VT))) {
4836     SDValue X = N0.getOperand(0).getOperand(0);
4837     if (X.getValueType().bitsLT(VT)) {
4838       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4839     } else if (X.getValueType().bitsGT(VT)) {
4840       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4841     }
4842     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4843     Mask = Mask.zext(VT.getSizeInBits());
4844     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4845                        X, DAG.getConstant(Mask, VT));
4846   }
4847
4848   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4849   // None of the supported targets knows how to perform load and vector_zext
4850   // on vectors in one instruction.  We only perform this transformation on
4851   // scalars.
4852   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4853       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4854        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4855     bool DoXform = true;
4856     SmallVector<SDNode*, 4> SetCCs;
4857     if (!N0.hasOneUse())
4858       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4859     if (DoXform) {
4860       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4861       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4862                                        LN0->getChain(),
4863                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4864                                        N0.getValueType(),
4865                                        LN0->isVolatile(), LN0->isNonTemporal(),
4866                                        LN0->getAlignment());
4867       CombineTo(N, ExtLoad);
4868       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4869                                   N0.getValueType(), ExtLoad);
4870       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4871
4872       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4873                       ISD::ZERO_EXTEND);
4874       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4875     }
4876   }
4877
4878   // fold (zext (and/or/xor (load x), cst)) ->
4879   //      (and/or/xor (zextload x), (zext cst))
4880   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4881        N0.getOpcode() == ISD::XOR) &&
4882       isa<LoadSDNode>(N0.getOperand(0)) &&
4883       N0.getOperand(1).getOpcode() == ISD::Constant &&
4884       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4885       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4886     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4887     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4888       bool DoXform = true;
4889       SmallVector<SDNode*, 4> SetCCs;
4890       if (!N0.hasOneUse())
4891         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4892                                           SetCCs, TLI);
4893       if (DoXform) {
4894         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4895                                          LN0->getChain(), LN0->getBasePtr(),
4896                                          LN0->getPointerInfo(),
4897                                          LN0->getMemoryVT(),
4898                                          LN0->isVolatile(),
4899                                          LN0->isNonTemporal(),
4900                                          LN0->getAlignment());
4901         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4902         Mask = Mask.zext(VT.getSizeInBits());
4903         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4904                                   ExtLoad, DAG.getConstant(Mask, VT));
4905         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4906                                     SDLoc(N0.getOperand(0)),
4907                                     N0.getOperand(0).getValueType(), ExtLoad);
4908         CombineTo(N, And);
4909         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4910         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4911                         ISD::ZERO_EXTEND);
4912         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4913       }
4914     }
4915   }
4916
4917   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4918   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4919   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4920       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4921     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4922     EVT MemVT = LN0->getMemoryVT();
4923     if ((!LegalOperations && !LN0->isVolatile()) ||
4924         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4925       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4926                                        LN0->getChain(),
4927                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4928                                        MemVT,
4929                                        LN0->isVolatile(), LN0->isNonTemporal(),
4930                                        LN0->getAlignment());
4931       CombineTo(N, ExtLoad);
4932       CombineTo(N0.getNode(),
4933                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4934                             ExtLoad),
4935                 ExtLoad.getValue(1));
4936       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4937     }
4938   }
4939
4940   if (N0.getOpcode() == ISD::SETCC) {
4941     if (!LegalOperations && VT.isVector()) {
4942       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4943       // Only do this before legalize for now.
4944       EVT N0VT = N0.getOperand(0).getValueType();
4945       EVT EltVT = VT.getVectorElementType();
4946       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4947                                     DAG.getConstant(1, EltVT));
4948       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4949         // We know that the # elements of the results is the same as the
4950         // # elements of the compare (and the # elements of the compare result
4951         // for that matter).  Check to see that they are the same size.  If so,
4952         // we know that the element size of the sext'd result matches the
4953         // element size of the compare operands.
4954         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4955                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4956                                          N0.getOperand(1),
4957                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4958                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4959                                        &OneOps[0], OneOps.size()));
4960
4961       // If the desired elements are smaller or larger than the source
4962       // elements we can use a matching integer vector type and then
4963       // truncate/sign extend
4964       EVT MatchingElementType =
4965         EVT::getIntegerVT(*DAG.getContext(),
4966                           N0VT.getScalarType().getSizeInBits());
4967       EVT MatchingVectorType =
4968         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4969                          N0VT.getVectorNumElements());
4970       SDValue VsetCC =
4971         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4972                       N0.getOperand(1),
4973                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4974       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4975                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4976                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4977                                      &OneOps[0], OneOps.size()));
4978     }
4979
4980     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4981     SDValue SCC =
4982       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4983                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4984                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4985     if (SCC.getNode()) return SCC;
4986   }
4987
4988   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4989   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4990       isa<ConstantSDNode>(N0.getOperand(1)) &&
4991       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4992       N0.hasOneUse()) {
4993     SDValue ShAmt = N0.getOperand(1);
4994     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4995     if (N0.getOpcode() == ISD::SHL) {
4996       SDValue InnerZExt = N0.getOperand(0);
4997       // If the original shl may be shifting out bits, do not perform this
4998       // transformation.
4999       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5000         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5001       if (ShAmtVal > KnownZeroBits)
5002         return SDValue();
5003     }
5004
5005     SDLoc DL(N);
5006
5007     // Ensure that the shift amount is wide enough for the shifted value.
5008     if (VT.getSizeInBits() >= 256)
5009       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5010
5011     return DAG.getNode(N0.getOpcode(), DL, VT,
5012                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5013                        ShAmt);
5014   }
5015
5016   return SDValue();
5017 }
5018
5019 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5020   SDValue N0 = N->getOperand(0);
5021   EVT VT = N->getValueType(0);
5022
5023   // fold (aext c1) -> c1
5024   if (isa<ConstantSDNode>(N0))
5025     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5026   // fold (aext (aext x)) -> (aext x)
5027   // fold (aext (zext x)) -> (zext x)
5028   // fold (aext (sext x)) -> (sext x)
5029   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5030       N0.getOpcode() == ISD::ZERO_EXTEND ||
5031       N0.getOpcode() == ISD::SIGN_EXTEND)
5032     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5033
5034   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5035   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5036   if (N0.getOpcode() == ISD::TRUNCATE) {
5037     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5038     if (NarrowLoad.getNode()) {
5039       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5040       if (NarrowLoad.getNode() != N0.getNode()) {
5041         CombineTo(N0.getNode(), NarrowLoad);
5042         // CombineTo deleted the truncate, if needed, but not what's under it.
5043         AddToWorkList(oye);
5044       }
5045       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5046     }
5047   }
5048
5049   // fold (aext (truncate x))
5050   if (N0.getOpcode() == ISD::TRUNCATE) {
5051     SDValue TruncOp = N0.getOperand(0);
5052     if (TruncOp.getValueType() == VT)
5053       return TruncOp; // x iff x size == zext size.
5054     if (TruncOp.getValueType().bitsGT(VT))
5055       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5056     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5057   }
5058
5059   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5060   // if the trunc is not free.
5061   if (N0.getOpcode() == ISD::AND &&
5062       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5063       N0.getOperand(1).getOpcode() == ISD::Constant &&
5064       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5065                           N0.getValueType())) {
5066     SDValue X = N0.getOperand(0).getOperand(0);
5067     if (X.getValueType().bitsLT(VT)) {
5068       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5069     } else if (X.getValueType().bitsGT(VT)) {
5070       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5071     }
5072     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5073     Mask = Mask.zext(VT.getSizeInBits());
5074     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5075                        X, DAG.getConstant(Mask, VT));
5076   }
5077
5078   // fold (aext (load x)) -> (aext (truncate (extload x)))
5079   // None of the supported targets knows how to perform load and any_ext
5080   // on vectors in one instruction.  We only perform this transformation on
5081   // scalars.
5082   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5083       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5084        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5085     bool DoXform = true;
5086     SmallVector<SDNode*, 4> SetCCs;
5087     if (!N0.hasOneUse())
5088       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5089     if (DoXform) {
5090       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5091       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5092                                        LN0->getChain(),
5093                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5094                                        N0.getValueType(),
5095                                        LN0->isVolatile(), LN0->isNonTemporal(),
5096                                        LN0->getAlignment());
5097       CombineTo(N, ExtLoad);
5098       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5099                                   N0.getValueType(), ExtLoad);
5100       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5101       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5102                       ISD::ANY_EXTEND);
5103       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5104     }
5105   }
5106
5107   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5108   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5109   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5110   if (N0.getOpcode() == ISD::LOAD &&
5111       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5112       N0.hasOneUse()) {
5113     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5114     EVT MemVT = LN0->getMemoryVT();
5115     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5116                                      VT, LN0->getChain(), LN0->getBasePtr(),
5117                                      LN0->getPointerInfo(), MemVT,
5118                                      LN0->isVolatile(), LN0->isNonTemporal(),
5119                                      LN0->getAlignment());
5120     CombineTo(N, ExtLoad);
5121     CombineTo(N0.getNode(),
5122               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5123                           N0.getValueType(), ExtLoad),
5124               ExtLoad.getValue(1));
5125     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5126   }
5127
5128   if (N0.getOpcode() == ISD::SETCC) {
5129     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5130     // Only do this before legalize for now.
5131     if (VT.isVector() && !LegalOperations) {
5132       EVT N0VT = N0.getOperand(0).getValueType();
5133         // We know that the # elements of the results is the same as the
5134         // # elements of the compare (and the # elements of the compare result
5135         // for that matter).  Check to see that they are the same size.  If so,
5136         // we know that the element size of the sext'd result matches the
5137         // element size of the compare operands.
5138       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5139         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5140                              N0.getOperand(1),
5141                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5142       // If the desired elements are smaller or larger than the source
5143       // elements we can use a matching integer vector type and then
5144       // truncate/sign extend
5145       else {
5146         EVT MatchingElementType =
5147           EVT::getIntegerVT(*DAG.getContext(),
5148                             N0VT.getScalarType().getSizeInBits());
5149         EVT MatchingVectorType =
5150           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5151                            N0VT.getVectorNumElements());
5152         SDValue VsetCC =
5153           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5154                         N0.getOperand(1),
5155                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5156         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5157       }
5158     }
5159
5160     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5161     SDValue SCC =
5162       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5163                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5164                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5165     if (SCC.getNode())
5166       return SCC;
5167   }
5168
5169   return SDValue();
5170 }
5171
5172 /// GetDemandedBits - See if the specified operand can be simplified with the
5173 /// knowledge that only the bits specified by Mask are used.  If so, return the
5174 /// simpler operand, otherwise return a null SDValue.
5175 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5176   switch (V.getOpcode()) {
5177   default: break;
5178   case ISD::Constant: {
5179     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5180     assert(CV != 0 && "Const value should be ConstSDNode.");
5181     const APInt &CVal = CV->getAPIntValue();
5182     APInt NewVal = CVal & Mask;
5183     if (NewVal != CVal)
5184       return DAG.getConstant(NewVal, V.getValueType());
5185     break;
5186   }
5187   case ISD::OR:
5188   case ISD::XOR:
5189     // If the LHS or RHS don't contribute bits to the or, drop them.
5190     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5191       return V.getOperand(1);
5192     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5193       return V.getOperand(0);
5194     break;
5195   case ISD::SRL:
5196     // Only look at single-use SRLs.
5197     if (!V.getNode()->hasOneUse())
5198       break;
5199     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5200       // See if we can recursively simplify the LHS.
5201       unsigned Amt = RHSC->getZExtValue();
5202
5203       // Watch out for shift count overflow though.
5204       if (Amt >= Mask.getBitWidth()) break;
5205       APInt NewMask = Mask << Amt;
5206       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5207       if (SimplifyLHS.getNode())
5208         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5209                            SimplifyLHS, V.getOperand(1));
5210     }
5211   }
5212   return SDValue();
5213 }
5214
5215 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5216 /// bits and then truncated to a narrower type and where N is a multiple
5217 /// of number of bits of the narrower type, transform it to a narrower load
5218 /// from address + N / num of bits of new type. If the result is to be
5219 /// extended, also fold the extension to form a extending load.
5220 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5221   unsigned Opc = N->getOpcode();
5222
5223   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5224   SDValue N0 = N->getOperand(0);
5225   EVT VT = N->getValueType(0);
5226   EVT ExtVT = VT;
5227
5228   // This transformation isn't valid for vector loads.
5229   if (VT.isVector())
5230     return SDValue();
5231
5232   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5233   // extended to VT.
5234   if (Opc == ISD::SIGN_EXTEND_INREG) {
5235     ExtType = ISD::SEXTLOAD;
5236     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5237   } else if (Opc == ISD::SRL) {
5238     // Another special-case: SRL is basically zero-extending a narrower value.
5239     ExtType = ISD::ZEXTLOAD;
5240     N0 = SDValue(N, 0);
5241     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5242     if (!N01) return SDValue();
5243     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5244                               VT.getSizeInBits() - N01->getZExtValue());
5245   }
5246   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5247     return SDValue();
5248
5249   unsigned EVTBits = ExtVT.getSizeInBits();
5250
5251   // Do not generate loads of non-round integer types since these can
5252   // be expensive (and would be wrong if the type is not byte sized).
5253   if (!ExtVT.isRound())
5254     return SDValue();
5255
5256   unsigned ShAmt = 0;
5257   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5258     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5259       ShAmt = N01->getZExtValue();
5260       // Is the shift amount a multiple of size of VT?
5261       if ((ShAmt & (EVTBits-1)) == 0) {
5262         N0 = N0.getOperand(0);
5263         // Is the load width a multiple of size of VT?
5264         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5265           return SDValue();
5266       }
5267
5268       // At this point, we must have a load or else we can't do the transform.
5269       if (!isa<LoadSDNode>(N0)) return SDValue();
5270
5271       // Because a SRL must be assumed to *need* to zero-extend the high bits
5272       // (as opposed to anyext the high bits), we can't combine the zextload
5273       // lowering of SRL and an sextload.
5274       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5275         return SDValue();
5276
5277       // If the shift amount is larger than the input type then we're not
5278       // accessing any of the loaded bytes.  If the load was a zextload/extload
5279       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5280       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5281         return SDValue();
5282     }
5283   }
5284
5285   // If the load is shifted left (and the result isn't shifted back right),
5286   // we can fold the truncate through the shift.
5287   unsigned ShLeftAmt = 0;
5288   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5289       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5290     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5291       ShLeftAmt = N01->getZExtValue();
5292       N0 = N0.getOperand(0);
5293     }
5294   }
5295
5296   // If we haven't found a load, we can't narrow it.  Don't transform one with
5297   // multiple uses, this would require adding a new load.
5298   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5299     return SDValue();
5300
5301   // Don't change the width of a volatile load.
5302   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5303   if (LN0->isVolatile())
5304     return SDValue();
5305
5306   // Verify that we are actually reducing a load width here.
5307   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5308     return SDValue();
5309
5310   // For the transform to be legal, the load must produce only two values
5311   // (the value loaded and the chain).  Don't transform a pre-increment
5312   // load, for example, which produces an extra value.  Otherwise the
5313   // transformation is not equivalent, and the downstream logic to replace
5314   // uses gets things wrong.
5315   if (LN0->getNumValues() > 2)
5316     return SDValue();
5317
5318   // If the load that we're shrinking is an extload and we're not just
5319   // discarding the extension we can't simply shrink the load. Bail.
5320   // TODO: It would be possible to merge the extensions in some cases.
5321   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5322       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5323     return SDValue();
5324
5325   EVT PtrType = N0.getOperand(1).getValueType();
5326
5327   if (PtrType == MVT::Untyped || PtrType.isExtended())
5328     // It's not possible to generate a constant of extended or untyped type.
5329     return SDValue();
5330
5331   // For big endian targets, we need to adjust the offset to the pointer to
5332   // load the correct bytes.
5333   if (TLI.isBigEndian()) {
5334     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5335     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5336     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5337   }
5338
5339   uint64_t PtrOff = ShAmt / 8;
5340   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5341   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5342                                PtrType, LN0->getBasePtr(),
5343                                DAG.getConstant(PtrOff, PtrType));
5344   AddToWorkList(NewPtr.getNode());
5345
5346   SDValue Load;
5347   if (ExtType == ISD::NON_EXTLOAD)
5348     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5349                         LN0->getPointerInfo().getWithOffset(PtrOff),
5350                         LN0->isVolatile(), LN0->isNonTemporal(),
5351                         LN0->isInvariant(), NewAlign);
5352   else
5353     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5354                           LN0->getPointerInfo().getWithOffset(PtrOff),
5355                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5356                           NewAlign);
5357
5358   // Replace the old load's chain with the new load's chain.
5359   WorkListRemover DeadNodes(*this);
5360   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5361
5362   // Shift the result left, if we've swallowed a left shift.
5363   SDValue Result = Load;
5364   if (ShLeftAmt != 0) {
5365     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5366     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5367       ShImmTy = VT;
5368     // If the shift amount is as large as the result size (but, presumably,
5369     // no larger than the source) then the useful bits of the result are
5370     // zero; we can't simply return the shortened shift, because the result
5371     // of that operation is undefined.
5372     if (ShLeftAmt >= VT.getSizeInBits())
5373       Result = DAG.getConstant(0, VT);
5374     else
5375       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5376                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5377   }
5378
5379   // Return the new loaded value.
5380   return Result;
5381 }
5382
5383 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5384   SDValue N0 = N->getOperand(0);
5385   SDValue N1 = N->getOperand(1);
5386   EVT VT = N->getValueType(0);
5387   EVT EVT = cast<VTSDNode>(N1)->getVT();
5388   unsigned VTBits = VT.getScalarType().getSizeInBits();
5389   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5390
5391   // fold (sext_in_reg c1) -> c1
5392   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5393     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5394
5395   // If the input is already sign extended, just drop the extension.
5396   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5397     return N0;
5398
5399   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5400   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5401       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5402     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5403                        N0.getOperand(0), N1);
5404
5405   // fold (sext_in_reg (sext x)) -> (sext x)
5406   // fold (sext_in_reg (aext x)) -> (sext x)
5407   // if x is small enough.
5408   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5409     SDValue N00 = N0.getOperand(0);
5410     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5411         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5412       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5413   }
5414
5415   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5416   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5417     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5418
5419   // fold operands of sext_in_reg based on knowledge that the top bits are not
5420   // demanded.
5421   if (SimplifyDemandedBits(SDValue(N, 0)))
5422     return SDValue(N, 0);
5423
5424   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5425   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5426   SDValue NarrowLoad = ReduceLoadWidth(N);
5427   if (NarrowLoad.getNode())
5428     return NarrowLoad;
5429
5430   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5431   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5432   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5433   if (N0.getOpcode() == ISD::SRL) {
5434     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5435       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5436         // We can turn this into an SRA iff the input to the SRL is already sign
5437         // extended enough.
5438         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5439         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5440           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5441                              N0.getOperand(0), N0.getOperand(1));
5442       }
5443   }
5444
5445   // fold (sext_inreg (extload x)) -> (sextload x)
5446   if (ISD::isEXTLoad(N0.getNode()) &&
5447       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5448       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5449       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5450        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5451     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5452     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5453                                      LN0->getChain(),
5454                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5455                                      EVT,
5456                                      LN0->isVolatile(), LN0->isNonTemporal(),
5457                                      LN0->getAlignment());
5458     CombineTo(N, ExtLoad);
5459     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5460     AddToWorkList(ExtLoad.getNode());
5461     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5462   }
5463   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5464   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5465       N0.hasOneUse() &&
5466       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5467       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5468        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5469     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5470     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5471                                      LN0->getChain(),
5472                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5473                                      EVT,
5474                                      LN0->isVolatile(), LN0->isNonTemporal(),
5475                                      LN0->getAlignment());
5476     CombineTo(N, ExtLoad);
5477     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5478     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5479   }
5480
5481   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5482   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5483     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5484                                        N0.getOperand(1), false);
5485     if (BSwap.getNode() != 0)
5486       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5487                          BSwap, N1);
5488   }
5489
5490   return SDValue();
5491 }
5492
5493 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5494   SDValue N0 = N->getOperand(0);
5495   EVT VT = N->getValueType(0);
5496   bool isLE = TLI.isLittleEndian();
5497
5498   // noop truncate
5499   if (N0.getValueType() == N->getValueType(0))
5500     return N0;
5501   // fold (truncate c1) -> c1
5502   if (isa<ConstantSDNode>(N0))
5503     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5504   // fold (truncate (truncate x)) -> (truncate x)
5505   if (N0.getOpcode() == ISD::TRUNCATE)
5506     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5507   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5508   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5509       N0.getOpcode() == ISD::SIGN_EXTEND ||
5510       N0.getOpcode() == ISD::ANY_EXTEND) {
5511     if (N0.getOperand(0).getValueType().bitsLT(VT))
5512       // if the source is smaller than the dest, we still need an extend
5513       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5514                          N0.getOperand(0));
5515     if (N0.getOperand(0).getValueType().bitsGT(VT))
5516       // if the source is larger than the dest, than we just need the truncate
5517       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5518     // if the source and dest are the same type, we can drop both the extend
5519     // and the truncate.
5520     return N0.getOperand(0);
5521   }
5522
5523   // Fold extract-and-trunc into a narrow extract. For example:
5524   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5525   //   i32 y = TRUNCATE(i64 x)
5526   //        -- becomes --
5527   //   v16i8 b = BITCAST (v2i64 val)
5528   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5529   //
5530   // Note: We only run this optimization after type legalization (which often
5531   // creates this pattern) and before operation legalization after which
5532   // we need to be more careful about the vector instructions that we generate.
5533   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5534       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5535
5536     EVT VecTy = N0.getOperand(0).getValueType();
5537     EVT ExTy = N0.getValueType();
5538     EVT TrTy = N->getValueType(0);
5539
5540     unsigned NumElem = VecTy.getVectorNumElements();
5541     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5542
5543     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5544     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5545
5546     SDValue EltNo = N0->getOperand(1);
5547     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5548       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5549       EVT IndexTy = TLI.getVectorIdxTy();
5550       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5551
5552       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5553                               NVT, N0.getOperand(0));
5554
5555       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5556                          SDLoc(N), TrTy, V,
5557                          DAG.getConstant(Index, IndexTy));
5558     }
5559   }
5560
5561   // Fold a series of buildvector, bitcast, and truncate if possible.
5562   // For example fold
5563   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5564   //   (2xi32 (buildvector x, y)).
5565   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5566       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5567       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5568       N0.getOperand(0).hasOneUse()) {
5569
5570     SDValue BuildVect = N0.getOperand(0);
5571     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5572     EVT TruncVecEltTy = VT.getVectorElementType();
5573
5574     // Check that the element types match.
5575     if (BuildVectEltTy == TruncVecEltTy) {
5576       // Now we only need to compute the offset of the truncated elements.
5577       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5578       unsigned TruncVecNumElts = VT.getVectorNumElements();
5579       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5580
5581       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5582              "Invalid number of elements");
5583
5584       SmallVector<SDValue, 8> Opnds;
5585       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5586         Opnds.push_back(BuildVect.getOperand(i));
5587
5588       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5589                          Opnds.size());
5590     }
5591   }
5592
5593   // See if we can simplify the input to this truncate through knowledge that
5594   // only the low bits are being used.
5595   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5596   // Currently we only perform this optimization on scalars because vectors
5597   // may have different active low bits.
5598   if (!VT.isVector()) {
5599     SDValue Shorter =
5600       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5601                                                VT.getSizeInBits()));
5602     if (Shorter.getNode())
5603       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5604   }
5605   // fold (truncate (load x)) -> (smaller load x)
5606   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5607   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5608     SDValue Reduced = ReduceLoadWidth(N);
5609     if (Reduced.getNode())
5610       return Reduced;
5611   }
5612   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5613   // where ... are all 'undef'.
5614   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5615     SmallVector<EVT, 8> VTs;
5616     SDValue V;
5617     unsigned Idx = 0;
5618     unsigned NumDefs = 0;
5619
5620     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5621       SDValue X = N0.getOperand(i);
5622       if (X.getOpcode() != ISD::UNDEF) {
5623         V = X;
5624         Idx = i;
5625         NumDefs++;
5626       }
5627       // Stop if more than one members are non-undef.
5628       if (NumDefs > 1)
5629         break;
5630       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5631                                      VT.getVectorElementType(),
5632                                      X.getValueType().getVectorNumElements()));
5633     }
5634
5635     if (NumDefs == 0)
5636       return DAG.getUNDEF(VT);
5637
5638     if (NumDefs == 1) {
5639       assert(V.getNode() && "The single defined operand is empty!");
5640       SmallVector<SDValue, 8> Opnds;
5641       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5642         if (i != Idx) {
5643           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5644           continue;
5645         }
5646         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5647         AddToWorkList(NV.getNode());
5648         Opnds.push_back(NV);
5649       }
5650       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5651                          &Opnds[0], Opnds.size());
5652     }
5653   }
5654
5655   // Simplify the operands using demanded-bits information.
5656   if (!VT.isVector() &&
5657       SimplifyDemandedBits(SDValue(N, 0)))
5658     return SDValue(N, 0);
5659
5660   return SDValue();
5661 }
5662
5663 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5664   SDValue Elt = N->getOperand(i);
5665   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5666     return Elt.getNode();
5667   return Elt.getOperand(Elt.getResNo()).getNode();
5668 }
5669
5670 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5671 /// if load locations are consecutive.
5672 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5673   assert(N->getOpcode() == ISD::BUILD_PAIR);
5674
5675   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5676   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5677   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5678       LD1->getPointerInfo().getAddrSpace() !=
5679          LD2->getPointerInfo().getAddrSpace())
5680     return SDValue();
5681   EVT LD1VT = LD1->getValueType(0);
5682
5683   if (ISD::isNON_EXTLoad(LD2) &&
5684       LD2->hasOneUse() &&
5685       // If both are volatile this would reduce the number of volatile loads.
5686       // If one is volatile it might be ok, but play conservative and bail out.
5687       !LD1->isVolatile() &&
5688       !LD2->isVolatile() &&
5689       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5690     unsigned Align = LD1->getAlignment();
5691     unsigned NewAlign = TLI.getDataLayout()->
5692       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5693
5694     if (NewAlign <= Align &&
5695         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5696       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5697                          LD1->getBasePtr(), LD1->getPointerInfo(),
5698                          false, false, false, Align);
5699   }
5700
5701   return SDValue();
5702 }
5703
5704 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5705   SDValue N0 = N->getOperand(0);
5706   EVT VT = N->getValueType(0);
5707
5708   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5709   // Only do this before legalize, since afterward the target may be depending
5710   // on the bitconvert.
5711   // First check to see if this is all constant.
5712   if (!LegalTypes &&
5713       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5714       VT.isVector()) {
5715     bool isSimple = true;
5716     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5717       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5718           N0.getOperand(i).getOpcode() != ISD::Constant &&
5719           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5720         isSimple = false;
5721         break;
5722       }
5723
5724     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5725     assert(!DestEltVT.isVector() &&
5726            "Element type of vector ValueType must not be vector!");
5727     if (isSimple)
5728       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5729   }
5730
5731   // If the input is a constant, let getNode fold it.
5732   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5733     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5734     if (Res.getNode() != N) {
5735       if (!LegalOperations ||
5736           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5737         return Res;
5738
5739       // Folding it resulted in an illegal node, and it's too late to
5740       // do that. Clean up the old node and forego the transformation.
5741       // Ideally this won't happen very often, because instcombine
5742       // and the earlier dagcombine runs (where illegal nodes are
5743       // permitted) should have folded most of them already.
5744       DAG.DeleteNode(Res.getNode());
5745     }
5746   }
5747
5748   // (conv (conv x, t1), t2) -> (conv x, t2)
5749   if (N0.getOpcode() == ISD::BITCAST)
5750     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5751                        N0.getOperand(0));
5752
5753   // fold (conv (load x)) -> (load (conv*)x)
5754   // If the resultant load doesn't need a higher alignment than the original!
5755   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5756       // Do not change the width of a volatile load.
5757       !cast<LoadSDNode>(N0)->isVolatile() &&
5758       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5759     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5760     unsigned Align = TLI.getDataLayout()->
5761       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5762     unsigned OrigAlign = LN0->getAlignment();
5763
5764     if (Align <= OrigAlign) {
5765       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5766                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5767                                  LN0->isVolatile(), LN0->isNonTemporal(),
5768                                  LN0->isInvariant(), OrigAlign);
5769       AddToWorkList(N);
5770       CombineTo(N0.getNode(),
5771                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5772                             N0.getValueType(), Load),
5773                 Load.getValue(1));
5774       return Load;
5775     }
5776   }
5777
5778   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5779   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5780   // This often reduces constant pool loads.
5781   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5782        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5783       N0.getNode()->hasOneUse() && VT.isInteger() &&
5784       !VT.isVector() && !N0.getValueType().isVector()) {
5785     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5786                                   N0.getOperand(0));
5787     AddToWorkList(NewConv.getNode());
5788
5789     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5790     if (N0.getOpcode() == ISD::FNEG)
5791       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5792                          NewConv, DAG.getConstant(SignBit, VT));
5793     assert(N0.getOpcode() == ISD::FABS);
5794     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5795                        NewConv, DAG.getConstant(~SignBit, VT));
5796   }
5797
5798   // fold (bitconvert (fcopysign cst, x)) ->
5799   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5800   // Note that we don't handle (copysign x, cst) because this can always be
5801   // folded to an fneg or fabs.
5802   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5803       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5804       VT.isInteger() && !VT.isVector()) {
5805     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5806     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5807     if (isTypeLegal(IntXVT)) {
5808       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5809                               IntXVT, N0.getOperand(1));
5810       AddToWorkList(X.getNode());
5811
5812       // If X has a different width than the result/lhs, sext it or truncate it.
5813       unsigned VTWidth = VT.getSizeInBits();
5814       if (OrigXWidth < VTWidth) {
5815         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5816         AddToWorkList(X.getNode());
5817       } else if (OrigXWidth > VTWidth) {
5818         // To get the sign bit in the right place, we have to shift it right
5819         // before truncating.
5820         X = DAG.getNode(ISD::SRL, SDLoc(X),
5821                         X.getValueType(), X,
5822                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5823         AddToWorkList(X.getNode());
5824         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5825         AddToWorkList(X.getNode());
5826       }
5827
5828       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5829       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5830                       X, DAG.getConstant(SignBit, VT));
5831       AddToWorkList(X.getNode());
5832
5833       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5834                                 VT, N0.getOperand(0));
5835       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5836                         Cst, DAG.getConstant(~SignBit, VT));
5837       AddToWorkList(Cst.getNode());
5838
5839       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5840     }
5841   }
5842
5843   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5844   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5845     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5846     if (CombineLD.getNode())
5847       return CombineLD;
5848   }
5849
5850   return SDValue();
5851 }
5852
5853 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5854   EVT VT = N->getValueType(0);
5855   return CombineConsecutiveLoads(N, VT);
5856 }
5857
5858 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5859 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5860 /// destination element value type.
5861 SDValue DAGCombiner::
5862 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5863   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5864
5865   // If this is already the right type, we're done.
5866   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5867
5868   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5869   unsigned DstBitSize = DstEltVT.getSizeInBits();
5870
5871   // If this is a conversion of N elements of one type to N elements of another
5872   // type, convert each element.  This handles FP<->INT cases.
5873   if (SrcBitSize == DstBitSize) {
5874     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5875                               BV->getValueType(0).getVectorNumElements());
5876
5877     // Due to the FP element handling below calling this routine recursively,
5878     // we can end up with a scalar-to-vector node here.
5879     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5880       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5881                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5882                                      DstEltVT, BV->getOperand(0)));
5883
5884     SmallVector<SDValue, 8> Ops;
5885     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5886       SDValue Op = BV->getOperand(i);
5887       // If the vector element type is not legal, the BUILD_VECTOR operands
5888       // are promoted and implicitly truncated.  Make that explicit here.
5889       if (Op.getValueType() != SrcEltVT)
5890         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5891       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5892                                 DstEltVT, Op));
5893       AddToWorkList(Ops.back().getNode());
5894     }
5895     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5896                        &Ops[0], Ops.size());
5897   }
5898
5899   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5900   // handle annoying details of growing/shrinking FP values, we convert them to
5901   // int first.
5902   if (SrcEltVT.isFloatingPoint()) {
5903     // Convert the input float vector to a int vector where the elements are the
5904     // same sizes.
5905     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5906     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5907     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5908     SrcEltVT = IntVT;
5909   }
5910
5911   // Now we know the input is an integer vector.  If the output is a FP type,
5912   // convert to integer first, then to FP of the right size.
5913   if (DstEltVT.isFloatingPoint()) {
5914     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5915     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5916     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5917
5918     // Next, convert to FP elements of the same size.
5919     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5920   }
5921
5922   // Okay, we know the src/dst types are both integers of differing types.
5923   // Handling growing first.
5924   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5925   if (SrcBitSize < DstBitSize) {
5926     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5927
5928     SmallVector<SDValue, 8> Ops;
5929     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5930          i += NumInputsPerOutput) {
5931       bool isLE = TLI.isLittleEndian();
5932       APInt NewBits = APInt(DstBitSize, 0);
5933       bool EltIsUndef = true;
5934       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5935         // Shift the previously computed bits over.
5936         NewBits <<= SrcBitSize;
5937         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5938         if (Op.getOpcode() == ISD::UNDEF) continue;
5939         EltIsUndef = false;
5940
5941         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5942                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5943       }
5944
5945       if (EltIsUndef)
5946         Ops.push_back(DAG.getUNDEF(DstEltVT));
5947       else
5948         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5949     }
5950
5951     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5952     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5953                        &Ops[0], Ops.size());
5954   }
5955
5956   // Finally, this must be the case where we are shrinking elements: each input
5957   // turns into multiple outputs.
5958   bool isS2V = ISD::isScalarToVector(BV);
5959   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5960   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5961                             NumOutputsPerInput*BV->getNumOperands());
5962   SmallVector<SDValue, 8> Ops;
5963
5964   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5965     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5966       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5967         Ops.push_back(DAG.getUNDEF(DstEltVT));
5968       continue;
5969     }
5970
5971     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5972                   getAPIntValue().zextOrTrunc(SrcBitSize);
5973
5974     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5975       APInt ThisVal = OpVal.trunc(DstBitSize);
5976       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5977       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5978         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5979         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5980                            Ops[0]);
5981       OpVal = OpVal.lshr(DstBitSize);
5982     }
5983
5984     // For big endian targets, swap the order of the pieces of each element.
5985     if (TLI.isBigEndian())
5986       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5987   }
5988
5989   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5990                      &Ops[0], Ops.size());
5991 }
5992
5993 SDValue DAGCombiner::visitFADD(SDNode *N) {
5994   SDValue N0 = N->getOperand(0);
5995   SDValue N1 = N->getOperand(1);
5996   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5997   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5998   EVT VT = N->getValueType(0);
5999
6000   // fold vector ops
6001   if (VT.isVector()) {
6002     SDValue FoldedVOp = SimplifyVBinOp(N);
6003     if (FoldedVOp.getNode()) return FoldedVOp;
6004   }
6005
6006   // fold (fadd c1, c2) -> c1 + c2
6007   if (N0CFP && N1CFP)
6008     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6009   // canonicalize constant to RHS
6010   if (N0CFP && !N1CFP)
6011     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6012   // fold (fadd A, 0) -> A
6013   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6014       N1CFP->getValueAPF().isZero())
6015     return N0;
6016   // fold (fadd A, (fneg B)) -> (fsub A, B)
6017   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6018     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6019     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6020                        GetNegatedExpression(N1, DAG, LegalOperations));
6021   // fold (fadd (fneg A), B) -> (fsub B, A)
6022   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6023     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6024     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6025                        GetNegatedExpression(N0, DAG, LegalOperations));
6026
6027   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6028   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6029       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6030       isa<ConstantFPSDNode>(N0.getOperand(1)))
6031     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6032                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6033                                    N0.getOperand(1), N1));
6034
6035   // No FP constant should be created after legalization as Instruction
6036   // Selection pass has hard time in dealing with FP constant.
6037   //
6038   // We don't need test this condition for transformation like following, as
6039   // the DAG being transformed implies it is legal to take FP constant as
6040   // operand.
6041   //
6042   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6043   //
6044   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6045
6046   // If allow, fold (fadd (fneg x), x) -> 0.0
6047   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6048       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6049     return DAG.getConstantFP(0.0, VT);
6050
6051     // If allow, fold (fadd x, (fneg x)) -> 0.0
6052   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6053       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6054     return DAG.getConstantFP(0.0, VT);
6055
6056   // In unsafe math mode, we can fold chains of FADD's of the same value
6057   // into multiplications.  This transform is not safe in general because
6058   // we are reducing the number of rounding steps.
6059   if (DAG.getTarget().Options.UnsafeFPMath &&
6060       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6061       !N0CFP && !N1CFP) {
6062     if (N0.getOpcode() == ISD::FMUL) {
6063       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6064       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6065
6066       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6067       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6068         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6069                                      SDValue(CFP00, 0),
6070                                      DAG.getConstantFP(1.0, VT));
6071         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6072                            N1, NewCFP);
6073       }
6074
6075       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6076       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6077         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6078                                      SDValue(CFP01, 0),
6079                                      DAG.getConstantFP(1.0, VT));
6080         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6081                            N1, NewCFP);
6082       }
6083
6084       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6085       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6086           N1.getOperand(0) == N1.getOperand(1) &&
6087           N0.getOperand(1) == N1.getOperand(0)) {
6088         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6089                                      SDValue(CFP00, 0),
6090                                      DAG.getConstantFP(2.0, VT));
6091         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6092                            N0.getOperand(1), NewCFP);
6093       }
6094
6095       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6096       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6097           N1.getOperand(0) == N1.getOperand(1) &&
6098           N0.getOperand(0) == N1.getOperand(0)) {
6099         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6100                                      SDValue(CFP01, 0),
6101                                      DAG.getConstantFP(2.0, VT));
6102         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6103                            N0.getOperand(0), NewCFP);
6104       }
6105     }
6106
6107     if (N1.getOpcode() == ISD::FMUL) {
6108       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6109       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6110
6111       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6112       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6113         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6114                                      SDValue(CFP10, 0),
6115                                      DAG.getConstantFP(1.0, VT));
6116         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6117                            N0, NewCFP);
6118       }
6119
6120       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6121       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6122         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6123                                      SDValue(CFP11, 0),
6124                                      DAG.getConstantFP(1.0, VT));
6125         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6126                            N0, NewCFP);
6127       }
6128
6129
6130       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6131       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6132           N0.getOperand(0) == N0.getOperand(1) &&
6133           N1.getOperand(1) == N0.getOperand(0)) {
6134         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6135                                      SDValue(CFP10, 0),
6136                                      DAG.getConstantFP(2.0, VT));
6137         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6138                            N1.getOperand(1), NewCFP);
6139       }
6140
6141       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6142       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6143           N0.getOperand(0) == N0.getOperand(1) &&
6144           N1.getOperand(0) == N0.getOperand(0)) {
6145         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6146                                      SDValue(CFP11, 0),
6147                                      DAG.getConstantFP(2.0, VT));
6148         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6149                            N1.getOperand(0), NewCFP);
6150       }
6151     }
6152
6153     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6154       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6155       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6156       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6157           (N0.getOperand(0) == N1))
6158         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6159                            N1, DAG.getConstantFP(3.0, VT));
6160     }
6161
6162     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6163       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6164       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6165       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6166           N1.getOperand(0) == N0)
6167         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6168                            N0, DAG.getConstantFP(3.0, VT));
6169     }
6170
6171     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6172     if (AllowNewFpConst &&
6173         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6174         N0.getOperand(0) == N0.getOperand(1) &&
6175         N1.getOperand(0) == N1.getOperand(1) &&
6176         N0.getOperand(0) == N1.getOperand(0))
6177       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6178                          N0.getOperand(0),
6179                          DAG.getConstantFP(4.0, VT));
6180   }
6181
6182   // FADD -> FMA combines:
6183   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6184        DAG.getTarget().Options.UnsafeFPMath) &&
6185       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6186       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6187
6188     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6189     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6190       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6191                          N0.getOperand(0), N0.getOperand(1), N1);
6192
6193     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6194     // Note: Commutes FADD operands.
6195     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6196       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6197                          N1.getOperand(0), N1.getOperand(1), N0);
6198   }
6199
6200   return SDValue();
6201 }
6202
6203 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6204   SDValue N0 = N->getOperand(0);
6205   SDValue N1 = N->getOperand(1);
6206   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6207   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6208   EVT VT = N->getValueType(0);
6209   SDLoc dl(N);
6210
6211   // fold vector ops
6212   if (VT.isVector()) {
6213     SDValue FoldedVOp = SimplifyVBinOp(N);
6214     if (FoldedVOp.getNode()) return FoldedVOp;
6215   }
6216
6217   // fold (fsub c1, c2) -> c1-c2
6218   if (N0CFP && N1CFP)
6219     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6220   // fold (fsub A, 0) -> A
6221   if (DAG.getTarget().Options.UnsafeFPMath &&
6222       N1CFP && N1CFP->getValueAPF().isZero())
6223     return N0;
6224   // fold (fsub 0, B) -> -B
6225   if (DAG.getTarget().Options.UnsafeFPMath &&
6226       N0CFP && N0CFP->getValueAPF().isZero()) {
6227     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6228       return GetNegatedExpression(N1, DAG, LegalOperations);
6229     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6230       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6231   }
6232   // fold (fsub A, (fneg B)) -> (fadd A, B)
6233   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6234     return DAG.getNode(ISD::FADD, dl, VT, N0,
6235                        GetNegatedExpression(N1, DAG, LegalOperations));
6236
6237   // If 'unsafe math' is enabled, fold
6238   //    (fsub x, x) -> 0.0 &
6239   //    (fsub x, (fadd x, y)) -> (fneg y) &
6240   //    (fsub x, (fadd y, x)) -> (fneg y)
6241   if (DAG.getTarget().Options.UnsafeFPMath) {
6242     if (N0 == N1)
6243       return DAG.getConstantFP(0.0f, VT);
6244
6245     if (N1.getOpcode() == ISD::FADD) {
6246       SDValue N10 = N1->getOperand(0);
6247       SDValue N11 = N1->getOperand(1);
6248
6249       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6250                                           &DAG.getTarget().Options))
6251         return GetNegatedExpression(N11, DAG, LegalOperations);
6252
6253       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6254                                           &DAG.getTarget().Options))
6255         return GetNegatedExpression(N10, DAG, LegalOperations);
6256     }
6257   }
6258
6259   // FSUB -> FMA combines:
6260   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6261        DAG.getTarget().Options.UnsafeFPMath) &&
6262       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6263       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6264
6265     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6266     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6267       return DAG.getNode(ISD::FMA, dl, VT,
6268                          N0.getOperand(0), N0.getOperand(1),
6269                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6270
6271     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6272     // Note: Commutes FSUB operands.
6273     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6274       return DAG.getNode(ISD::FMA, dl, VT,
6275                          DAG.getNode(ISD::FNEG, dl, VT,
6276                          N1.getOperand(0)),
6277                          N1.getOperand(1), N0);
6278
6279     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6280     if (N0.getOpcode() == ISD::FNEG &&
6281         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6282         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6283       SDValue N00 = N0.getOperand(0).getOperand(0);
6284       SDValue N01 = N0.getOperand(0).getOperand(1);
6285       return DAG.getNode(ISD::FMA, dl, VT,
6286                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6287                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6288     }
6289   }
6290
6291   return SDValue();
6292 }
6293
6294 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6295   SDValue N0 = N->getOperand(0);
6296   SDValue N1 = N->getOperand(1);
6297   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6298   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6299   EVT VT = N->getValueType(0);
6300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6301
6302   // fold vector ops
6303   if (VT.isVector()) {
6304     SDValue FoldedVOp = SimplifyVBinOp(N);
6305     if (FoldedVOp.getNode()) return FoldedVOp;
6306   }
6307
6308   // fold (fmul c1, c2) -> c1*c2
6309   if (N0CFP && N1CFP)
6310     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6311   // canonicalize constant to RHS
6312   if (N0CFP && !N1CFP)
6313     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6314   // fold (fmul A, 0) -> 0
6315   if (DAG.getTarget().Options.UnsafeFPMath &&
6316       N1CFP && N1CFP->getValueAPF().isZero())
6317     return N1;
6318   // fold (fmul A, 0) -> 0, vector edition.
6319   if (DAG.getTarget().Options.UnsafeFPMath &&
6320       ISD::isBuildVectorAllZeros(N1.getNode()))
6321     return N1;
6322   // fold (fmul A, 1.0) -> A
6323   if (N1CFP && N1CFP->isExactlyValue(1.0))
6324     return N0;
6325   // fold (fmul X, 2.0) -> (fadd X, X)
6326   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6327     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6328   // fold (fmul X, -1.0) -> (fneg X)
6329   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6330     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6331       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6332
6333   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6334   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6335                                        &DAG.getTarget().Options)) {
6336     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6337                                          &DAG.getTarget().Options)) {
6338       // Both can be negated for free, check to see if at least one is cheaper
6339       // negated.
6340       if (LHSNeg == 2 || RHSNeg == 2)
6341         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6342                            GetNegatedExpression(N0, DAG, LegalOperations),
6343                            GetNegatedExpression(N1, DAG, LegalOperations));
6344     }
6345   }
6346
6347   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6348   if (DAG.getTarget().Options.UnsafeFPMath &&
6349       N1CFP && N0.getOpcode() == ISD::FMUL &&
6350       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6351     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6352                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6353                                    N0.getOperand(1), N1));
6354
6355   return SDValue();
6356 }
6357
6358 SDValue DAGCombiner::visitFMA(SDNode *N) {
6359   SDValue N0 = N->getOperand(0);
6360   SDValue N1 = N->getOperand(1);
6361   SDValue N2 = N->getOperand(2);
6362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6363   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6364   EVT VT = N->getValueType(0);
6365   SDLoc dl(N);
6366
6367   if (DAG.getTarget().Options.UnsafeFPMath) {
6368     if (N0CFP && N0CFP->isZero())
6369       return N2;
6370     if (N1CFP && N1CFP->isZero())
6371       return N2;
6372   }
6373   if (N0CFP && N0CFP->isExactlyValue(1.0))
6374     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6375   if (N1CFP && N1CFP->isExactlyValue(1.0))
6376     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6377
6378   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6379   if (N0CFP && !N1CFP)
6380     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6381
6382   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6383   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6384       N2.getOpcode() == ISD::FMUL &&
6385       N0 == N2.getOperand(0) &&
6386       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6387     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6388                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6389   }
6390
6391
6392   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6393   if (DAG.getTarget().Options.UnsafeFPMath &&
6394       N0.getOpcode() == ISD::FMUL && N1CFP &&
6395       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6396     return DAG.getNode(ISD::FMA, dl, VT,
6397                        N0.getOperand(0),
6398                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6399                        N2);
6400   }
6401
6402   // (fma x, 1, y) -> (fadd x, y)
6403   // (fma x, -1, y) -> (fadd (fneg x), y)
6404   if (N1CFP) {
6405     if (N1CFP->isExactlyValue(1.0))
6406       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6407
6408     if (N1CFP->isExactlyValue(-1.0) &&
6409         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6410       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6411       AddToWorkList(RHSNeg.getNode());
6412       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6413     }
6414   }
6415
6416   // (fma x, c, x) -> (fmul x, (c+1))
6417   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6418     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6419                        DAG.getNode(ISD::FADD, dl, VT,
6420                                    N1, DAG.getConstantFP(1.0, VT)));
6421
6422   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6423   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6424       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6425     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6426                        DAG.getNode(ISD::FADD, dl, VT,
6427                                    N1, DAG.getConstantFP(-1.0, VT)));
6428
6429
6430   return SDValue();
6431 }
6432
6433 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6434   SDValue N0 = N->getOperand(0);
6435   SDValue N1 = N->getOperand(1);
6436   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6437   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6438   EVT VT = N->getValueType(0);
6439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6440
6441   // fold vector ops
6442   if (VT.isVector()) {
6443     SDValue FoldedVOp = SimplifyVBinOp(N);
6444     if (FoldedVOp.getNode()) return FoldedVOp;
6445   }
6446
6447   // fold (fdiv c1, c2) -> c1/c2
6448   if (N0CFP && N1CFP)
6449     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6450
6451   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6452   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6453     // Compute the reciprocal 1.0 / c2.
6454     APFloat N1APF = N1CFP->getValueAPF();
6455     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6456     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6457     // Only do the transform if the reciprocal is a legal fp immediate that
6458     // isn't too nasty (eg NaN, denormal, ...).
6459     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6460         (!LegalOperations ||
6461          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6462          // backend)... we should handle this gracefully after Legalize.
6463          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6464          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6465          TLI.isFPImmLegal(Recip, VT)))
6466       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6467                          DAG.getConstantFP(Recip, VT));
6468   }
6469
6470   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6471   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6472                                        &DAG.getTarget().Options)) {
6473     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6474                                          &DAG.getTarget().Options)) {
6475       // Both can be negated for free, check to see if at least one is cheaper
6476       // negated.
6477       if (LHSNeg == 2 || RHSNeg == 2)
6478         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6479                            GetNegatedExpression(N0, DAG, LegalOperations),
6480                            GetNegatedExpression(N1, DAG, LegalOperations));
6481     }
6482   }
6483
6484   return SDValue();
6485 }
6486
6487 SDValue DAGCombiner::visitFREM(SDNode *N) {
6488   SDValue N0 = N->getOperand(0);
6489   SDValue N1 = N->getOperand(1);
6490   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6491   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6492   EVT VT = N->getValueType(0);
6493
6494   // fold (frem c1, c2) -> fmod(c1,c2)
6495   if (N0CFP && N1CFP)
6496     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6497
6498   return SDValue();
6499 }
6500
6501 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6502   SDValue N0 = N->getOperand(0);
6503   SDValue N1 = N->getOperand(1);
6504   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6505   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6506   EVT VT = N->getValueType(0);
6507
6508   if (N0CFP && N1CFP)  // Constant fold
6509     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6510
6511   if (N1CFP) {
6512     const APFloat& V = N1CFP->getValueAPF();
6513     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6514     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6515     if (!V.isNegative()) {
6516       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6517         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6518     } else {
6519       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6520         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6521                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6522     }
6523   }
6524
6525   // copysign(fabs(x), y) -> copysign(x, y)
6526   // copysign(fneg(x), y) -> copysign(x, y)
6527   // copysign(copysign(x,z), y) -> copysign(x, y)
6528   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6529       N0.getOpcode() == ISD::FCOPYSIGN)
6530     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6531                        N0.getOperand(0), N1);
6532
6533   // copysign(x, abs(y)) -> abs(x)
6534   if (N1.getOpcode() == ISD::FABS)
6535     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6536
6537   // copysign(x, copysign(y,z)) -> copysign(x, z)
6538   if (N1.getOpcode() == ISD::FCOPYSIGN)
6539     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6540                        N0, N1.getOperand(1));
6541
6542   // copysign(x, fp_extend(y)) -> copysign(x, y)
6543   // copysign(x, fp_round(y)) -> copysign(x, y)
6544   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6545     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6546                        N0, N1.getOperand(0));
6547
6548   return SDValue();
6549 }
6550
6551 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6552   SDValue N0 = N->getOperand(0);
6553   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6554   EVT VT = N->getValueType(0);
6555   EVT OpVT = N0.getValueType();
6556
6557   // fold (sint_to_fp c1) -> c1fp
6558   if (N0C &&
6559       // ...but only if the target supports immediate floating-point values
6560       (!LegalOperations ||
6561        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6562     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6563
6564   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6565   // but UINT_TO_FP is legal on this target, try to convert.
6566   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6567       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6568     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6569     if (DAG.SignBitIsZero(N0))
6570       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6571   }
6572
6573   // The next optimizations are desireable only if SELECT_CC can be lowered.
6574   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6575   // having to say they don't support SELECT_CC on every type the DAG knows
6576   // about, since there is no way to mark an opcode illegal at all value types
6577   // (See also visitSELECT)
6578   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6579     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6580     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6581         !VT.isVector() &&
6582         (!LegalOperations ||
6583          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6584       SDValue Ops[] =
6585         { N0.getOperand(0), N0.getOperand(1),
6586           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6587           N0.getOperand(2) };
6588       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6589     }
6590
6591     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6592     //      (select_cc x, y, 1.0, 0.0,, cc)
6593     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6594         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6595         (!LegalOperations ||
6596          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6597       SDValue Ops[] =
6598         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6599           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6600           N0.getOperand(0).getOperand(2) };
6601       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6602     }
6603   }
6604
6605   return SDValue();
6606 }
6607
6608 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6609   SDValue N0 = N->getOperand(0);
6610   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6611   EVT VT = N->getValueType(0);
6612   EVT OpVT = N0.getValueType();
6613
6614   // fold (uint_to_fp c1) -> c1fp
6615   if (N0C &&
6616       // ...but only if the target supports immediate floating-point values
6617       (!LegalOperations ||
6618        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6619     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6620
6621   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6622   // but SINT_TO_FP is legal on this target, try to convert.
6623   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6624       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6625     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6626     if (DAG.SignBitIsZero(N0))
6627       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6628   }
6629
6630   // The next optimizations are desireable only if SELECT_CC can be lowered.
6631   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6632   // having to say they don't support SELECT_CC on every type the DAG knows
6633   // about, since there is no way to mark an opcode illegal at all value types
6634   // (See also visitSELECT)
6635   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6636     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6637
6638     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6639         (!LegalOperations ||
6640          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6641       SDValue Ops[] =
6642         { N0.getOperand(0), N0.getOperand(1),
6643           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6644           N0.getOperand(2) };
6645       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6646     }
6647   }
6648
6649   return SDValue();
6650 }
6651
6652 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6653   SDValue N0 = N->getOperand(0);
6654   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6655   EVT VT = N->getValueType(0);
6656
6657   // fold (fp_to_sint c1fp) -> c1
6658   if (N0CFP)
6659     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6660
6661   return SDValue();
6662 }
6663
6664 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6665   SDValue N0 = N->getOperand(0);
6666   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6667   EVT VT = N->getValueType(0);
6668
6669   // fold (fp_to_uint c1fp) -> c1
6670   if (N0CFP)
6671     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6672
6673   return SDValue();
6674 }
6675
6676 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6677   SDValue N0 = N->getOperand(0);
6678   SDValue N1 = N->getOperand(1);
6679   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6680   EVT VT = N->getValueType(0);
6681
6682   // fold (fp_round c1fp) -> c1fp
6683   if (N0CFP)
6684     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6685
6686   // fold (fp_round (fp_extend x)) -> x
6687   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6688     return N0.getOperand(0);
6689
6690   // fold (fp_round (fp_round x)) -> (fp_round x)
6691   if (N0.getOpcode() == ISD::FP_ROUND) {
6692     // This is a value preserving truncation if both round's are.
6693     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6694                    N0.getNode()->getConstantOperandVal(1) == 1;
6695     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6696                        DAG.getIntPtrConstant(IsTrunc));
6697   }
6698
6699   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6700   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6701     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6702                               N0.getOperand(0), N1);
6703     AddToWorkList(Tmp.getNode());
6704     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6705                        Tmp, N0.getOperand(1));
6706   }
6707
6708   return SDValue();
6709 }
6710
6711 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6712   SDValue N0 = N->getOperand(0);
6713   EVT VT = N->getValueType(0);
6714   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6715   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6716
6717   // fold (fp_round_inreg c1fp) -> c1fp
6718   if (N0CFP && isTypeLegal(EVT)) {
6719     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6720     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6721   }
6722
6723   return SDValue();
6724 }
6725
6726 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6727   SDValue N0 = N->getOperand(0);
6728   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6729   EVT VT = N->getValueType(0);
6730
6731   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6732   if (N->hasOneUse() &&
6733       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6734     return SDValue();
6735
6736   // fold (fp_extend c1fp) -> c1fp
6737   if (N0CFP)
6738     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6739
6740   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6741   // value of X.
6742   if (N0.getOpcode() == ISD::FP_ROUND
6743       && N0.getNode()->getConstantOperandVal(1) == 1) {
6744     SDValue In = N0.getOperand(0);
6745     if (In.getValueType() == VT) return In;
6746     if (VT.bitsLT(In.getValueType()))
6747       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6748                          In, N0.getOperand(1));
6749     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6750   }
6751
6752   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6753   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6754       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6755        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6756     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6757     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6758                                      LN0->getChain(),
6759                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6760                                      N0.getValueType(),
6761                                      LN0->isVolatile(), LN0->isNonTemporal(),
6762                                      LN0->getAlignment());
6763     CombineTo(N, ExtLoad);
6764     CombineTo(N0.getNode(),
6765               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6766                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6767               ExtLoad.getValue(1));
6768     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6769   }
6770
6771   return SDValue();
6772 }
6773
6774 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6775   SDValue N0 = N->getOperand(0);
6776   EVT VT = N->getValueType(0);
6777
6778   if (VT.isVector()) {
6779     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6780     if (FoldedVOp.getNode()) return FoldedVOp;
6781   }
6782
6783   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6784                          &DAG.getTarget().Options))
6785     return GetNegatedExpression(N0, DAG, LegalOperations);
6786
6787   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6788   // constant pool values.
6789   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6790       !VT.isVector() &&
6791       N0.getNode()->hasOneUse() &&
6792       N0.getOperand(0).getValueType().isInteger()) {
6793     SDValue Int = N0.getOperand(0);
6794     EVT IntVT = Int.getValueType();
6795     if (IntVT.isInteger() && !IntVT.isVector()) {
6796       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6797               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6798       AddToWorkList(Int.getNode());
6799       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6800                          VT, Int);
6801     }
6802   }
6803
6804   // (fneg (fmul c, x)) -> (fmul -c, x)
6805   if (N0.getOpcode() == ISD::FMUL) {
6806     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6807     if (CFP1)
6808       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6809                          N0.getOperand(0),
6810                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6811                                      N0.getOperand(1)));
6812   }
6813
6814   return SDValue();
6815 }
6816
6817 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6818   SDValue N0 = N->getOperand(0);
6819   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6820   EVT VT = N->getValueType(0);
6821
6822   // fold (fceil c1) -> fceil(c1)
6823   if (N0CFP)
6824     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6825
6826   return SDValue();
6827 }
6828
6829 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6830   SDValue N0 = N->getOperand(0);
6831   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6832   EVT VT = N->getValueType(0);
6833
6834   // fold (ftrunc c1) -> ftrunc(c1)
6835   if (N0CFP)
6836     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6837
6838   return SDValue();
6839 }
6840
6841 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6842   SDValue N0 = N->getOperand(0);
6843   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6844   EVT VT = N->getValueType(0);
6845
6846   // fold (ffloor c1) -> ffloor(c1)
6847   if (N0CFP)
6848     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6849
6850   return SDValue();
6851 }
6852
6853 SDValue DAGCombiner::visitFABS(SDNode *N) {
6854   SDValue N0 = N->getOperand(0);
6855   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6856   EVT VT = N->getValueType(0);
6857
6858   if (VT.isVector()) {
6859     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6860     if (FoldedVOp.getNode()) return FoldedVOp;
6861   }
6862
6863   // fold (fabs c1) -> fabs(c1)
6864   if (N0CFP)
6865     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6866   // fold (fabs (fabs x)) -> (fabs x)
6867   if (N0.getOpcode() == ISD::FABS)
6868     return N->getOperand(0);
6869   // fold (fabs (fneg x)) -> (fabs x)
6870   // fold (fabs (fcopysign x, y)) -> (fabs x)
6871   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6872     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6873
6874   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6875   // constant pool values.
6876   if (!TLI.isFAbsFree(VT) &&
6877       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6878       N0.getOperand(0).getValueType().isInteger() &&
6879       !N0.getOperand(0).getValueType().isVector()) {
6880     SDValue Int = N0.getOperand(0);
6881     EVT IntVT = Int.getValueType();
6882     if (IntVT.isInteger() && !IntVT.isVector()) {
6883       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6884              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6885       AddToWorkList(Int.getNode());
6886       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6887                          N->getValueType(0), Int);
6888     }
6889   }
6890
6891   return SDValue();
6892 }
6893
6894 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6895   SDValue Chain = N->getOperand(0);
6896   SDValue N1 = N->getOperand(1);
6897   SDValue N2 = N->getOperand(2);
6898
6899   // If N is a constant we could fold this into a fallthrough or unconditional
6900   // branch. However that doesn't happen very often in normal code, because
6901   // Instcombine/SimplifyCFG should have handled the available opportunities.
6902   // If we did this folding here, it would be necessary to update the
6903   // MachineBasicBlock CFG, which is awkward.
6904
6905   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6906   // on the target.
6907   if (N1.getOpcode() == ISD::SETCC &&
6908       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6909                                    N1.getOperand(0).getValueType())) {
6910     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6911                        Chain, N1.getOperand(2),
6912                        N1.getOperand(0), N1.getOperand(1), N2);
6913   }
6914
6915   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6916       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6917        (N1.getOperand(0).hasOneUse() &&
6918         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6919     SDNode *Trunc = 0;
6920     if (N1.getOpcode() == ISD::TRUNCATE) {
6921       // Look pass the truncate.
6922       Trunc = N1.getNode();
6923       N1 = N1.getOperand(0);
6924     }
6925
6926     // Match this pattern so that we can generate simpler code:
6927     //
6928     //   %a = ...
6929     //   %b = and i32 %a, 2
6930     //   %c = srl i32 %b, 1
6931     //   brcond i32 %c ...
6932     //
6933     // into
6934     //
6935     //   %a = ...
6936     //   %b = and i32 %a, 2
6937     //   %c = setcc eq %b, 0
6938     //   brcond %c ...
6939     //
6940     // This applies only when the AND constant value has one bit set and the
6941     // SRL constant is equal to the log2 of the AND constant. The back-end is
6942     // smart enough to convert the result into a TEST/JMP sequence.
6943     SDValue Op0 = N1.getOperand(0);
6944     SDValue Op1 = N1.getOperand(1);
6945
6946     if (Op0.getOpcode() == ISD::AND &&
6947         Op1.getOpcode() == ISD::Constant) {
6948       SDValue AndOp1 = Op0.getOperand(1);
6949
6950       if (AndOp1.getOpcode() == ISD::Constant) {
6951         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6952
6953         if (AndConst.isPowerOf2() &&
6954             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6955           SDValue SetCC =
6956             DAG.getSetCC(SDLoc(N),
6957                          getSetCCResultType(Op0.getValueType()),
6958                          Op0, DAG.getConstant(0, Op0.getValueType()),
6959                          ISD::SETNE);
6960
6961           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6962                                           MVT::Other, Chain, SetCC, N2);
6963           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6964           // will convert it back to (X & C1) >> C2.
6965           CombineTo(N, NewBRCond, false);
6966           // Truncate is dead.
6967           if (Trunc) {
6968             removeFromWorkList(Trunc);
6969             DAG.DeleteNode(Trunc);
6970           }
6971           // Replace the uses of SRL with SETCC
6972           WorkListRemover DeadNodes(*this);
6973           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6974           removeFromWorkList(N1.getNode());
6975           DAG.DeleteNode(N1.getNode());
6976           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6977         }
6978       }
6979     }
6980
6981     if (Trunc)
6982       // Restore N1 if the above transformation doesn't match.
6983       N1 = N->getOperand(1);
6984   }
6985
6986   // Transform br(xor(x, y)) -> br(x != y)
6987   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6988   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6989     SDNode *TheXor = N1.getNode();
6990     SDValue Op0 = TheXor->getOperand(0);
6991     SDValue Op1 = TheXor->getOperand(1);
6992     if (Op0.getOpcode() == Op1.getOpcode()) {
6993       // Avoid missing important xor optimizations.
6994       SDValue Tmp = visitXOR(TheXor);
6995       if (Tmp.getNode()) {
6996         if (Tmp.getNode() != TheXor) {
6997           DEBUG(dbgs() << "\nReplacing.8 ";
6998                 TheXor->dump(&DAG);
6999                 dbgs() << "\nWith: ";
7000                 Tmp.getNode()->dump(&DAG);
7001                 dbgs() << '\n');
7002           WorkListRemover DeadNodes(*this);
7003           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7004           removeFromWorkList(TheXor);
7005           DAG.DeleteNode(TheXor);
7006           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7007                              MVT::Other, Chain, Tmp, N2);
7008         }
7009
7010         // visitXOR has changed XOR's operands or replaced the XOR completely,
7011         // bail out.
7012         return SDValue(N, 0);
7013       }
7014     }
7015
7016     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7017       bool Equal = false;
7018       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7019         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7020             Op0.getOpcode() == ISD::XOR) {
7021           TheXor = Op0.getNode();
7022           Equal = true;
7023         }
7024
7025       EVT SetCCVT = N1.getValueType();
7026       if (LegalTypes)
7027         SetCCVT = getSetCCResultType(SetCCVT);
7028       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7029                                    SetCCVT,
7030                                    Op0, Op1,
7031                                    Equal ? ISD::SETEQ : ISD::SETNE);
7032       // Replace the uses of XOR with SETCC
7033       WorkListRemover DeadNodes(*this);
7034       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7035       removeFromWorkList(N1.getNode());
7036       DAG.DeleteNode(N1.getNode());
7037       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7038                          MVT::Other, Chain, SetCC, N2);
7039     }
7040   }
7041
7042   return SDValue();
7043 }
7044
7045 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7046 //
7047 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7048   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7049   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7050
7051   // If N is a constant we could fold this into a fallthrough or unconditional
7052   // branch. However that doesn't happen very often in normal code, because
7053   // Instcombine/SimplifyCFG should have handled the available opportunities.
7054   // If we did this folding here, it would be necessary to update the
7055   // MachineBasicBlock CFG, which is awkward.
7056
7057   // Use SimplifySetCC to simplify SETCC's.
7058   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7059                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7060                                false);
7061   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7062
7063   // fold to a simpler setcc
7064   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7065     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7066                        N->getOperand(0), Simp.getOperand(2),
7067                        Simp.getOperand(0), Simp.getOperand(1),
7068                        N->getOperand(4));
7069
7070   return SDValue();
7071 }
7072
7073 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7074 /// uses N as its base pointer and that N may be folded in the load / store
7075 /// addressing mode.
7076 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7077                                     SelectionDAG &DAG,
7078                                     const TargetLowering &TLI) {
7079   EVT VT;
7080   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7081     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7082       return false;
7083     VT = Use->getValueType(0);
7084   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7085     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7086       return false;
7087     VT = ST->getValue().getValueType();
7088   } else
7089     return false;
7090
7091   TargetLowering::AddrMode AM;
7092   if (N->getOpcode() == ISD::ADD) {
7093     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7094     if (Offset)
7095       // [reg +/- imm]
7096       AM.BaseOffs = Offset->getSExtValue();
7097     else
7098       // [reg +/- reg]
7099       AM.Scale = 1;
7100   } else if (N->getOpcode() == ISD::SUB) {
7101     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7102     if (Offset)
7103       // [reg +/- imm]
7104       AM.BaseOffs = -Offset->getSExtValue();
7105     else
7106       // [reg +/- reg]
7107       AM.Scale = 1;
7108   } else
7109     return false;
7110
7111   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7112 }
7113
7114 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7115 /// pre-indexed load / store when the base pointer is an add or subtract
7116 /// and it has other uses besides the load / store. After the
7117 /// transformation, the new indexed load / store has effectively folded
7118 /// the add / subtract in and all of its other uses are redirected to the
7119 /// new load / store.
7120 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7121   if (Level < AfterLegalizeDAG)
7122     return false;
7123
7124   bool isLoad = true;
7125   SDValue Ptr;
7126   EVT VT;
7127   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7128     if (LD->isIndexed())
7129       return false;
7130     VT = LD->getMemoryVT();
7131     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7132         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7133       return false;
7134     Ptr = LD->getBasePtr();
7135   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7136     if (ST->isIndexed())
7137       return false;
7138     VT = ST->getMemoryVT();
7139     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7140         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7141       return false;
7142     Ptr = ST->getBasePtr();
7143     isLoad = false;
7144   } else {
7145     return false;
7146   }
7147
7148   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7149   // out.  There is no reason to make this a preinc/predec.
7150   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7151       Ptr.getNode()->hasOneUse())
7152     return false;
7153
7154   // Ask the target to do addressing mode selection.
7155   SDValue BasePtr;
7156   SDValue Offset;
7157   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7158   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7159     return false;
7160
7161   // Backends without true r+i pre-indexed forms may need to pass a
7162   // constant base with a variable offset so that constant coercion
7163   // will work with the patterns in canonical form.
7164   bool Swapped = false;
7165   if (isa<ConstantSDNode>(BasePtr)) {
7166     std::swap(BasePtr, Offset);
7167     Swapped = true;
7168   }
7169
7170   // Don't create a indexed load / store with zero offset.
7171   if (isa<ConstantSDNode>(Offset) &&
7172       cast<ConstantSDNode>(Offset)->isNullValue())
7173     return false;
7174
7175   // Try turning it into a pre-indexed load / store except when:
7176   // 1) The new base ptr is a frame index.
7177   // 2) If N is a store and the new base ptr is either the same as or is a
7178   //    predecessor of the value being stored.
7179   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7180   //    that would create a cycle.
7181   // 4) All uses are load / store ops that use it as old base ptr.
7182
7183   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7184   // (plus the implicit offset) to a register to preinc anyway.
7185   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7186     return false;
7187
7188   // Check #2.
7189   if (!isLoad) {
7190     SDValue Val = cast<StoreSDNode>(N)->getValue();
7191     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7192       return false;
7193   }
7194
7195   // If the offset is a constant, there may be other adds of constants that
7196   // can be folded with this one. We should do this to avoid having to keep
7197   // a copy of the original base pointer.
7198   SmallVector<SDNode *, 16> OtherUses;
7199   if (isa<ConstantSDNode>(Offset))
7200     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7201          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7202       SDNode *Use = *I;
7203       if (Use == Ptr.getNode())
7204         continue;
7205
7206       if (Use->isPredecessorOf(N))
7207         continue;
7208
7209       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7210         OtherUses.clear();
7211         break;
7212       }
7213
7214       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7215       if (Op1.getNode() == BasePtr.getNode())
7216         std::swap(Op0, Op1);
7217       assert(Op0.getNode() == BasePtr.getNode() &&
7218              "Use of ADD/SUB but not an operand");
7219
7220       if (!isa<ConstantSDNode>(Op1)) {
7221         OtherUses.clear();
7222         break;
7223       }
7224
7225       // FIXME: In some cases, we can be smarter about this.
7226       if (Op1.getValueType() != Offset.getValueType()) {
7227         OtherUses.clear();
7228         break;
7229       }
7230
7231       OtherUses.push_back(Use);
7232     }
7233
7234   if (Swapped)
7235     std::swap(BasePtr, Offset);
7236
7237   // Now check for #3 and #4.
7238   bool RealUse = false;
7239
7240   // Caches for hasPredecessorHelper
7241   SmallPtrSet<const SDNode *, 32> Visited;
7242   SmallVector<const SDNode *, 16> Worklist;
7243
7244   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7245          E = Ptr.getNode()->use_end(); I != E; ++I) {
7246     SDNode *Use = *I;
7247     if (Use == N)
7248       continue;
7249     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7250       return false;
7251
7252     // If Ptr may be folded in addressing mode of other use, then it's
7253     // not profitable to do this transformation.
7254     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7255       RealUse = true;
7256   }
7257
7258   if (!RealUse)
7259     return false;
7260
7261   SDValue Result;
7262   if (isLoad)
7263     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7264                                 BasePtr, Offset, AM);
7265   else
7266     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7267                                  BasePtr, Offset, AM);
7268   ++PreIndexedNodes;
7269   ++NodesCombined;
7270   DEBUG(dbgs() << "\nReplacing.4 ";
7271         N->dump(&DAG);
7272         dbgs() << "\nWith: ";
7273         Result.getNode()->dump(&DAG);
7274         dbgs() << '\n');
7275   WorkListRemover DeadNodes(*this);
7276   if (isLoad) {
7277     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7278     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7279   } else {
7280     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7281   }
7282
7283   // Finally, since the node is now dead, remove it from the graph.
7284   DAG.DeleteNode(N);
7285
7286   if (Swapped)
7287     std::swap(BasePtr, Offset);
7288
7289   // Replace other uses of BasePtr that can be updated to use Ptr
7290   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7291     unsigned OffsetIdx = 1;
7292     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7293       OffsetIdx = 0;
7294     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7295            BasePtr.getNode() && "Expected BasePtr operand");
7296
7297     // We need to replace ptr0 in the following expression:
7298     //   x0 * offset0 + y0 * ptr0 = t0
7299     // knowing that
7300     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7301     //
7302     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7303     // indexed load/store and the expresion that needs to be re-written.
7304     //
7305     // Therefore, we have:
7306     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7307
7308     ConstantSDNode *CN =
7309       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7310     int X0, X1, Y0, Y1;
7311     APInt Offset0 = CN->getAPIntValue();
7312     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7313
7314     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7315     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7316     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7317     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7318
7319     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7320
7321     APInt CNV = Offset0;
7322     if (X0 < 0) CNV = -CNV;
7323     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7324     else CNV = CNV - Offset1;
7325
7326     // We can now generate the new expression.
7327     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7328     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7329
7330     SDValue NewUse = DAG.getNode(Opcode,
7331                                  SDLoc(OtherUses[i]),
7332                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7333     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7334     removeFromWorkList(OtherUses[i]);
7335     DAG.DeleteNode(OtherUses[i]);
7336   }
7337
7338   // Replace the uses of Ptr with uses of the updated base value.
7339   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7340   removeFromWorkList(Ptr.getNode());
7341   DAG.DeleteNode(Ptr.getNode());
7342
7343   return true;
7344 }
7345
7346 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7347 /// add / sub of the base pointer node into a post-indexed load / store.
7348 /// The transformation folded the add / subtract into the new indexed
7349 /// load / store effectively and all of its uses are redirected to the
7350 /// new load / store.
7351 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7352   if (Level < AfterLegalizeDAG)
7353     return false;
7354
7355   bool isLoad = true;
7356   SDValue Ptr;
7357   EVT VT;
7358   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7359     if (LD->isIndexed())
7360       return false;
7361     VT = LD->getMemoryVT();
7362     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7363         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7364       return false;
7365     Ptr = LD->getBasePtr();
7366   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7367     if (ST->isIndexed())
7368       return false;
7369     VT = ST->getMemoryVT();
7370     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7371         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7372       return false;
7373     Ptr = ST->getBasePtr();
7374     isLoad = false;
7375   } else {
7376     return false;
7377   }
7378
7379   if (Ptr.getNode()->hasOneUse())
7380     return false;
7381
7382   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7383          E = Ptr.getNode()->use_end(); I != E; ++I) {
7384     SDNode *Op = *I;
7385     if (Op == N ||
7386         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7387       continue;
7388
7389     SDValue BasePtr;
7390     SDValue Offset;
7391     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7392     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7393       // Don't create a indexed load / store with zero offset.
7394       if (isa<ConstantSDNode>(Offset) &&
7395           cast<ConstantSDNode>(Offset)->isNullValue())
7396         continue;
7397
7398       // Try turning it into a post-indexed load / store except when
7399       // 1) All uses are load / store ops that use it as base ptr (and
7400       //    it may be folded as addressing mmode).
7401       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7402       //    nor a successor of N. Otherwise, if Op is folded that would
7403       //    create a cycle.
7404
7405       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7406         continue;
7407
7408       // Check for #1.
7409       bool TryNext = false;
7410       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7411              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7412         SDNode *Use = *II;
7413         if (Use == Ptr.getNode())
7414           continue;
7415
7416         // If all the uses are load / store addresses, then don't do the
7417         // transformation.
7418         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7419           bool RealUse = false;
7420           for (SDNode::use_iterator III = Use->use_begin(),
7421                  EEE = Use->use_end(); III != EEE; ++III) {
7422             SDNode *UseUse = *III;
7423             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7424               RealUse = true;
7425           }
7426
7427           if (!RealUse) {
7428             TryNext = true;
7429             break;
7430           }
7431         }
7432       }
7433
7434       if (TryNext)
7435         continue;
7436
7437       // Check for #2
7438       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7439         SDValue Result = isLoad
7440           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7441                                BasePtr, Offset, AM)
7442           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7443                                 BasePtr, Offset, AM);
7444         ++PostIndexedNodes;
7445         ++NodesCombined;
7446         DEBUG(dbgs() << "\nReplacing.5 ";
7447               N->dump(&DAG);
7448               dbgs() << "\nWith: ";
7449               Result.getNode()->dump(&DAG);
7450               dbgs() << '\n');
7451         WorkListRemover DeadNodes(*this);
7452         if (isLoad) {
7453           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7454           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7455         } else {
7456           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7457         }
7458
7459         // Finally, since the node is now dead, remove it from the graph.
7460         DAG.DeleteNode(N);
7461
7462         // Replace the uses of Use with uses of the updated base value.
7463         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7464                                       Result.getValue(isLoad ? 1 : 0));
7465         removeFromWorkList(Op);
7466         DAG.DeleteNode(Op);
7467         return true;
7468       }
7469     }
7470   }
7471
7472   return false;
7473 }
7474
7475 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7476   LoadSDNode *LD  = cast<LoadSDNode>(N);
7477   SDValue Chain = LD->getChain();
7478   SDValue Ptr   = LD->getBasePtr();
7479
7480   // If load is not volatile and there are no uses of the loaded value (and
7481   // the updated indexed value in case of indexed loads), change uses of the
7482   // chain value into uses of the chain input (i.e. delete the dead load).
7483   if (!LD->isVolatile()) {
7484     if (N->getValueType(1) == MVT::Other) {
7485       // Unindexed loads.
7486       if (!N->hasAnyUseOfValue(0)) {
7487         // It's not safe to use the two value CombineTo variant here. e.g.
7488         // v1, chain2 = load chain1, loc
7489         // v2, chain3 = load chain2, loc
7490         // v3         = add v2, c
7491         // Now we replace use of chain2 with chain1.  This makes the second load
7492         // isomorphic to the one we are deleting, and thus makes this load live.
7493         DEBUG(dbgs() << "\nReplacing.6 ";
7494               N->dump(&DAG);
7495               dbgs() << "\nWith chain: ";
7496               Chain.getNode()->dump(&DAG);
7497               dbgs() << "\n");
7498         WorkListRemover DeadNodes(*this);
7499         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7500
7501         if (N->use_empty()) {
7502           removeFromWorkList(N);
7503           DAG.DeleteNode(N);
7504         }
7505
7506         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7507       }
7508     } else {
7509       // Indexed loads.
7510       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7511       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7512         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7513         DEBUG(dbgs() << "\nReplacing.7 ";
7514               N->dump(&DAG);
7515               dbgs() << "\nWith: ";
7516               Undef.getNode()->dump(&DAG);
7517               dbgs() << " and 2 other values\n");
7518         WorkListRemover DeadNodes(*this);
7519         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7520         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7521                                       DAG.getUNDEF(N->getValueType(1)));
7522         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7523         removeFromWorkList(N);
7524         DAG.DeleteNode(N);
7525         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7526       }
7527     }
7528   }
7529
7530   // If this load is directly stored, replace the load value with the stored
7531   // value.
7532   // TODO: Handle store large -> read small portion.
7533   // TODO: Handle TRUNCSTORE/LOADEXT
7534   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7535     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7536       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7537       if (PrevST->getBasePtr() == Ptr &&
7538           PrevST->getValue().getValueType() == N->getValueType(0))
7539       return CombineTo(N, Chain.getOperand(1), Chain);
7540     }
7541   }
7542
7543   // Try to infer better alignment information than the load already has.
7544   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7545     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7546       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7547         SDValue NewLoad =
7548                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7549                               LD->getValueType(0),
7550                               Chain, Ptr, LD->getPointerInfo(),
7551                               LD->getMemoryVT(),
7552                               LD->isVolatile(), LD->isNonTemporal(), Align);
7553         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7554       }
7555     }
7556   }
7557
7558   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7559     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7560   if (UseAA) {
7561     // Walk up chain skipping non-aliasing memory nodes.
7562     SDValue BetterChain = FindBetterChain(N, Chain);
7563
7564     // If there is a better chain.
7565     if (Chain != BetterChain) {
7566       SDValue ReplLoad;
7567
7568       // Replace the chain to void dependency.
7569       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7570         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7571                                BetterChain, Ptr, LD->getPointerInfo(),
7572                                LD->isVolatile(), LD->isNonTemporal(),
7573                                LD->isInvariant(), LD->getAlignment());
7574       } else {
7575         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7576                                   LD->getValueType(0),
7577                                   BetterChain, Ptr, LD->getPointerInfo(),
7578                                   LD->getMemoryVT(),
7579                                   LD->isVolatile(),
7580                                   LD->isNonTemporal(),
7581                                   LD->getAlignment());
7582       }
7583
7584       // Create token factor to keep old chain connected.
7585       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7586                                   MVT::Other, Chain, ReplLoad.getValue(1));
7587
7588       // Make sure the new and old chains are cleaned up.
7589       AddToWorkList(Token.getNode());
7590
7591       // Replace uses with load result and token factor. Don't add users
7592       // to work list.
7593       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7594     }
7595   }
7596
7597   // Try transforming N to an indexed load.
7598   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7599     return SDValue(N, 0);
7600
7601   // Try to slice up N to more direct loads if the slices are mapped to
7602   // different register banks or pairing can take place.
7603   if (SliceUpLoad(N))
7604     return SDValue(N, 0);
7605
7606   return SDValue();
7607 }
7608
7609 namespace {
7610 /// \brief Helper structure used to slice a load in smaller loads.
7611 /// Basically a slice is obtained from the following sequence:
7612 /// Origin = load Ty1, Base
7613 /// Shift = srl Ty1 Origin, CstTy Amount
7614 /// Inst = trunc Shift to Ty2
7615 ///
7616 /// Then, it will be rewriten into:
7617 /// Slice = load SliceTy, Base + SliceOffset
7618 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7619 ///
7620 /// SliceTy is deduced from the number of bits that are actually used to
7621 /// build Inst.
7622 struct LoadedSlice {
7623   /// \brief Helper structure used to compute the cost of a slice.
7624   struct Cost {
7625     /// Are we optimizing for code size.
7626     bool ForCodeSize;
7627     /// Various cost.
7628     unsigned Loads;
7629     unsigned Truncates;
7630     unsigned CrossRegisterBanksCopies;
7631     unsigned ZExts;
7632     unsigned Shift;
7633
7634     Cost(bool ForCodeSize = false)
7635         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7636           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7637
7638     /// \brief Get the cost of one isolated slice.
7639     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7640         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7641           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7642       EVT TruncType = LS.Inst->getValueType(0);
7643       EVT LoadedType = LS.getLoadedType();
7644       if (TruncType != LoadedType &&
7645           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7646         ZExts = 1;
7647     }
7648
7649     /// \brief Account for slicing gain in the current cost.
7650     /// Slicing provide a few gains like removing a shift or a
7651     /// truncate. This method allows to grow the cost of the original
7652     /// load with the gain from this slice.
7653     void addSliceGain(const LoadedSlice &LS) {
7654       // Each slice saves a truncate.
7655       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7656       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7657                               LS.Inst->getOperand(0).getValueType()))
7658         ++Truncates;
7659       // If there is a shift amount, this slice gets rid of it.
7660       if (LS.Shift)
7661         ++Shift;
7662       // If this slice can merge a cross register bank copy, account for it.
7663       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7664         ++CrossRegisterBanksCopies;
7665     }
7666
7667     Cost &operator+=(const Cost &RHS) {
7668       Loads += RHS.Loads;
7669       Truncates += RHS.Truncates;
7670       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7671       ZExts += RHS.ZExts;
7672       Shift += RHS.Shift;
7673       return *this;
7674     }
7675
7676     bool operator==(const Cost &RHS) const {
7677       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7678              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7679              ZExts == RHS.ZExts && Shift == RHS.Shift;
7680     }
7681
7682     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7683
7684     bool operator<(const Cost &RHS) const {
7685       // Assume cross register banks copies are as expensive as loads.
7686       // FIXME: Do we want some more target hooks?
7687       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7688       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7689       // Unless we are optimizing for code size, consider the
7690       // expensive operation first.
7691       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7692         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7693       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7694              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7695     }
7696
7697     bool operator>(const Cost &RHS) const { return RHS < *this; }
7698
7699     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7700
7701     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7702   };
7703   // The last instruction that represent the slice. This should be a
7704   // truncate instruction.
7705   SDNode *Inst;
7706   // The original load instruction.
7707   LoadSDNode *Origin;
7708   // The right shift amount in bits from the original load.
7709   unsigned Shift;
7710   // The DAG from which Origin came from.
7711   // This is used to get some contextual information about legal types, etc.
7712   SelectionDAG *DAG;
7713
7714   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7715               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7716       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7717
7718   LoadedSlice(const LoadedSlice &LS)
7719       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7720
7721   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7722   /// \return Result is \p BitWidth and has used bits set to 1 and
7723   ///         not used bits set to 0.
7724   APInt getUsedBits() const {
7725     // Reproduce the trunc(lshr) sequence:
7726     // - Start from the truncated value.
7727     // - Zero extend to the desired bit width.
7728     // - Shift left.
7729     assert(Origin && "No original load to compare against.");
7730     unsigned BitWidth = Origin->getValueSizeInBits(0);
7731     assert(Inst && "This slice is not bound to an instruction");
7732     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7733            "Extracted slice is bigger than the whole type!");
7734     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7735     UsedBits.setAllBits();
7736     UsedBits = UsedBits.zext(BitWidth);
7737     UsedBits <<= Shift;
7738     return UsedBits;
7739   }
7740
7741   /// \brief Get the size of the slice to be loaded in bytes.
7742   unsigned getLoadedSize() const {
7743     unsigned SliceSize = getUsedBits().countPopulation();
7744     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7745     return SliceSize / 8;
7746   }
7747
7748   /// \brief Get the type that will be loaded for this slice.
7749   /// Note: This may not be the final type for the slice.
7750   EVT getLoadedType() const {
7751     assert(DAG && "Missing context");
7752     LLVMContext &Ctxt = *DAG->getContext();
7753     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7754   }
7755
7756   /// \brief Get the alignment of the load used for this slice.
7757   unsigned getAlignment() const {
7758     unsigned Alignment = Origin->getAlignment();
7759     unsigned Offset = getOffsetFromBase();
7760     if (Offset != 0)
7761       Alignment = MinAlign(Alignment, Alignment + Offset);
7762     return Alignment;
7763   }
7764
7765   /// \brief Check if this slice can be rewritten with legal operations.
7766   bool isLegal() const {
7767     // An invalid slice is not legal.
7768     if (!Origin || !Inst || !DAG)
7769       return false;
7770
7771     // Offsets are for indexed load only, we do not handle that.
7772     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7773       return false;
7774
7775     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7776
7777     // Check that the type is legal.
7778     EVT SliceType = getLoadedType();
7779     if (!TLI.isTypeLegal(SliceType))
7780       return false;
7781
7782     // Check that the load is legal for this type.
7783     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7784       return false;
7785
7786     // Check that the offset can be computed.
7787     // 1. Check its type.
7788     EVT PtrType = Origin->getBasePtr().getValueType();
7789     if (PtrType == MVT::Untyped || PtrType.isExtended())
7790       return false;
7791
7792     // 2. Check that it fits in the immediate.
7793     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7794       return false;
7795
7796     // 3. Check that the computation is legal.
7797     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7798       return false;
7799
7800     // Check that the zext is legal if it needs one.
7801     EVT TruncateType = Inst->getValueType(0);
7802     if (TruncateType != SliceType &&
7803         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7804       return false;
7805
7806     return true;
7807   }
7808
7809   /// \brief Get the offset in bytes of this slice in the original chunk of
7810   /// bits.
7811   /// \pre DAG != NULL.
7812   uint64_t getOffsetFromBase() const {
7813     assert(DAG && "Missing context.");
7814     bool IsBigEndian =
7815         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7816     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7817     uint64_t Offset = Shift / 8;
7818     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7819     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7820            "The size of the original loaded type is not a multiple of a"
7821            " byte.");
7822     // If Offset is bigger than TySizeInBytes, it means we are loading all
7823     // zeros. This should have been optimized before in the process.
7824     assert(TySizeInBytes > Offset &&
7825            "Invalid shift amount for given loaded size");
7826     if (IsBigEndian)
7827       Offset = TySizeInBytes - Offset - getLoadedSize();
7828     return Offset;
7829   }
7830
7831   /// \brief Generate the sequence of instructions to load the slice
7832   /// represented by this object and redirect the uses of this slice to
7833   /// this new sequence of instructions.
7834   /// \pre this->Inst && this->Origin are valid Instructions and this
7835   /// object passed the legal check: LoadedSlice::isLegal returned true.
7836   /// \return The last instruction of the sequence used to load the slice.
7837   SDValue loadSlice() const {
7838     assert(Inst && Origin && "Unable to replace a non-existing slice.");
7839     const SDValue &OldBaseAddr = Origin->getBasePtr();
7840     SDValue BaseAddr = OldBaseAddr;
7841     // Get the offset in that chunk of bytes w.r.t. the endianess.
7842     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7843     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7844     if (Offset) {
7845       // BaseAddr = BaseAddr + Offset.
7846       EVT ArithType = BaseAddr.getValueType();
7847       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7848                               DAG->getConstant(Offset, ArithType));
7849     }
7850
7851     // Create the type of the loaded slice according to its size.
7852     EVT SliceType = getLoadedType();
7853
7854     // Create the load for the slice.
7855     SDValue LastInst = DAG->getLoad(
7856         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7857         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7858         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7859     // If the final type is not the same as the loaded type, this means that
7860     // we have to pad with zero. Create a zero extend for that.
7861     EVT FinalType = Inst->getValueType(0);
7862     if (SliceType != FinalType)
7863       LastInst =
7864           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7865     return LastInst;
7866   }
7867
7868   /// \brief Check if this slice can be merged with an expensive cross register
7869   /// bank copy. E.g.,
7870   /// i = load i32
7871   /// f = bitcast i32 i to float
7872   bool canMergeExpensiveCrossRegisterBankCopy() const {
7873     if (!Inst || !Inst->hasOneUse())
7874       return false;
7875     SDNode *Use = *Inst->use_begin();
7876     if (Use->getOpcode() != ISD::BITCAST)
7877       return false;
7878     assert(DAG && "Missing context");
7879     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7880     EVT ResVT = Use->getValueType(0);
7881     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7882     const TargetRegisterClass *ArgRC =
7883         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7884     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7885       return false;
7886
7887     // At this point, we know that we perform a cross-register-bank copy.
7888     // Check if it is expensive.
7889     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7890     // Assume bitcasts are cheap, unless both register classes do not
7891     // explicitly share a common sub class.
7892     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7893       return false;
7894
7895     // Check if it will be merged with the load.
7896     // 1. Check the alignment constraint.
7897     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7898         ResVT.getTypeForEVT(*DAG->getContext()));
7899
7900     if (RequiredAlignment > getAlignment())
7901       return false;
7902
7903     // 2. Check that the load is a legal operation for that type.
7904     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7905       return false;
7906
7907     // 3. Check that we do not have a zext in the way.
7908     if (Inst->getValueType(0) != getLoadedType())
7909       return false;
7910
7911     return true;
7912   }
7913 };
7914 }
7915
7916 /// \brief Sorts LoadedSlice according to their offset.
7917 struct LoadedSliceSorter {
7918   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7919     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7920     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7921   }
7922 };
7923
7924 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7925 /// \p UsedBits looks like 0..0 1..1 0..0.
7926 static bool areUsedBitsDense(const APInt &UsedBits) {
7927   // If all the bits are one, this is dense!
7928   if (UsedBits.isAllOnesValue())
7929     return true;
7930
7931   // Get rid of the unused bits on the right.
7932   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7933   // Get rid of the unused bits on the left.
7934   if (NarrowedUsedBits.countLeadingZeros())
7935     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7936   // Check that the chunk of bits is completely used.
7937   return NarrowedUsedBits.isAllOnesValue();
7938 }
7939
7940 /// \brief Check whether or not \p First and \p Second are next to each other
7941 /// in memory. This means that there is no hole between the bits loaded
7942 /// by \p First and the bits loaded by \p Second.
7943 static bool areSlicesNextToEachOther(const LoadedSlice &First,
7944                                      const LoadedSlice &Second) {
7945   assert(First.Origin == Second.Origin && First.Origin &&
7946          "Unable to match different memory origins.");
7947   APInt UsedBits = First.getUsedBits();
7948   assert((UsedBits & Second.getUsedBits()) == 0 &&
7949          "Slices are not supposed to overlap.");
7950   UsedBits |= Second.getUsedBits();
7951   return areUsedBitsDense(UsedBits);
7952 }
7953
7954 /// \brief Adjust the \p GlobalLSCost according to the target
7955 /// paring capabilities and the layout of the slices.
7956 /// \pre \p GlobalLSCost should account for at least as many loads as
7957 /// there is in the slices in \p LoadedSlices.
7958 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
7959                                  LoadedSlice::Cost &GlobalLSCost) {
7960   unsigned NumberOfSlices = LoadedSlices.size();
7961   // If there is less than 2 elements, no pairing is possible.
7962   if (NumberOfSlices < 2)
7963     return;
7964
7965   // Sort the slices so that elements that are likely to be next to each
7966   // other in memory are next to each other in the list.
7967   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
7968   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
7969   // First (resp. Second) is the first (resp. Second) potentially candidate
7970   // to be placed in a paired load.
7971   const LoadedSlice *First = NULL;
7972   const LoadedSlice *Second = NULL;
7973   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
7974                 // Set the beginning of the pair.
7975                                                            First = Second) {
7976
7977     Second = &LoadedSlices[CurrSlice];
7978
7979     // If First is NULL, it means we start a new pair.
7980     // Get to the next slice.
7981     if (!First)
7982       continue;
7983
7984     EVT LoadedType = First->getLoadedType();
7985
7986     // If the types of the slices are different, we cannot pair them.
7987     if (LoadedType != Second->getLoadedType())
7988       continue;
7989
7990     // Check if the target supplies paired loads for this type.
7991     unsigned RequiredAlignment = 0;
7992     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
7993       // move to the next pair, this type is hopeless.
7994       Second = NULL;
7995       continue;
7996     }
7997     // Check if we meet the alignment requirement.
7998     if (RequiredAlignment > First->getAlignment())
7999       continue;
8000
8001     // Check that both loads are next to each other in memory.
8002     if (!areSlicesNextToEachOther(*First, *Second))
8003       continue;
8004
8005     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8006     --GlobalLSCost.Loads;
8007     // Move to the next pair.
8008     Second = NULL;
8009   }
8010 }
8011
8012 /// \brief Check the profitability of all involved LoadedSlice.
8013 /// Currently, it is considered profitable if there is exactly two
8014 /// involved slices (1) which are (2) next to each other in memory, and
8015 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8016 ///
8017 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8018 /// the elements themselves.
8019 ///
8020 /// FIXME: When the cost model will be mature enough, we can relax
8021 /// constraints (1) and (2).
8022 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8023                                 const APInt &UsedBits, bool ForCodeSize) {
8024   unsigned NumberOfSlices = LoadedSlices.size();
8025   if (StressLoadSlicing)
8026     return NumberOfSlices > 1;
8027
8028   // Check (1).
8029   if (NumberOfSlices != 2)
8030     return false;
8031
8032   // Check (2).
8033   if (!areUsedBitsDense(UsedBits))
8034     return false;
8035
8036   // Check (3).
8037   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8038   // The original code has one big load.
8039   OrigCost.Loads = 1;
8040   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8041     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8042     // Accumulate the cost of all the slices.
8043     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8044     GlobalSlicingCost += SliceCost;
8045
8046     // Account as cost in the original configuration the gain obtained
8047     // with the current slices.
8048     OrigCost.addSliceGain(LS);
8049   }
8050
8051   // If the target supports paired load, adjust the cost accordingly.
8052   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8053   return OrigCost > GlobalSlicingCost;
8054 }
8055
8056 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8057 /// operations, split it in the various pieces being extracted.
8058 ///
8059 /// This sort of thing is introduced by SROA.
8060 /// This slicing takes care not to insert overlapping loads.
8061 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8062 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8063   if (Level < AfterLegalizeDAG)
8064     return false;
8065
8066   LoadSDNode *LD = cast<LoadSDNode>(N);
8067   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8068       !LD->getValueType(0).isInteger())
8069     return false;
8070
8071   // Keep track of already used bits to detect overlapping values.
8072   // In that case, we will just abort the transformation.
8073   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8074
8075   SmallVector<LoadedSlice, 4> LoadedSlices;
8076
8077   // Check if this load is used as several smaller chunks of bits.
8078   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8079   // of computation for each trunc.
8080   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8081        UI != UIEnd; ++UI) {
8082     // Skip the uses of the chain.
8083     if (UI.getUse().getResNo() != 0)
8084       continue;
8085
8086     SDNode *User = *UI;
8087     unsigned Shift = 0;
8088
8089     // Check if this is a trunc(lshr).
8090     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8091         isa<ConstantSDNode>(User->getOperand(1))) {
8092       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8093       User = *User->use_begin();
8094     }
8095
8096     // At this point, User is a Truncate, iff we encountered, trunc or
8097     // trunc(lshr).
8098     if (User->getOpcode() != ISD::TRUNCATE)
8099       return false;
8100
8101     // The width of the type must be a power of 2 and greater than 8-bits.
8102     // Otherwise the load cannot be represented in LLVM IR.
8103     // Moreover, if we shifted with a non 8-bits multiple, the slice
8104     // will be accross several bytes. We do not support that.
8105     unsigned Width = User->getValueSizeInBits(0);
8106     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8107       return 0;
8108
8109     // Build the slice for this chain of computations.
8110     LoadedSlice LS(User, LD, Shift, &DAG);
8111     APInt CurrentUsedBits = LS.getUsedBits();
8112
8113     // Check if this slice overlaps with another.
8114     if ((CurrentUsedBits & UsedBits) != 0)
8115       return false;
8116     // Update the bits used globally.
8117     UsedBits |= CurrentUsedBits;
8118
8119     // Check if the new slice would be legal.
8120     if (!LS.isLegal())
8121       return false;
8122
8123     // Record the slice.
8124     LoadedSlices.push_back(LS);
8125   }
8126
8127   // Abort slicing if it does not seem to be profitable.
8128   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8129     return false;
8130
8131   ++SlicedLoads;
8132
8133   // Rewrite each chain to use an independent load.
8134   // By construction, each chain can be represented by a unique load.
8135
8136   // Prepare the argument for the new token factor for all the slices.
8137   SmallVector<SDValue, 8> ArgChains;
8138   for (SmallVectorImpl<LoadedSlice>::const_iterator
8139            LSIt = LoadedSlices.begin(),
8140            LSItEnd = LoadedSlices.end();
8141        LSIt != LSItEnd; ++LSIt) {
8142     SDValue SliceInst = LSIt->loadSlice();
8143     CombineTo(LSIt->Inst, SliceInst, true);
8144     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8145       SliceInst = SliceInst.getOperand(0);
8146     assert(SliceInst->getOpcode() == ISD::LOAD &&
8147            "It takes more than a zext to get to the loaded slice!!");
8148     ArgChains.push_back(SliceInst.getValue(1));
8149   }
8150
8151   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8152                               &ArgChains[0], ArgChains.size());
8153   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8154   return true;
8155 }
8156
8157 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8158 /// load is having specific bytes cleared out.  If so, return the byte size
8159 /// being masked out and the shift amount.
8160 static std::pair<unsigned, unsigned>
8161 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8162   std::pair<unsigned, unsigned> Result(0, 0);
8163
8164   // Check for the structure we're looking for.
8165   if (V->getOpcode() != ISD::AND ||
8166       !isa<ConstantSDNode>(V->getOperand(1)) ||
8167       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8168     return Result;
8169
8170   // Check the chain and pointer.
8171   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8172   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8173
8174   // The store should be chained directly to the load or be an operand of a
8175   // tokenfactor.
8176   if (LD == Chain.getNode())
8177     ; // ok.
8178   else if (Chain->getOpcode() != ISD::TokenFactor)
8179     return Result; // Fail.
8180   else {
8181     bool isOk = false;
8182     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8183       if (Chain->getOperand(i).getNode() == LD) {
8184         isOk = true;
8185         break;
8186       }
8187     if (!isOk) return Result;
8188   }
8189
8190   // This only handles simple types.
8191   if (V.getValueType() != MVT::i16 &&
8192       V.getValueType() != MVT::i32 &&
8193       V.getValueType() != MVT::i64)
8194     return Result;
8195
8196   // Check the constant mask.  Invert it so that the bits being masked out are
8197   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8198   // follow the sign bit for uniformity.
8199   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8200   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8201   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8202   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8203   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8204   if (NotMaskLZ == 64) return Result;  // All zero mask.
8205
8206   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8207   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8208     return Result;
8209
8210   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8211   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8212     NotMaskLZ -= 64-V.getValueSizeInBits();
8213
8214   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8215   switch (MaskedBytes) {
8216   case 1:
8217   case 2:
8218   case 4: break;
8219   default: return Result; // All one mask, or 5-byte mask.
8220   }
8221
8222   // Verify that the first bit starts at a multiple of mask so that the access
8223   // is aligned the same as the access width.
8224   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8225
8226   Result.first = MaskedBytes;
8227   Result.second = NotMaskTZ/8;
8228   return Result;
8229 }
8230
8231
8232 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8233 /// provides a value as specified by MaskInfo.  If so, replace the specified
8234 /// store with a narrower store of truncated IVal.
8235 static SDNode *
8236 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8237                                 SDValue IVal, StoreSDNode *St,
8238                                 DAGCombiner *DC) {
8239   unsigned NumBytes = MaskInfo.first;
8240   unsigned ByteShift = MaskInfo.second;
8241   SelectionDAG &DAG = DC->getDAG();
8242
8243   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8244   // that uses this.  If not, this is not a replacement.
8245   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8246                                   ByteShift*8, (ByteShift+NumBytes)*8);
8247   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8248
8249   // Check that it is legal on the target to do this.  It is legal if the new
8250   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8251   // legalization.
8252   MVT VT = MVT::getIntegerVT(NumBytes*8);
8253   if (!DC->isTypeLegal(VT))
8254     return 0;
8255
8256   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8257   // shifted by ByteShift and truncated down to NumBytes.
8258   if (ByteShift)
8259     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8260                        DAG.getConstant(ByteShift*8,
8261                                     DC->getShiftAmountTy(IVal.getValueType())));
8262
8263   // Figure out the offset for the store and the alignment of the access.
8264   unsigned StOffset;
8265   unsigned NewAlign = St->getAlignment();
8266
8267   if (DAG.getTargetLoweringInfo().isLittleEndian())
8268     StOffset = ByteShift;
8269   else
8270     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8271
8272   SDValue Ptr = St->getBasePtr();
8273   if (StOffset) {
8274     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8275                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8276     NewAlign = MinAlign(NewAlign, StOffset);
8277   }
8278
8279   // Truncate down to the new size.
8280   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8281
8282   ++OpsNarrowed;
8283   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8284                       St->getPointerInfo().getWithOffset(StOffset),
8285                       false, false, NewAlign).getNode();
8286 }
8287
8288
8289 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8290 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8291 /// of the loaded bits, try narrowing the load and store if it would end up
8292 /// being a win for performance or code size.
8293 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8294   StoreSDNode *ST  = cast<StoreSDNode>(N);
8295   if (ST->isVolatile())
8296     return SDValue();
8297
8298   SDValue Chain = ST->getChain();
8299   SDValue Value = ST->getValue();
8300   SDValue Ptr   = ST->getBasePtr();
8301   EVT VT = Value.getValueType();
8302
8303   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8304     return SDValue();
8305
8306   unsigned Opc = Value.getOpcode();
8307
8308   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8309   // is a byte mask indicating a consecutive number of bytes, check to see if
8310   // Y is known to provide just those bytes.  If so, we try to replace the
8311   // load + replace + store sequence with a single (narrower) store, which makes
8312   // the load dead.
8313   if (Opc == ISD::OR) {
8314     std::pair<unsigned, unsigned> MaskedLoad;
8315     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8316     if (MaskedLoad.first)
8317       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8318                                                   Value.getOperand(1), ST,this))
8319         return SDValue(NewST, 0);
8320
8321     // Or is commutative, so try swapping X and Y.
8322     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8323     if (MaskedLoad.first)
8324       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8325                                                   Value.getOperand(0), ST,this))
8326         return SDValue(NewST, 0);
8327   }
8328
8329   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8330       Value.getOperand(1).getOpcode() != ISD::Constant)
8331     return SDValue();
8332
8333   SDValue N0 = Value.getOperand(0);
8334   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8335       Chain == SDValue(N0.getNode(), 1)) {
8336     LoadSDNode *LD = cast<LoadSDNode>(N0);
8337     if (LD->getBasePtr() != Ptr ||
8338         LD->getPointerInfo().getAddrSpace() !=
8339         ST->getPointerInfo().getAddrSpace())
8340       return SDValue();
8341
8342     // Find the type to narrow it the load / op / store to.
8343     SDValue N1 = Value.getOperand(1);
8344     unsigned BitWidth = N1.getValueSizeInBits();
8345     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8346     if (Opc == ISD::AND)
8347       Imm ^= APInt::getAllOnesValue(BitWidth);
8348     if (Imm == 0 || Imm.isAllOnesValue())
8349       return SDValue();
8350     unsigned ShAmt = Imm.countTrailingZeros();
8351     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8352     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8353     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8354     while (NewBW < BitWidth &&
8355            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8356              TLI.isNarrowingProfitable(VT, NewVT))) {
8357       NewBW = NextPowerOf2(NewBW);
8358       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8359     }
8360     if (NewBW >= BitWidth)
8361       return SDValue();
8362
8363     // If the lsb changed does not start at the type bitwidth boundary,
8364     // start at the previous one.
8365     if (ShAmt % NewBW)
8366       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8367     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8368                                    std::min(BitWidth, ShAmt + NewBW));
8369     if ((Imm & Mask) == Imm) {
8370       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8371       if (Opc == ISD::AND)
8372         NewImm ^= APInt::getAllOnesValue(NewBW);
8373       uint64_t PtrOff = ShAmt / 8;
8374       // For big endian targets, we need to adjust the offset to the pointer to
8375       // load the correct bytes.
8376       if (TLI.isBigEndian())
8377         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8378
8379       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8380       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8381       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8382         return SDValue();
8383
8384       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8385                                    Ptr.getValueType(), Ptr,
8386                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8387       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8388                                   LD->getChain(), NewPtr,
8389                                   LD->getPointerInfo().getWithOffset(PtrOff),
8390                                   LD->isVolatile(), LD->isNonTemporal(),
8391                                   LD->isInvariant(), NewAlign);
8392       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8393                                    DAG.getConstant(NewImm, NewVT));
8394       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8395                                    NewVal, NewPtr,
8396                                    ST->getPointerInfo().getWithOffset(PtrOff),
8397                                    false, false, NewAlign);
8398
8399       AddToWorkList(NewPtr.getNode());
8400       AddToWorkList(NewLD.getNode());
8401       AddToWorkList(NewVal.getNode());
8402       WorkListRemover DeadNodes(*this);
8403       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8404       ++OpsNarrowed;
8405       return NewST;
8406     }
8407   }
8408
8409   return SDValue();
8410 }
8411
8412 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8413 /// if the load value isn't used by any other operations, then consider
8414 /// transforming the pair to integer load / store operations if the target
8415 /// deems the transformation profitable.
8416 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8417   StoreSDNode *ST  = cast<StoreSDNode>(N);
8418   SDValue Chain = ST->getChain();
8419   SDValue Value = ST->getValue();
8420   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8421       Value.hasOneUse() &&
8422       Chain == SDValue(Value.getNode(), 1)) {
8423     LoadSDNode *LD = cast<LoadSDNode>(Value);
8424     EVT VT = LD->getMemoryVT();
8425     if (!VT.isFloatingPoint() ||
8426         VT != ST->getMemoryVT() ||
8427         LD->isNonTemporal() ||
8428         ST->isNonTemporal() ||
8429         LD->getPointerInfo().getAddrSpace() != 0 ||
8430         ST->getPointerInfo().getAddrSpace() != 0)
8431       return SDValue();
8432
8433     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8434     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8435         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8436         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8437         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8438       return SDValue();
8439
8440     unsigned LDAlign = LD->getAlignment();
8441     unsigned STAlign = ST->getAlignment();
8442     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8443     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8444     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8445       return SDValue();
8446
8447     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8448                                 LD->getChain(), LD->getBasePtr(),
8449                                 LD->getPointerInfo(),
8450                                 false, false, false, LDAlign);
8451
8452     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8453                                  NewLD, ST->getBasePtr(),
8454                                  ST->getPointerInfo(),
8455                                  false, false, STAlign);
8456
8457     AddToWorkList(NewLD.getNode());
8458     AddToWorkList(NewST.getNode());
8459     WorkListRemover DeadNodes(*this);
8460     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8461     ++LdStFP2Int;
8462     return NewST;
8463   }
8464
8465   return SDValue();
8466 }
8467
8468 /// Helper struct to parse and store a memory address as base + index + offset.
8469 /// We ignore sign extensions when it is safe to do so.
8470 /// The following two expressions are not equivalent. To differentiate we need
8471 /// to store whether there was a sign extension involved in the index
8472 /// computation.
8473 ///  (load (i64 add (i64 copyfromreg %c)
8474 ///                 (i64 signextend (add (i8 load %index)
8475 ///                                      (i8 1))))
8476 /// vs
8477 ///
8478 /// (load (i64 add (i64 copyfromreg %c)
8479 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8480 ///                                         (i32 1)))))
8481 struct BaseIndexOffset {
8482   SDValue Base;
8483   SDValue Index;
8484   int64_t Offset;
8485   bool IsIndexSignExt;
8486
8487   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8488
8489   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8490                   bool IsIndexSignExt) :
8491     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8492
8493   bool equalBaseIndex(const BaseIndexOffset &Other) {
8494     return Other.Base == Base && Other.Index == Index &&
8495       Other.IsIndexSignExt == IsIndexSignExt;
8496   }
8497
8498   /// Parses tree in Ptr for base, index, offset addresses.
8499   static BaseIndexOffset match(SDValue Ptr) {
8500     bool IsIndexSignExt = false;
8501
8502     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8503     // instruction, then it could be just the BASE or everything else we don't
8504     // know how to handle. Just use Ptr as BASE and give up.
8505     if (Ptr->getOpcode() != ISD::ADD)
8506       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8507
8508     // We know that we have at least an ADD instruction. Try to pattern match
8509     // the simple case of BASE + OFFSET.
8510     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8511       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8512       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8513                               IsIndexSignExt);
8514     }
8515
8516     // Inside a loop the current BASE pointer is calculated using an ADD and a
8517     // MUL instruction. In this case Ptr is the actual BASE pointer.
8518     // (i64 add (i64 %array_ptr)
8519     //          (i64 mul (i64 %induction_var)
8520     //                   (i64 %element_size)))
8521     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8522       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8523
8524     // Look at Base + Index + Offset cases.
8525     SDValue Base = Ptr->getOperand(0);
8526     SDValue IndexOffset = Ptr->getOperand(1);
8527
8528     // Skip signextends.
8529     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8530       IndexOffset = IndexOffset->getOperand(0);
8531       IsIndexSignExt = true;
8532     }
8533
8534     // Either the case of Base + Index (no offset) or something else.
8535     if (IndexOffset->getOpcode() != ISD::ADD)
8536       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8537
8538     // Now we have the case of Base + Index + offset.
8539     SDValue Index = IndexOffset->getOperand(0);
8540     SDValue Offset = IndexOffset->getOperand(1);
8541
8542     if (!isa<ConstantSDNode>(Offset))
8543       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8544
8545     // Ignore signextends.
8546     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8547       Index = Index->getOperand(0);
8548       IsIndexSignExt = true;
8549     } else IsIndexSignExt = false;
8550
8551     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8552     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8553   }
8554 };
8555
8556 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8557 /// is located in a sequence of memory operations connected by a chain.
8558 struct MemOpLink {
8559   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8560     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8561   // Ptr to the mem node.
8562   LSBaseSDNode *MemNode;
8563   // Offset from the base ptr.
8564   int64_t OffsetFromBase;
8565   // What is the sequence number of this mem node.
8566   // Lowest mem operand in the DAG starts at zero.
8567   unsigned SequenceNum;
8568 };
8569
8570 /// Sorts store nodes in a link according to their offset from a shared
8571 // base ptr.
8572 struct ConsecutiveMemoryChainSorter {
8573   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8574     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8575   }
8576 };
8577
8578 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8579   EVT MemVT = St->getMemoryVT();
8580   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8581   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8582     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8583
8584   // Don't merge vectors into wider inputs.
8585   if (MemVT.isVector() || !MemVT.isSimple())
8586     return false;
8587
8588   // Perform an early exit check. Do not bother looking at stored values that
8589   // are not constants or loads.
8590   SDValue StoredVal = St->getValue();
8591   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8592   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8593       !IsLoadSrc)
8594     return false;
8595
8596   // Only look at ends of store sequences.
8597   SDValue Chain = SDValue(St, 1);
8598   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8599     return false;
8600
8601   // This holds the base pointer, index, and the offset in bytes from the base
8602   // pointer.
8603   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8604
8605   // We must have a base and an offset.
8606   if (!BasePtr.Base.getNode())
8607     return false;
8608
8609   // Do not handle stores to undef base pointers.
8610   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8611     return false;
8612
8613   // Save the LoadSDNodes that we find in the chain.
8614   // We need to make sure that these nodes do not interfere with
8615   // any of the store nodes.
8616   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8617
8618   // Save the StoreSDNodes that we find in the chain.
8619   SmallVector<MemOpLink, 8> StoreNodes;
8620
8621   // Walk up the chain and look for nodes with offsets from the same
8622   // base pointer. Stop when reaching an instruction with a different kind
8623   // or instruction which has a different base pointer.
8624   unsigned Seq = 0;
8625   StoreSDNode *Index = St;
8626   while (Index) {
8627     // If the chain has more than one use, then we can't reorder the mem ops.
8628     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8629       break;
8630
8631     // Find the base pointer and offset for this memory node.
8632     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8633
8634     // Check that the base pointer is the same as the original one.
8635     if (!Ptr.equalBaseIndex(BasePtr))
8636       break;
8637
8638     // Check that the alignment is the same.
8639     if (Index->getAlignment() != St->getAlignment())
8640       break;
8641
8642     // The memory operands must not be volatile.
8643     if (Index->isVolatile() || Index->isIndexed())
8644       break;
8645
8646     // No truncation.
8647     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8648       if (St->isTruncatingStore())
8649         break;
8650
8651     // The stored memory type must be the same.
8652     if (Index->getMemoryVT() != MemVT)
8653       break;
8654
8655     // We do not allow unaligned stores because we want to prevent overriding
8656     // stores.
8657     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8658       break;
8659
8660     // We found a potential memory operand to merge.
8661     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8662
8663     // Find the next memory operand in the chain. If the next operand in the
8664     // chain is a store then move up and continue the scan with the next
8665     // memory operand. If the next operand is a load save it and use alias
8666     // information to check if it interferes with anything.
8667     SDNode *NextInChain = Index->getChain().getNode();
8668     while (1) {
8669       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8670         // We found a store node. Use it for the next iteration.
8671         Index = STn;
8672         break;
8673       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8674         // Save the load node for later. Continue the scan.
8675         AliasLoadNodes.push_back(Ldn);
8676         NextInChain = Ldn->getChain().getNode();
8677         continue;
8678       } else {
8679         Index = NULL;
8680         break;
8681       }
8682     }
8683   }
8684
8685   // Check if there is anything to merge.
8686   if (StoreNodes.size() < 2)
8687     return false;
8688
8689   // Sort the memory operands according to their distance from the base pointer.
8690   std::sort(StoreNodes.begin(), StoreNodes.end(),
8691             ConsecutiveMemoryChainSorter());
8692
8693   // Scan the memory operations on the chain and find the first non-consecutive
8694   // store memory address.
8695   unsigned LastConsecutiveStore = 0;
8696   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8697   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8698
8699     // Check that the addresses are consecutive starting from the second
8700     // element in the list of stores.
8701     if (i > 0) {
8702       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8703       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8704         break;
8705     }
8706
8707     bool Alias = false;
8708     // Check if this store interferes with any of the loads that we found.
8709     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8710       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8711         Alias = true;
8712         break;
8713       }
8714     // We found a load that alias with this store. Stop the sequence.
8715     if (Alias)
8716       break;
8717
8718     // Mark this node as useful.
8719     LastConsecutiveStore = i;
8720   }
8721
8722   // The node with the lowest store address.
8723   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8724
8725   // Store the constants into memory as one consecutive store.
8726   if (!IsLoadSrc) {
8727     unsigned LastLegalType = 0;
8728     unsigned LastLegalVectorType = 0;
8729     bool NonZero = false;
8730     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8731       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8732       SDValue StoredVal = St->getValue();
8733
8734       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8735         NonZero |= !C->isNullValue();
8736       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8737         NonZero |= !C->getConstantFPValue()->isNullValue();
8738       } else {
8739         // Non constant.
8740         break;
8741       }
8742
8743       // Find a legal type for the constant store.
8744       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8745       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8746       if (TLI.isTypeLegal(StoreTy))
8747         LastLegalType = i+1;
8748       // Or check whether a truncstore is legal.
8749       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8750                TargetLowering::TypePromoteInteger) {
8751         EVT LegalizedStoredValueTy =
8752           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8753         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8754           LastLegalType = i+1;
8755       }
8756
8757       // Find a legal type for the vector store.
8758       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8759       if (TLI.isTypeLegal(Ty))
8760         LastLegalVectorType = i + 1;
8761     }
8762
8763     // We only use vectors if the constant is known to be zero and the
8764     // function is not marked with the noimplicitfloat attribute.
8765     if (NonZero || NoVectors)
8766       LastLegalVectorType = 0;
8767
8768     // Check if we found a legal integer type to store.
8769     if (LastLegalType == 0 && LastLegalVectorType == 0)
8770       return false;
8771
8772     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8773     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8774
8775     // Make sure we have something to merge.
8776     if (NumElem < 2)
8777       return false;
8778
8779     unsigned EarliestNodeUsed = 0;
8780     for (unsigned i=0; i < NumElem; ++i) {
8781       // Find a chain for the new wide-store operand. Notice that some
8782       // of the store nodes that we found may not be selected for inclusion
8783       // in the wide store. The chain we use needs to be the chain of the
8784       // earliest store node which is *used* and replaced by the wide store.
8785       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8786         EarliestNodeUsed = i;
8787     }
8788
8789     // The earliest Node in the DAG.
8790     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8791     SDLoc DL(StoreNodes[0].MemNode);
8792
8793     SDValue StoredVal;
8794     if (UseVector) {
8795       // Find a legal type for the vector store.
8796       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8797       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8798       StoredVal = DAG.getConstant(0, Ty);
8799     } else {
8800       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8801       APInt StoreInt(StoreBW, 0);
8802
8803       // Construct a single integer constant which is made of the smaller
8804       // constant inputs.
8805       bool IsLE = TLI.isLittleEndian();
8806       for (unsigned i = 0; i < NumElem ; ++i) {
8807         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8808         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8809         SDValue Val = St->getValue();
8810         StoreInt<<=ElementSizeBytes*8;
8811         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8812           StoreInt|=C->getAPIntValue().zext(StoreBW);
8813         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8814           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8815         } else {
8816           assert(false && "Invalid constant element type");
8817         }
8818       }
8819
8820       // Create the new Load and Store operations.
8821       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8822       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8823     }
8824
8825     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8826                                     FirstInChain->getBasePtr(),
8827                                     FirstInChain->getPointerInfo(),
8828                                     false, false,
8829                                     FirstInChain->getAlignment());
8830
8831     // Replace the first store with the new store
8832     CombineTo(EarliestOp, NewStore);
8833     // Erase all other stores.
8834     for (unsigned i = 0; i < NumElem ; ++i) {
8835       if (StoreNodes[i].MemNode == EarliestOp)
8836         continue;
8837       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8838       // ReplaceAllUsesWith will replace all uses that existed when it was
8839       // called, but graph optimizations may cause new ones to appear. For
8840       // example, the case in pr14333 looks like
8841       //
8842       //  St's chain -> St -> another store -> X
8843       //
8844       // And the only difference from St to the other store is the chain.
8845       // When we change it's chain to be St's chain they become identical,
8846       // get CSEed and the net result is that X is now a use of St.
8847       // Since we know that St is redundant, just iterate.
8848       while (!St->use_empty())
8849         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8850       removeFromWorkList(St);
8851       DAG.DeleteNode(St);
8852     }
8853
8854     return true;
8855   }
8856
8857   // Below we handle the case of multiple consecutive stores that
8858   // come from multiple consecutive loads. We merge them into a single
8859   // wide load and a single wide store.
8860
8861   // Look for load nodes which are used by the stored values.
8862   SmallVector<MemOpLink, 8> LoadNodes;
8863
8864   // Find acceptable loads. Loads need to have the same chain (token factor),
8865   // must not be zext, volatile, indexed, and they must be consecutive.
8866   BaseIndexOffset LdBasePtr;
8867   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8868     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8869     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8870     if (!Ld) break;
8871
8872     // Loads must only have one use.
8873     if (!Ld->hasNUsesOfValue(1, 0))
8874       break;
8875
8876     // Check that the alignment is the same as the stores.
8877     if (Ld->getAlignment() != St->getAlignment())
8878       break;
8879
8880     // The memory operands must not be volatile.
8881     if (Ld->isVolatile() || Ld->isIndexed())
8882       break;
8883
8884     // We do not accept ext loads.
8885     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8886       break;
8887
8888     // The stored memory type must be the same.
8889     if (Ld->getMemoryVT() != MemVT)
8890       break;
8891
8892     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8893     // If this is not the first ptr that we check.
8894     if (LdBasePtr.Base.getNode()) {
8895       // The base ptr must be the same.
8896       if (!LdPtr.equalBaseIndex(LdBasePtr))
8897         break;
8898     } else {
8899       // Check that all other base pointers are the same as this one.
8900       LdBasePtr = LdPtr;
8901     }
8902
8903     // We found a potential memory operand to merge.
8904     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8905   }
8906
8907   if (LoadNodes.size() < 2)
8908     return false;
8909
8910   // Scan the memory operations on the chain and find the first non-consecutive
8911   // load memory address. These variables hold the index in the store node
8912   // array.
8913   unsigned LastConsecutiveLoad = 0;
8914   // This variable refers to the size and not index in the array.
8915   unsigned LastLegalVectorType = 0;
8916   unsigned LastLegalIntegerType = 0;
8917   StartAddress = LoadNodes[0].OffsetFromBase;
8918   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8919   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8920     // All loads much share the same chain.
8921     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8922       break;
8923
8924     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8925     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8926       break;
8927     LastConsecutiveLoad = i;
8928
8929     // Find a legal type for the vector store.
8930     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8931     if (TLI.isTypeLegal(StoreTy))
8932       LastLegalVectorType = i + 1;
8933
8934     // Find a legal type for the integer store.
8935     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8936     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8937     if (TLI.isTypeLegal(StoreTy))
8938       LastLegalIntegerType = i + 1;
8939     // Or check whether a truncstore and extload is legal.
8940     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8941              TargetLowering::TypePromoteInteger) {
8942       EVT LegalizedStoredValueTy =
8943         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8944       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8945           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8946           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8947           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8948         LastLegalIntegerType = i+1;
8949     }
8950   }
8951
8952   // Only use vector types if the vector type is larger than the integer type.
8953   // If they are the same, use integers.
8954   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8955   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8956
8957   // We add +1 here because the LastXXX variables refer to location while
8958   // the NumElem refers to array/index size.
8959   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8960   NumElem = std::min(LastLegalType, NumElem);
8961
8962   if (NumElem < 2)
8963     return false;
8964
8965   // The earliest Node in the DAG.
8966   unsigned EarliestNodeUsed = 0;
8967   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8968   for (unsigned i=1; i<NumElem; ++i) {
8969     // Find a chain for the new wide-store operand. Notice that some
8970     // of the store nodes that we found may not be selected for inclusion
8971     // in the wide store. The chain we use needs to be the chain of the
8972     // earliest store node which is *used* and replaced by the wide store.
8973     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8974       EarliestNodeUsed = i;
8975   }
8976
8977   // Find if it is better to use vectors or integers to load and store
8978   // to memory.
8979   EVT JointMemOpVT;
8980   if (UseVectorTy) {
8981     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8982   } else {
8983     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8984     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8985   }
8986
8987   SDLoc LoadDL(LoadNodes[0].MemNode);
8988   SDLoc StoreDL(StoreNodes[0].MemNode);
8989
8990   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8991   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8992                                 FirstLoad->getChain(),
8993                                 FirstLoad->getBasePtr(),
8994                                 FirstLoad->getPointerInfo(),
8995                                 false, false, false,
8996                                 FirstLoad->getAlignment());
8997
8998   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8999                                   FirstInChain->getBasePtr(),
9000                                   FirstInChain->getPointerInfo(), false, false,
9001                                   FirstInChain->getAlignment());
9002
9003   // Replace one of the loads with the new load.
9004   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9005   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9006                                 SDValue(NewLoad.getNode(), 1));
9007
9008   // Remove the rest of the load chains.
9009   for (unsigned i = 1; i < NumElem ; ++i) {
9010     // Replace all chain users of the old load nodes with the chain of the new
9011     // load node.
9012     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9013     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9014   }
9015
9016   // Replace the first store with the new store.
9017   CombineTo(EarliestOp, NewStore);
9018   // Erase all other stores.
9019   for (unsigned i = 0; i < NumElem ; ++i) {
9020     // Remove all Store nodes.
9021     if (StoreNodes[i].MemNode == EarliestOp)
9022       continue;
9023     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9024     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9025     removeFromWorkList(St);
9026     DAG.DeleteNode(St);
9027   }
9028
9029   return true;
9030 }
9031
9032 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9033   StoreSDNode *ST  = cast<StoreSDNode>(N);
9034   SDValue Chain = ST->getChain();
9035   SDValue Value = ST->getValue();
9036   SDValue Ptr   = ST->getBasePtr();
9037
9038   // If this is a store of a bit convert, store the input value if the
9039   // resultant store does not need a higher alignment than the original.
9040   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9041       ST->isUnindexed()) {
9042     unsigned OrigAlign = ST->getAlignment();
9043     EVT SVT = Value.getOperand(0).getValueType();
9044     unsigned Align = TLI.getDataLayout()->
9045       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9046     if (Align <= OrigAlign &&
9047         ((!LegalOperations && !ST->isVolatile()) ||
9048          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9049       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9050                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9051                           ST->isNonTemporal(), OrigAlign);
9052   }
9053
9054   // Turn 'store undef, Ptr' -> nothing.
9055   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9056     return Chain;
9057
9058   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9059   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9060     // NOTE: If the original store is volatile, this transform must not increase
9061     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9062     // processor operation but an i64 (which is not legal) requires two.  So the
9063     // transform should not be done in this case.
9064     if (Value.getOpcode() != ISD::TargetConstantFP) {
9065       SDValue Tmp;
9066       switch (CFP->getSimpleValueType(0).SimpleTy) {
9067       default: llvm_unreachable("Unknown FP type");
9068       case MVT::f16:    // We don't do this for these yet.
9069       case MVT::f80:
9070       case MVT::f128:
9071       case MVT::ppcf128:
9072         break;
9073       case MVT::f32:
9074         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9075             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9076           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9077                               bitcastToAPInt().getZExtValue(), MVT::i32);
9078           return DAG.getStore(Chain, SDLoc(N), Tmp,
9079                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
9080                               ST->isNonTemporal(), ST->getAlignment());
9081         }
9082         break;
9083       case MVT::f64:
9084         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9085              !ST->isVolatile()) ||
9086             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9087           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9088                                 getZExtValue(), MVT::i64);
9089           return DAG.getStore(Chain, SDLoc(N), Tmp,
9090                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
9091                               ST->isNonTemporal(), ST->getAlignment());
9092         }
9093
9094         if (!ST->isVolatile() &&
9095             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9096           // Many FP stores are not made apparent until after legalize, e.g. for
9097           // argument passing.  Since this is so common, custom legalize the
9098           // 64-bit integer store into two 32-bit stores.
9099           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9100           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9101           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9102           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9103
9104           unsigned Alignment = ST->getAlignment();
9105           bool isVolatile = ST->isVolatile();
9106           bool isNonTemporal = ST->isNonTemporal();
9107
9108           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9109                                      Ptr, ST->getPointerInfo(),
9110                                      isVolatile, isNonTemporal,
9111                                      ST->getAlignment());
9112           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9113                             DAG.getConstant(4, Ptr.getValueType()));
9114           Alignment = MinAlign(Alignment, 4U);
9115           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9116                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9117                                      isVolatile, isNonTemporal,
9118                                      Alignment);
9119           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9120                              St0, St1);
9121         }
9122
9123         break;
9124       }
9125     }
9126   }
9127
9128   // Try to infer better alignment information than the store already has.
9129   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9130     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9131       if (Align > ST->getAlignment())
9132         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9133                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9134                                  ST->isVolatile(), ST->isNonTemporal(), Align);
9135     }
9136   }
9137
9138   // Try transforming a pair floating point load / store ops to integer
9139   // load / store ops.
9140   SDValue NewST = TransformFPLoadStorePair(N);
9141   if (NewST.getNode())
9142     return NewST;
9143
9144   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9145     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9146   if (UseAA) {
9147     // Walk up chain skipping non-aliasing memory nodes.
9148     SDValue BetterChain = FindBetterChain(N, Chain);
9149
9150     // If there is a better chain.
9151     if (Chain != BetterChain) {
9152       SDValue ReplStore;
9153
9154       // Replace the chain to avoid dependency.
9155       if (ST->isTruncatingStore()) {
9156         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9157                                       ST->getPointerInfo(),
9158                                       ST->getMemoryVT(), ST->isVolatile(),
9159                                       ST->isNonTemporal(), ST->getAlignment());
9160       } else {
9161         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9162                                  ST->getPointerInfo(),
9163                                  ST->isVolatile(), ST->isNonTemporal(),
9164                                  ST->getAlignment());
9165       }
9166
9167       // Create token to keep both nodes around.
9168       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9169                                   MVT::Other, Chain, ReplStore);
9170
9171       // Make sure the new and old chains are cleaned up.
9172       AddToWorkList(Token.getNode());
9173
9174       // Don't add users to work list.
9175       return CombineTo(N, Token, false);
9176     }
9177   }
9178
9179   // Try transforming N to an indexed store.
9180   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9181     return SDValue(N, 0);
9182
9183   // FIXME: is there such a thing as a truncating indexed store?
9184   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9185       Value.getValueType().isInteger()) {
9186     // See if we can simplify the input to this truncstore with knowledge that
9187     // only the low bits are being used.  For example:
9188     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9189     SDValue Shorter =
9190       GetDemandedBits(Value,
9191                       APInt::getLowBitsSet(
9192                         Value.getValueType().getScalarType().getSizeInBits(),
9193                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9194     AddToWorkList(Value.getNode());
9195     if (Shorter.getNode())
9196       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9197                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9198                                ST->isVolatile(), ST->isNonTemporal(),
9199                                ST->getAlignment());
9200
9201     // Otherwise, see if we can simplify the operation with
9202     // SimplifyDemandedBits, which only works if the value has a single use.
9203     if (SimplifyDemandedBits(Value,
9204                         APInt::getLowBitsSet(
9205                           Value.getValueType().getScalarType().getSizeInBits(),
9206                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9207       return SDValue(N, 0);
9208   }
9209
9210   // If this is a load followed by a store to the same location, then the store
9211   // is dead/noop.
9212   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9213     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9214         ST->isUnindexed() && !ST->isVolatile() &&
9215         // There can't be any side effects between the load and store, such as
9216         // a call or store.
9217         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9218       // The store is dead, remove it.
9219       return Chain;
9220     }
9221   }
9222
9223   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9224   // truncating store.  We can do this even if this is already a truncstore.
9225   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9226       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9227       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9228                             ST->getMemoryVT())) {
9229     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9230                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9231                              ST->isVolatile(), ST->isNonTemporal(),
9232                              ST->getAlignment());
9233   }
9234
9235   // Only perform this optimization before the types are legal, because we
9236   // don't want to perform this optimization on every DAGCombine invocation.
9237   if (!LegalTypes) {
9238     bool EverChanged = false;
9239
9240     do {
9241       // There can be multiple store sequences on the same chain.
9242       // Keep trying to merge store sequences until we are unable to do so
9243       // or until we merge the last store on the chain.
9244       bool Changed = MergeConsecutiveStores(ST);
9245       EverChanged |= Changed;
9246       if (!Changed) break;
9247     } while (ST->getOpcode() != ISD::DELETED_NODE);
9248
9249     if (EverChanged)
9250       return SDValue(N, 0);
9251   }
9252
9253   return ReduceLoadOpStoreWidth(N);
9254 }
9255
9256 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9257   SDValue InVec = N->getOperand(0);
9258   SDValue InVal = N->getOperand(1);
9259   SDValue EltNo = N->getOperand(2);
9260   SDLoc dl(N);
9261
9262   // If the inserted element is an UNDEF, just use the input vector.
9263   if (InVal.getOpcode() == ISD::UNDEF)
9264     return InVec;
9265
9266   EVT VT = InVec.getValueType();
9267
9268   // If we can't generate a legal BUILD_VECTOR, exit
9269   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9270     return SDValue();
9271
9272   // Check that we know which element is being inserted
9273   if (!isa<ConstantSDNode>(EltNo))
9274     return SDValue();
9275   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9276
9277   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9278   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9279   // vector elements.
9280   SmallVector<SDValue, 8> Ops;
9281   // Do not combine these two vectors if the output vector will not replace
9282   // the input vector.
9283   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9284     Ops.append(InVec.getNode()->op_begin(),
9285                InVec.getNode()->op_end());
9286   } else if (InVec.getOpcode() == ISD::UNDEF) {
9287     unsigned NElts = VT.getVectorNumElements();
9288     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9289   } else {
9290     return SDValue();
9291   }
9292
9293   // Insert the element
9294   if (Elt < Ops.size()) {
9295     // All the operands of BUILD_VECTOR must have the same type;
9296     // we enforce that here.
9297     EVT OpVT = Ops[0].getValueType();
9298     if (InVal.getValueType() != OpVT)
9299       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9300                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9301                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9302     Ops[Elt] = InVal;
9303   }
9304
9305   // Return the new vector
9306   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9307                      VT, &Ops[0], Ops.size());
9308 }
9309
9310 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9311   // (vextract (scalar_to_vector val, 0) -> val
9312   SDValue InVec = N->getOperand(0);
9313   EVT VT = InVec.getValueType();
9314   EVT NVT = N->getValueType(0);
9315
9316   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9317     // Check if the result type doesn't match the inserted element type. A
9318     // SCALAR_TO_VECTOR may truncate the inserted element and the
9319     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9320     SDValue InOp = InVec.getOperand(0);
9321     if (InOp.getValueType() != NVT) {
9322       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9323       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9324     }
9325     return InOp;
9326   }
9327
9328   SDValue EltNo = N->getOperand(1);
9329   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9330
9331   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9332   // We only perform this optimization before the op legalization phase because
9333   // we may introduce new vector instructions which are not backed by TD
9334   // patterns. For example on AVX, extracting elements from a wide vector
9335   // without using extract_subvector.
9336   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9337       && ConstEltNo && !LegalOperations) {
9338     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9339     int NumElem = VT.getVectorNumElements();
9340     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9341     // Find the new index to extract from.
9342     int OrigElt = SVOp->getMaskElt(Elt);
9343
9344     // Extracting an undef index is undef.
9345     if (OrigElt == -1)
9346       return DAG.getUNDEF(NVT);
9347
9348     // Select the right vector half to extract from.
9349     if (OrigElt < NumElem) {
9350       InVec = InVec->getOperand(0);
9351     } else {
9352       InVec = InVec->getOperand(1);
9353       OrigElt -= NumElem;
9354     }
9355
9356     EVT IndexTy = TLI.getVectorIdxTy();
9357     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9358                        InVec, DAG.getConstant(OrigElt, IndexTy));
9359   }
9360
9361   // Perform only after legalization to ensure build_vector / vector_shuffle
9362   // optimizations have already been done.
9363   if (!LegalOperations) return SDValue();
9364
9365   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9366   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9367   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9368
9369   if (ConstEltNo) {
9370     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9371     bool NewLoad = false;
9372     bool BCNumEltsChanged = false;
9373     EVT ExtVT = VT.getVectorElementType();
9374     EVT LVT = ExtVT;
9375
9376     // If the result of load has to be truncated, then it's not necessarily
9377     // profitable.
9378     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9379       return SDValue();
9380
9381     if (InVec.getOpcode() == ISD::BITCAST) {
9382       // Don't duplicate a load with other uses.
9383       if (!InVec.hasOneUse())
9384         return SDValue();
9385
9386       EVT BCVT = InVec.getOperand(0).getValueType();
9387       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9388         return SDValue();
9389       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9390         BCNumEltsChanged = true;
9391       InVec = InVec.getOperand(0);
9392       ExtVT = BCVT.getVectorElementType();
9393       NewLoad = true;
9394     }
9395
9396     LoadSDNode *LN0 = NULL;
9397     const ShuffleVectorSDNode *SVN = NULL;
9398     if (ISD::isNormalLoad(InVec.getNode())) {
9399       LN0 = cast<LoadSDNode>(InVec);
9400     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9401                InVec.getOperand(0).getValueType() == ExtVT &&
9402                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9403       // Don't duplicate a load with other uses.
9404       if (!InVec.hasOneUse())
9405         return SDValue();
9406
9407       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9408     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9409       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9410       // =>
9411       // (load $addr+1*size)
9412
9413       // Don't duplicate a load with other uses.
9414       if (!InVec.hasOneUse())
9415         return SDValue();
9416
9417       // If the bit convert changed the number of elements, it is unsafe
9418       // to examine the mask.
9419       if (BCNumEltsChanged)
9420         return SDValue();
9421
9422       // Select the input vector, guarding against out of range extract vector.
9423       unsigned NumElems = VT.getVectorNumElements();
9424       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9425       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9426
9427       if (InVec.getOpcode() == ISD::BITCAST) {
9428         // Don't duplicate a load with other uses.
9429         if (!InVec.hasOneUse())
9430           return SDValue();
9431
9432         InVec = InVec.getOperand(0);
9433       }
9434       if (ISD::isNormalLoad(InVec.getNode())) {
9435         LN0 = cast<LoadSDNode>(InVec);
9436         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9437       }
9438     }
9439
9440     // Make sure we found a non-volatile load and the extractelement is
9441     // the only use.
9442     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9443       return SDValue();
9444
9445     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9446     if (Elt == -1)
9447       return DAG.getUNDEF(LVT);
9448
9449     unsigned Align = LN0->getAlignment();
9450     if (NewLoad) {
9451       // Check the resultant load doesn't need a higher alignment than the
9452       // original load.
9453       unsigned NewAlign =
9454         TLI.getDataLayout()
9455             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9456
9457       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9458         return SDValue();
9459
9460       Align = NewAlign;
9461     }
9462
9463     SDValue NewPtr = LN0->getBasePtr();
9464     unsigned PtrOff = 0;
9465
9466     if (Elt) {
9467       PtrOff = LVT.getSizeInBits() * Elt / 8;
9468       EVT PtrType = NewPtr.getValueType();
9469       if (TLI.isBigEndian())
9470         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9471       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9472                            DAG.getConstant(PtrOff, PtrType));
9473     }
9474
9475     // The replacement we need to do here is a little tricky: we need to
9476     // replace an extractelement of a load with a load.
9477     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9478     // Note that this replacement assumes that the extractvalue is the only
9479     // use of the load; that's okay because we don't want to perform this
9480     // transformation in other cases anyway.
9481     SDValue Load;
9482     SDValue Chain;
9483     if (NVT.bitsGT(LVT)) {
9484       // If the result type of vextract is wider than the load, then issue an
9485       // extending load instead.
9486       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9487         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9488       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9489                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9490                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
9491       Chain = Load.getValue(1);
9492     } else {
9493       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9494                          LN0->getPointerInfo().getWithOffset(PtrOff),
9495                          LN0->isVolatile(), LN0->isNonTemporal(),
9496                          LN0->isInvariant(), Align);
9497       Chain = Load.getValue(1);
9498       if (NVT.bitsLT(LVT))
9499         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9500       else
9501         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9502     }
9503     WorkListRemover DeadNodes(*this);
9504     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9505     SDValue To[] = { Load, Chain };
9506     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9507     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9508     // worklist explicitly as well.
9509     AddToWorkList(Load.getNode());
9510     AddUsersToWorkList(Load.getNode()); // Add users too
9511     // Make sure to revisit this node to clean it up; it will usually be dead.
9512     AddToWorkList(N);
9513     return SDValue(N, 0);
9514   }
9515
9516   return SDValue();
9517 }
9518
9519 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9520 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9521   // We perform this optimization post type-legalization because
9522   // the type-legalizer often scalarizes integer-promoted vectors.
9523   // Performing this optimization before may create bit-casts which
9524   // will be type-legalized to complex code sequences.
9525   // We perform this optimization only before the operation legalizer because we
9526   // may introduce illegal operations.
9527   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9528     return SDValue();
9529
9530   unsigned NumInScalars = N->getNumOperands();
9531   SDLoc dl(N);
9532   EVT VT = N->getValueType(0);
9533
9534   // Check to see if this is a BUILD_VECTOR of a bunch of values
9535   // which come from any_extend or zero_extend nodes. If so, we can create
9536   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9537   // optimizations. We do not handle sign-extend because we can't fill the sign
9538   // using shuffles.
9539   EVT SourceType = MVT::Other;
9540   bool AllAnyExt = true;
9541
9542   for (unsigned i = 0; i != NumInScalars; ++i) {
9543     SDValue In = N->getOperand(i);
9544     // Ignore undef inputs.
9545     if (In.getOpcode() == ISD::UNDEF) continue;
9546
9547     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9548     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9549
9550     // Abort if the element is not an extension.
9551     if (!ZeroExt && !AnyExt) {
9552       SourceType = MVT::Other;
9553       break;
9554     }
9555
9556     // The input is a ZeroExt or AnyExt. Check the original type.
9557     EVT InTy = In.getOperand(0).getValueType();
9558
9559     // Check that all of the widened source types are the same.
9560     if (SourceType == MVT::Other)
9561       // First time.
9562       SourceType = InTy;
9563     else if (InTy != SourceType) {
9564       // Multiple income types. Abort.
9565       SourceType = MVT::Other;
9566       break;
9567     }
9568
9569     // Check if all of the extends are ANY_EXTENDs.
9570     AllAnyExt &= AnyExt;
9571   }
9572
9573   // In order to have valid types, all of the inputs must be extended from the
9574   // same source type and all of the inputs must be any or zero extend.
9575   // Scalar sizes must be a power of two.
9576   EVT OutScalarTy = VT.getScalarType();
9577   bool ValidTypes = SourceType != MVT::Other &&
9578                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9579                  isPowerOf2_32(SourceType.getSizeInBits());
9580
9581   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9582   // turn into a single shuffle instruction.
9583   if (!ValidTypes)
9584     return SDValue();
9585
9586   bool isLE = TLI.isLittleEndian();
9587   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9588   assert(ElemRatio > 1 && "Invalid element size ratio");
9589   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9590                                DAG.getConstant(0, SourceType);
9591
9592   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9593   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9594
9595   // Populate the new build_vector
9596   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9597     SDValue Cast = N->getOperand(i);
9598     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9599             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9600             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9601     SDValue In;
9602     if (Cast.getOpcode() == ISD::UNDEF)
9603       In = DAG.getUNDEF(SourceType);
9604     else
9605       In = Cast->getOperand(0);
9606     unsigned Index = isLE ? (i * ElemRatio) :
9607                             (i * ElemRatio + (ElemRatio - 1));
9608
9609     assert(Index < Ops.size() && "Invalid index");
9610     Ops[Index] = In;
9611   }
9612
9613   // The type of the new BUILD_VECTOR node.
9614   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9615   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9616          "Invalid vector size");
9617   // Check if the new vector type is legal.
9618   if (!isTypeLegal(VecVT)) return SDValue();
9619
9620   // Make the new BUILD_VECTOR.
9621   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9622
9623   // The new BUILD_VECTOR node has the potential to be further optimized.
9624   AddToWorkList(BV.getNode());
9625   // Bitcast to the desired type.
9626   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9627 }
9628
9629 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9630   EVT VT = N->getValueType(0);
9631
9632   unsigned NumInScalars = N->getNumOperands();
9633   SDLoc dl(N);
9634
9635   EVT SrcVT = MVT::Other;
9636   unsigned Opcode = ISD::DELETED_NODE;
9637   unsigned NumDefs = 0;
9638
9639   for (unsigned i = 0; i != NumInScalars; ++i) {
9640     SDValue In = N->getOperand(i);
9641     unsigned Opc = In.getOpcode();
9642
9643     if (Opc == ISD::UNDEF)
9644       continue;
9645
9646     // If all scalar values are floats and converted from integers.
9647     if (Opcode == ISD::DELETED_NODE &&
9648         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9649       Opcode = Opc;
9650     }
9651
9652     if (Opc != Opcode)
9653       return SDValue();
9654
9655     EVT InVT = In.getOperand(0).getValueType();
9656
9657     // If all scalar values are typed differently, bail out. It's chosen to
9658     // simplify BUILD_VECTOR of integer types.
9659     if (SrcVT == MVT::Other)
9660       SrcVT = InVT;
9661     if (SrcVT != InVT)
9662       return SDValue();
9663     NumDefs++;
9664   }
9665
9666   // If the vector has just one element defined, it's not worth to fold it into
9667   // a vectorized one.
9668   if (NumDefs < 2)
9669     return SDValue();
9670
9671   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9672          && "Should only handle conversion from integer to float.");
9673   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9674
9675   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9676
9677   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9678     return SDValue();
9679
9680   SmallVector<SDValue, 8> Opnds;
9681   for (unsigned i = 0; i != NumInScalars; ++i) {
9682     SDValue In = N->getOperand(i);
9683
9684     if (In.getOpcode() == ISD::UNDEF)
9685       Opnds.push_back(DAG.getUNDEF(SrcVT));
9686     else
9687       Opnds.push_back(In.getOperand(0));
9688   }
9689   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9690                            &Opnds[0], Opnds.size());
9691   AddToWorkList(BV.getNode());
9692
9693   return DAG.getNode(Opcode, dl, VT, BV);
9694 }
9695
9696 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9697   unsigned NumInScalars = N->getNumOperands();
9698   SDLoc dl(N);
9699   EVT VT = N->getValueType(0);
9700
9701   // A vector built entirely of undefs is undef.
9702   if (ISD::allOperandsUndef(N))
9703     return DAG.getUNDEF(VT);
9704
9705   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9706   if (V.getNode())
9707     return V;
9708
9709   V = reduceBuildVecConvertToConvertBuildVec(N);
9710   if (V.getNode())
9711     return V;
9712
9713   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9714   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9715   // at most two distinct vectors, turn this into a shuffle node.
9716
9717   // May only combine to shuffle after legalize if shuffle is legal.
9718   if (LegalOperations &&
9719       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9720     return SDValue();
9721
9722   SDValue VecIn1, VecIn2;
9723   for (unsigned i = 0; i != NumInScalars; ++i) {
9724     // Ignore undef inputs.
9725     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9726
9727     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9728     // constant index, bail out.
9729     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9730         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9731       VecIn1 = VecIn2 = SDValue(0, 0);
9732       break;
9733     }
9734
9735     // We allow up to two distinct input vectors.
9736     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9737     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9738       continue;
9739
9740     if (VecIn1.getNode() == 0) {
9741       VecIn1 = ExtractedFromVec;
9742     } else if (VecIn2.getNode() == 0) {
9743       VecIn2 = ExtractedFromVec;
9744     } else {
9745       // Too many inputs.
9746       VecIn1 = VecIn2 = SDValue(0, 0);
9747       break;
9748     }
9749   }
9750
9751     // If everything is good, we can make a shuffle operation.
9752   if (VecIn1.getNode()) {
9753     SmallVector<int, 8> Mask;
9754     for (unsigned i = 0; i != NumInScalars; ++i) {
9755       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9756         Mask.push_back(-1);
9757         continue;
9758       }
9759
9760       // If extracting from the first vector, just use the index directly.
9761       SDValue Extract = N->getOperand(i);
9762       SDValue ExtVal = Extract.getOperand(1);
9763       if (Extract.getOperand(0) == VecIn1) {
9764         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9765         if (ExtIndex > VT.getVectorNumElements())
9766           return SDValue();
9767
9768         Mask.push_back(ExtIndex);
9769         continue;
9770       }
9771
9772       // Otherwise, use InIdx + VecSize
9773       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9774       Mask.push_back(Idx+NumInScalars);
9775     }
9776
9777     // We can't generate a shuffle node with mismatched input and output types.
9778     // Attempt to transform a single input vector to the correct type.
9779     if ((VT != VecIn1.getValueType())) {
9780       // We don't support shuffeling between TWO values of different types.
9781       if (VecIn2.getNode() != 0)
9782         return SDValue();
9783
9784       // We only support widening of vectors which are half the size of the
9785       // output registers. For example XMM->YMM widening on X86 with AVX.
9786       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9787         return SDValue();
9788
9789       // If the input vector type has a different base type to the output
9790       // vector type, bail out.
9791       if (VecIn1.getValueType().getVectorElementType() !=
9792           VT.getVectorElementType())
9793         return SDValue();
9794
9795       // Widen the input vector by adding undef values.
9796       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9797                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9798     }
9799
9800     // If VecIn2 is unused then change it to undef.
9801     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9802
9803     // Check that we were able to transform all incoming values to the same
9804     // type.
9805     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9806         VecIn1.getValueType() != VT)
9807           return SDValue();
9808
9809     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9810     if (!isTypeLegal(VT))
9811       return SDValue();
9812
9813     // Return the new VECTOR_SHUFFLE node.
9814     SDValue Ops[2];
9815     Ops[0] = VecIn1;
9816     Ops[1] = VecIn2;
9817     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9818   }
9819
9820   return SDValue();
9821 }
9822
9823 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9824   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9825   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9826   // inputs come from at most two distinct vectors, turn this into a shuffle
9827   // node.
9828
9829   // If we only have one input vector, we don't need to do any concatenation.
9830   if (N->getNumOperands() == 1)
9831     return N->getOperand(0);
9832
9833   // Check if all of the operands are undefs.
9834   if (ISD::allOperandsUndef(N))
9835     return DAG.getUNDEF(N->getValueType(0));
9836
9837   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9838   // nodes often generate nop CONCAT_VECTOR nodes.
9839   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9840   // place the incoming vectors at the exact same location.
9841   SDValue SingleSource = SDValue();
9842   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9843
9844   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9845     SDValue Op = N->getOperand(i);
9846
9847     if (Op.getOpcode() == ISD::UNDEF)
9848       continue;
9849
9850     // Check if this is the identity extract:
9851     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9852       return SDValue();
9853
9854     // Find the single incoming vector for the extract_subvector.
9855     if (SingleSource.getNode()) {
9856       if (Op.getOperand(0) != SingleSource)
9857         return SDValue();
9858     } else {
9859       SingleSource = Op.getOperand(0);
9860
9861       // Check the source type is the same as the type of the result.
9862       // If not, this concat may extend the vector, so we can not
9863       // optimize it away.
9864       if (SingleSource.getValueType() != N->getValueType(0))
9865         return SDValue();
9866     }
9867
9868     unsigned IdentityIndex = i * PartNumElem;
9869     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9870     // The extract index must be constant.
9871     if (!CS)
9872       return SDValue();
9873
9874     // Check that we are reading from the identity index.
9875     if (CS->getZExtValue() != IdentityIndex)
9876       return SDValue();
9877   }
9878
9879   if (SingleSource.getNode())
9880     return SingleSource;
9881
9882   return SDValue();
9883 }
9884
9885 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9886   EVT NVT = N->getValueType(0);
9887   SDValue V = N->getOperand(0);
9888
9889   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9890     // Combine:
9891     //    (extract_subvec (concat V1, V2, ...), i)
9892     // Into:
9893     //    Vi if possible
9894     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9895     if (V->getOperand(0).getValueType() != NVT)
9896       return SDValue();
9897     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9898     unsigned NumElems = NVT.getVectorNumElements();
9899     assert((Idx % NumElems) == 0 &&
9900            "IDX in concat is not a multiple of the result vector length.");
9901     return V->getOperand(Idx / NumElems);
9902   }
9903
9904   // Skip bitcasting
9905   if (V->getOpcode() == ISD::BITCAST)
9906     V = V.getOperand(0);
9907
9908   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9909     SDLoc dl(N);
9910     // Handle only simple case where vector being inserted and vector
9911     // being extracted are of same type, and are half size of larger vectors.
9912     EVT BigVT = V->getOperand(0).getValueType();
9913     EVT SmallVT = V->getOperand(1).getValueType();
9914     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9915       return SDValue();
9916
9917     // Only handle cases where both indexes are constants with the same type.
9918     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9919     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9920
9921     if (InsIdx && ExtIdx &&
9922         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9923         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9924       // Combine:
9925       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9926       // Into:
9927       //    indices are equal or bit offsets are equal => V1
9928       //    otherwise => (extract_subvec V1, ExtIdx)
9929       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9930           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9931         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9932       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9933                          DAG.getNode(ISD::BITCAST, dl,
9934                                      N->getOperand(0).getValueType(),
9935                                      V->getOperand(0)), N->getOperand(1));
9936     }
9937   }
9938
9939   return SDValue();
9940 }
9941
9942 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9943 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9944   EVT VT = N->getValueType(0);
9945   unsigned NumElts = VT.getVectorNumElements();
9946
9947   SDValue N0 = N->getOperand(0);
9948   SDValue N1 = N->getOperand(1);
9949   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9950
9951   SmallVector<SDValue, 4> Ops;
9952   EVT ConcatVT = N0.getOperand(0).getValueType();
9953   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9954   unsigned NumConcats = NumElts / NumElemsPerConcat;
9955
9956   // Look at every vector that's inserted. We're looking for exact
9957   // subvector-sized copies from a concatenated vector
9958   for (unsigned I = 0; I != NumConcats; ++I) {
9959     // Make sure we're dealing with a copy.
9960     unsigned Begin = I * NumElemsPerConcat;
9961     bool AllUndef = true, NoUndef = true;
9962     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9963       if (SVN->getMaskElt(J) >= 0)
9964         AllUndef = false;
9965       else
9966         NoUndef = false;
9967     }
9968
9969     if (NoUndef) {
9970       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9971         return SDValue();
9972
9973       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9974         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9975           return SDValue();
9976
9977       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9978       if (FirstElt < N0.getNumOperands())
9979         Ops.push_back(N0.getOperand(FirstElt));
9980       else
9981         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9982
9983     } else if (AllUndef) {
9984       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9985     } else { // Mixed with general masks and undefs, can't do optimization.
9986       return SDValue();
9987     }
9988   }
9989
9990   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9991                      Ops.size());
9992 }
9993
9994 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9995   EVT VT = N->getValueType(0);
9996   unsigned NumElts = VT.getVectorNumElements();
9997
9998   SDValue N0 = N->getOperand(0);
9999   SDValue N1 = N->getOperand(1);
10000
10001   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10002
10003   // Canonicalize shuffle undef, undef -> undef
10004   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10005     return DAG.getUNDEF(VT);
10006
10007   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10008
10009   // Canonicalize shuffle v, v -> v, undef
10010   if (N0 == N1) {
10011     SmallVector<int, 8> NewMask;
10012     for (unsigned i = 0; i != NumElts; ++i) {
10013       int Idx = SVN->getMaskElt(i);
10014       if (Idx >= (int)NumElts) Idx -= NumElts;
10015       NewMask.push_back(Idx);
10016     }
10017     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10018                                 &NewMask[0]);
10019   }
10020
10021   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10022   if (N0.getOpcode() == ISD::UNDEF) {
10023     SmallVector<int, 8> NewMask;
10024     for (unsigned i = 0; i != NumElts; ++i) {
10025       int Idx = SVN->getMaskElt(i);
10026       if (Idx >= 0) {
10027         if (Idx >= (int)NumElts)
10028           Idx -= NumElts;
10029         else
10030           Idx = -1; // remove reference to lhs
10031       }
10032       NewMask.push_back(Idx);
10033     }
10034     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10035                                 &NewMask[0]);
10036   }
10037
10038   // Remove references to rhs if it is undef
10039   if (N1.getOpcode() == ISD::UNDEF) {
10040     bool Changed = false;
10041     SmallVector<int, 8> NewMask;
10042     for (unsigned i = 0; i != NumElts; ++i) {
10043       int Idx = SVN->getMaskElt(i);
10044       if (Idx >= (int)NumElts) {
10045         Idx = -1;
10046         Changed = true;
10047       }
10048       NewMask.push_back(Idx);
10049     }
10050     if (Changed)
10051       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10052   }
10053
10054   // If it is a splat, check if the argument vector is another splat or a
10055   // build_vector with all scalar elements the same.
10056   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10057     SDNode *V = N0.getNode();
10058
10059     // If this is a bit convert that changes the element type of the vector but
10060     // not the number of vector elements, look through it.  Be careful not to
10061     // look though conversions that change things like v4f32 to v2f64.
10062     if (V->getOpcode() == ISD::BITCAST) {
10063       SDValue ConvInput = V->getOperand(0);
10064       if (ConvInput.getValueType().isVector() &&
10065           ConvInput.getValueType().getVectorNumElements() == NumElts)
10066         V = ConvInput.getNode();
10067     }
10068
10069     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10070       assert(V->getNumOperands() == NumElts &&
10071              "BUILD_VECTOR has wrong number of operands");
10072       SDValue Base;
10073       bool AllSame = true;
10074       for (unsigned i = 0; i != NumElts; ++i) {
10075         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10076           Base = V->getOperand(i);
10077           break;
10078         }
10079       }
10080       // Splat of <u, u, u, u>, return <u, u, u, u>
10081       if (!Base.getNode())
10082         return N0;
10083       for (unsigned i = 0; i != NumElts; ++i) {
10084         if (V->getOperand(i) != Base) {
10085           AllSame = false;
10086           break;
10087         }
10088       }
10089       // Splat of <x, x, x, x>, return <x, x, x, x>
10090       if (AllSame)
10091         return N0;
10092     }
10093   }
10094
10095   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10096       Level < AfterLegalizeVectorOps &&
10097       (N1.getOpcode() == ISD::UNDEF ||
10098       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10099        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10100     SDValue V = partitionShuffleOfConcats(N, DAG);
10101
10102     if (V.getNode())
10103       return V;
10104   }
10105
10106   // If this shuffle node is simply a swizzle of another shuffle node,
10107   // and it reverses the swizzle of the previous shuffle then we can
10108   // optimize shuffle(shuffle(x, undef), undef) -> x.
10109   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10110       N1.getOpcode() == ISD::UNDEF) {
10111
10112     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10113
10114     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10115     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10116       return SDValue();
10117
10118     // The incoming shuffle must be of the same type as the result of the
10119     // current shuffle.
10120     assert(OtherSV->getOperand(0).getValueType() == VT &&
10121            "Shuffle types don't match");
10122
10123     for (unsigned i = 0; i != NumElts; ++i) {
10124       int Idx = SVN->getMaskElt(i);
10125       assert(Idx < (int)NumElts && "Index references undef operand");
10126       // Next, this index comes from the first value, which is the incoming
10127       // shuffle. Adopt the incoming index.
10128       if (Idx >= 0)
10129         Idx = OtherSV->getMaskElt(Idx);
10130
10131       // The combined shuffle must map each index to itself.
10132       if (Idx >= 0 && (unsigned)Idx != i)
10133         return SDValue();
10134     }
10135
10136     return OtherSV->getOperand(0);
10137   }
10138
10139   return SDValue();
10140 }
10141
10142 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10143 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10144 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10145 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10146 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10147   EVT VT = N->getValueType(0);
10148   SDLoc dl(N);
10149   SDValue LHS = N->getOperand(0);
10150   SDValue RHS = N->getOperand(1);
10151   if (N->getOpcode() == ISD::AND) {
10152     if (RHS.getOpcode() == ISD::BITCAST)
10153       RHS = RHS.getOperand(0);
10154     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10155       SmallVector<int, 8> Indices;
10156       unsigned NumElts = RHS.getNumOperands();
10157       for (unsigned i = 0; i != NumElts; ++i) {
10158         SDValue Elt = RHS.getOperand(i);
10159         if (!isa<ConstantSDNode>(Elt))
10160           return SDValue();
10161
10162         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10163           Indices.push_back(i);
10164         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10165           Indices.push_back(NumElts);
10166         else
10167           return SDValue();
10168       }
10169
10170       // Let's see if the target supports this vector_shuffle.
10171       EVT RVT = RHS.getValueType();
10172       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10173         return SDValue();
10174
10175       // Return the new VECTOR_SHUFFLE node.
10176       EVT EltVT = RVT.getVectorElementType();
10177       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10178                                      DAG.getConstant(0, EltVT));
10179       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10180                                  RVT, &ZeroOps[0], ZeroOps.size());
10181       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10182       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10183       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10184     }
10185   }
10186
10187   return SDValue();
10188 }
10189
10190 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10191 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10192   assert(N->getValueType(0).isVector() &&
10193          "SimplifyVBinOp only works on vectors!");
10194
10195   SDValue LHS = N->getOperand(0);
10196   SDValue RHS = N->getOperand(1);
10197   SDValue Shuffle = XformToShuffleWithZero(N);
10198   if (Shuffle.getNode()) return Shuffle;
10199
10200   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10201   // this operation.
10202   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10203       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10204     SmallVector<SDValue, 8> Ops;
10205     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10206       SDValue LHSOp = LHS.getOperand(i);
10207       SDValue RHSOp = RHS.getOperand(i);
10208       // If these two elements can't be folded, bail out.
10209       if ((LHSOp.getOpcode() != ISD::UNDEF &&
10210            LHSOp.getOpcode() != ISD::Constant &&
10211            LHSOp.getOpcode() != ISD::ConstantFP) ||
10212           (RHSOp.getOpcode() != ISD::UNDEF &&
10213            RHSOp.getOpcode() != ISD::Constant &&
10214            RHSOp.getOpcode() != ISD::ConstantFP))
10215         break;
10216
10217       // Can't fold divide by zero.
10218       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10219           N->getOpcode() == ISD::FDIV) {
10220         if ((RHSOp.getOpcode() == ISD::Constant &&
10221              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10222             (RHSOp.getOpcode() == ISD::ConstantFP &&
10223              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10224           break;
10225       }
10226
10227       EVT VT = LHSOp.getValueType();
10228       EVT RVT = RHSOp.getValueType();
10229       if (RVT != VT) {
10230         // Integer BUILD_VECTOR operands may have types larger than the element
10231         // size (e.g., when the element type is not legal).  Prior to type
10232         // legalization, the types may not match between the two BUILD_VECTORS.
10233         // Truncate one of the operands to make them match.
10234         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10235           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10236         } else {
10237           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10238           VT = RVT;
10239         }
10240       }
10241       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10242                                    LHSOp, RHSOp);
10243       if (FoldOp.getOpcode() != ISD::UNDEF &&
10244           FoldOp.getOpcode() != ISD::Constant &&
10245           FoldOp.getOpcode() != ISD::ConstantFP)
10246         break;
10247       Ops.push_back(FoldOp);
10248       AddToWorkList(FoldOp.getNode());
10249     }
10250
10251     if (Ops.size() == LHS.getNumOperands())
10252       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10253                          LHS.getValueType(), &Ops[0], Ops.size());
10254   }
10255
10256   return SDValue();
10257 }
10258
10259 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10260 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10261   assert(N->getValueType(0).isVector() &&
10262          "SimplifyVUnaryOp only works on vectors!");
10263
10264   SDValue N0 = N->getOperand(0);
10265
10266   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10267     return SDValue();
10268
10269   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10270   SmallVector<SDValue, 8> Ops;
10271   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10272     SDValue Op = N0.getOperand(i);
10273     if (Op.getOpcode() != ISD::UNDEF &&
10274         Op.getOpcode() != ISD::ConstantFP)
10275       break;
10276     EVT EltVT = Op.getValueType();
10277     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10278     if (FoldOp.getOpcode() != ISD::UNDEF &&
10279         FoldOp.getOpcode() != ISD::ConstantFP)
10280       break;
10281     Ops.push_back(FoldOp);
10282     AddToWorkList(FoldOp.getNode());
10283   }
10284
10285   if (Ops.size() != N0.getNumOperands())
10286     return SDValue();
10287
10288   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10289                      N0.getValueType(), &Ops[0], Ops.size());
10290 }
10291
10292 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10293                                     SDValue N1, SDValue N2){
10294   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10295
10296   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10297                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10298
10299   // If we got a simplified select_cc node back from SimplifySelectCC, then
10300   // break it down into a new SETCC node, and a new SELECT node, and then return
10301   // the SELECT node, since we were called with a SELECT node.
10302   if (SCC.getNode()) {
10303     // Check to see if we got a select_cc back (to turn into setcc/select).
10304     // Otherwise, just return whatever node we got back, like fabs.
10305     if (SCC.getOpcode() == ISD::SELECT_CC) {
10306       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10307                                   N0.getValueType(),
10308                                   SCC.getOperand(0), SCC.getOperand(1),
10309                                   SCC.getOperand(4));
10310       AddToWorkList(SETCC.getNode());
10311       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10312                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10313     }
10314
10315     return SCC;
10316   }
10317   return SDValue();
10318 }
10319
10320 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10321 /// are the two values being selected between, see if we can simplify the
10322 /// select.  Callers of this should assume that TheSelect is deleted if this
10323 /// returns true.  As such, they should return the appropriate thing (e.g. the
10324 /// node) back to the top-level of the DAG combiner loop to avoid it being
10325 /// looked at.
10326 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10327                                     SDValue RHS) {
10328
10329   // Cannot simplify select with vector condition
10330   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10331
10332   // If this is a select from two identical things, try to pull the operation
10333   // through the select.
10334   if (LHS.getOpcode() != RHS.getOpcode() ||
10335       !LHS.hasOneUse() || !RHS.hasOneUse())
10336     return false;
10337
10338   // If this is a load and the token chain is identical, replace the select
10339   // of two loads with a load through a select of the address to load from.
10340   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10341   // constants have been dropped into the constant pool.
10342   if (LHS.getOpcode() == ISD::LOAD) {
10343     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10344     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10345
10346     // Token chains must be identical.
10347     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10348         // Do not let this transformation reduce the number of volatile loads.
10349         LLD->isVolatile() || RLD->isVolatile() ||
10350         // If this is an EXTLOAD, the VT's must match.
10351         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10352         // If this is an EXTLOAD, the kind of extension must match.
10353         (LLD->getExtensionType() != RLD->getExtensionType() &&
10354          // The only exception is if one of the extensions is anyext.
10355          LLD->getExtensionType() != ISD::EXTLOAD &&
10356          RLD->getExtensionType() != ISD::EXTLOAD) ||
10357         // FIXME: this discards src value information.  This is
10358         // over-conservative. It would be beneficial to be able to remember
10359         // both potential memory locations.  Since we are discarding
10360         // src value info, don't do the transformation if the memory
10361         // locations are not in the default address space.
10362         LLD->getPointerInfo().getAddrSpace() != 0 ||
10363         RLD->getPointerInfo().getAddrSpace() != 0 ||
10364         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10365                                       LLD->getBasePtr().getValueType()))
10366       return false;
10367
10368     // Check that the select condition doesn't reach either load.  If so,
10369     // folding this will induce a cycle into the DAG.  If not, this is safe to
10370     // xform, so create a select of the addresses.
10371     SDValue Addr;
10372     if (TheSelect->getOpcode() == ISD::SELECT) {
10373       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10374       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10375           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10376         return false;
10377       // The loads must not depend on one another.
10378       if (LLD->isPredecessorOf(RLD) ||
10379           RLD->isPredecessorOf(LLD))
10380         return false;
10381       Addr = DAG.getSelect(SDLoc(TheSelect),
10382                            LLD->getBasePtr().getValueType(),
10383                            TheSelect->getOperand(0), LLD->getBasePtr(),
10384                            RLD->getBasePtr());
10385     } else {  // Otherwise SELECT_CC
10386       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10387       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10388
10389       if ((LLD->hasAnyUseOfValue(1) &&
10390            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10391           (RLD->hasAnyUseOfValue(1) &&
10392            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10393         return false;
10394
10395       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10396                          LLD->getBasePtr().getValueType(),
10397                          TheSelect->getOperand(0),
10398                          TheSelect->getOperand(1),
10399                          LLD->getBasePtr(), RLD->getBasePtr(),
10400                          TheSelect->getOperand(4));
10401     }
10402
10403     SDValue Load;
10404     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10405       Load = DAG.getLoad(TheSelect->getValueType(0),
10406                          SDLoc(TheSelect),
10407                          // FIXME: Discards pointer info.
10408                          LLD->getChain(), Addr, MachinePointerInfo(),
10409                          LLD->isVolatile(), LLD->isNonTemporal(),
10410                          LLD->isInvariant(), LLD->getAlignment());
10411     } else {
10412       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10413                             RLD->getExtensionType() : LLD->getExtensionType(),
10414                             SDLoc(TheSelect),
10415                             TheSelect->getValueType(0),
10416                             // FIXME: Discards pointer info.
10417                             LLD->getChain(), Addr, MachinePointerInfo(),
10418                             LLD->getMemoryVT(), LLD->isVolatile(),
10419                             LLD->isNonTemporal(), LLD->getAlignment());
10420     }
10421
10422     // Users of the select now use the result of the load.
10423     CombineTo(TheSelect, Load);
10424
10425     // Users of the old loads now use the new load's chain.  We know the
10426     // old-load value is dead now.
10427     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10428     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10429     return true;
10430   }
10431
10432   return false;
10433 }
10434
10435 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10436 /// where 'cond' is the comparison specified by CC.
10437 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10438                                       SDValue N2, SDValue N3,
10439                                       ISD::CondCode CC, bool NotExtCompare) {
10440   // (x ? y : y) -> y.
10441   if (N2 == N3) return N2;
10442
10443   EVT VT = N2.getValueType();
10444   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10445   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10446   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10447
10448   // Determine if the condition we're dealing with is constant
10449   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10450                               N0, N1, CC, DL, false);
10451   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10452   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10453
10454   // fold select_cc true, x, y -> x
10455   if (SCCC && !SCCC->isNullValue())
10456     return N2;
10457   // fold select_cc false, x, y -> y
10458   if (SCCC && SCCC->isNullValue())
10459     return N3;
10460
10461   // Check to see if we can simplify the select into an fabs node
10462   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10463     // Allow either -0.0 or 0.0
10464     if (CFP->getValueAPF().isZero()) {
10465       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10466       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10467           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10468           N2 == N3.getOperand(0))
10469         return DAG.getNode(ISD::FABS, DL, VT, N0);
10470
10471       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10472       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10473           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10474           N2.getOperand(0) == N3)
10475         return DAG.getNode(ISD::FABS, DL, VT, N3);
10476     }
10477   }
10478
10479   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10480   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10481   // in it.  This is a win when the constant is not otherwise available because
10482   // it replaces two constant pool loads with one.  We only do this if the FP
10483   // type is known to be legal, because if it isn't, then we are before legalize
10484   // types an we want the other legalization to happen first (e.g. to avoid
10485   // messing with soft float) and if the ConstantFP is not legal, because if
10486   // it is legal, we may not need to store the FP constant in a constant pool.
10487   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10488     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10489       if (TLI.isTypeLegal(N2.getValueType()) &&
10490           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10491            TargetLowering::Legal) &&
10492           // If both constants have multiple uses, then we won't need to do an
10493           // extra load, they are likely around in registers for other users.
10494           (TV->hasOneUse() || FV->hasOneUse())) {
10495         Constant *Elts[] = {
10496           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10497           const_cast<ConstantFP*>(TV->getConstantFPValue())
10498         };
10499         Type *FPTy = Elts[0]->getType();
10500         const DataLayout &TD = *TLI.getDataLayout();
10501
10502         // Create a ConstantArray of the two constants.
10503         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10504         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10505                                             TD.getPrefTypeAlignment(FPTy));
10506         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10507
10508         // Get the offsets to the 0 and 1 element of the array so that we can
10509         // select between them.
10510         SDValue Zero = DAG.getIntPtrConstant(0);
10511         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10512         SDValue One = DAG.getIntPtrConstant(EltSize);
10513
10514         SDValue Cond = DAG.getSetCC(DL,
10515                                     getSetCCResultType(N0.getValueType()),
10516                                     N0, N1, CC);
10517         AddToWorkList(Cond.getNode());
10518         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10519                                           Cond, One, Zero);
10520         AddToWorkList(CstOffset.getNode());
10521         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10522                             CstOffset);
10523         AddToWorkList(CPIdx.getNode());
10524         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10525                            MachinePointerInfo::getConstantPool(), false,
10526                            false, false, Alignment);
10527
10528       }
10529     }
10530
10531   // Check to see if we can perform the "gzip trick", transforming
10532   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10533   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10534       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10535        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10536     EVT XType = N0.getValueType();
10537     EVT AType = N2.getValueType();
10538     if (XType.bitsGE(AType)) {
10539       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10540       // single-bit constant.
10541       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10542         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10543         ShCtV = XType.getSizeInBits()-ShCtV-1;
10544         SDValue ShCt = DAG.getConstant(ShCtV,
10545                                        getShiftAmountTy(N0.getValueType()));
10546         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10547                                     XType, N0, ShCt);
10548         AddToWorkList(Shift.getNode());
10549
10550         if (XType.bitsGT(AType)) {
10551           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10552           AddToWorkList(Shift.getNode());
10553         }
10554
10555         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10556       }
10557
10558       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10559                                   XType, N0,
10560                                   DAG.getConstant(XType.getSizeInBits()-1,
10561                                          getShiftAmountTy(N0.getValueType())));
10562       AddToWorkList(Shift.getNode());
10563
10564       if (XType.bitsGT(AType)) {
10565         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10566         AddToWorkList(Shift.getNode());
10567       }
10568
10569       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10570     }
10571   }
10572
10573   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10574   // where y is has a single bit set.
10575   // A plaintext description would be, we can turn the SELECT_CC into an AND
10576   // when the condition can be materialized as an all-ones register.  Any
10577   // single bit-test can be materialized as an all-ones register with
10578   // shift-left and shift-right-arith.
10579   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10580       N0->getValueType(0) == VT &&
10581       N1C && N1C->isNullValue() &&
10582       N2C && N2C->isNullValue()) {
10583     SDValue AndLHS = N0->getOperand(0);
10584     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10585     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10586       // Shift the tested bit over the sign bit.
10587       APInt AndMask = ConstAndRHS->getAPIntValue();
10588       SDValue ShlAmt =
10589         DAG.getConstant(AndMask.countLeadingZeros(),
10590                         getShiftAmountTy(AndLHS.getValueType()));
10591       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10592
10593       // Now arithmetic right shift it all the way over, so the result is either
10594       // all-ones, or zero.
10595       SDValue ShrAmt =
10596         DAG.getConstant(AndMask.getBitWidth()-1,
10597                         getShiftAmountTy(Shl.getValueType()));
10598       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10599
10600       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10601     }
10602   }
10603
10604   // fold select C, 16, 0 -> shl C, 4
10605   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10606     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10607       TargetLowering::ZeroOrOneBooleanContent) {
10608
10609     // If the caller doesn't want us to simplify this into a zext of a compare,
10610     // don't do it.
10611     if (NotExtCompare && N2C->getAPIntValue() == 1)
10612       return SDValue();
10613
10614     // Get a SetCC of the condition
10615     // NOTE: Don't create a SETCC if it's not legal on this target.
10616     if (!LegalOperations ||
10617         TLI.isOperationLegal(ISD::SETCC,
10618           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10619       SDValue Temp, SCC;
10620       // cast from setcc result type to select result type
10621       if (LegalTypes) {
10622         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10623                             N0, N1, CC);
10624         if (N2.getValueType().bitsLT(SCC.getValueType()))
10625           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10626                                         N2.getValueType());
10627         else
10628           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10629                              N2.getValueType(), SCC);
10630       } else {
10631         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10632         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10633                            N2.getValueType(), SCC);
10634       }
10635
10636       AddToWorkList(SCC.getNode());
10637       AddToWorkList(Temp.getNode());
10638
10639       if (N2C->getAPIntValue() == 1)
10640         return Temp;
10641
10642       // shl setcc result by log2 n2c
10643       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10644                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10645                                          getShiftAmountTy(Temp.getValueType())));
10646     }
10647   }
10648
10649   // Check to see if this is the equivalent of setcc
10650   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10651   // otherwise, go ahead with the folds.
10652   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10653     EVT XType = N0.getValueType();
10654     if (!LegalOperations ||
10655         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10656       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10657       if (Res.getValueType() != VT)
10658         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10659       return Res;
10660     }
10661
10662     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10663     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10664         (!LegalOperations ||
10665          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10666       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10667       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10668                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10669                                        getShiftAmountTy(Ctlz.getValueType())));
10670     }
10671     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10672     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10673       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10674                                   XType, DAG.getConstant(0, XType), N0);
10675       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10676       return DAG.getNode(ISD::SRL, DL, XType,
10677                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10678                          DAG.getConstant(XType.getSizeInBits()-1,
10679                                          getShiftAmountTy(XType)));
10680     }
10681     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10682     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10683       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10684                                  DAG.getConstant(XType.getSizeInBits()-1,
10685                                          getShiftAmountTy(N0.getValueType())));
10686       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10687     }
10688   }
10689
10690   // Check to see if this is an integer abs.
10691   // select_cc setg[te] X,  0,  X, -X ->
10692   // select_cc setgt    X, -1,  X, -X ->
10693   // select_cc setl[te] X,  0, -X,  X ->
10694   // select_cc setlt    X,  1, -X,  X ->
10695   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10696   if (N1C) {
10697     ConstantSDNode *SubC = NULL;
10698     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10699          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10700         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10701       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10702     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10703               (N1C->isOne() && CC == ISD::SETLT)) &&
10704              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10705       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10706
10707     EVT XType = N0.getValueType();
10708     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10709       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10710                                   N0,
10711                                   DAG.getConstant(XType.getSizeInBits()-1,
10712                                          getShiftAmountTy(N0.getValueType())));
10713       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10714                                 XType, N0, Shift);
10715       AddToWorkList(Shift.getNode());
10716       AddToWorkList(Add.getNode());
10717       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10718     }
10719   }
10720
10721   return SDValue();
10722 }
10723
10724 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10725 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10726                                    SDValue N1, ISD::CondCode Cond,
10727                                    SDLoc DL, bool foldBooleans) {
10728   TargetLowering::DAGCombinerInfo
10729     DagCombineInfo(DAG, Level, false, this);
10730   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10731 }
10732
10733 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10734 /// return a DAG expression to select that will generate the same value by
10735 /// multiplying by a magic number.  See:
10736 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10737 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10738   std::vector<SDNode*> Built;
10739   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10740
10741   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10742        ii != ee; ++ii)
10743     AddToWorkList(*ii);
10744   return S;
10745 }
10746
10747 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10748 /// return a DAG expression to select that will generate the same value by
10749 /// multiplying by a magic number.  See:
10750 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10751 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10752   std::vector<SDNode*> Built;
10753   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10754
10755   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10756        ii != ee; ++ii)
10757     AddToWorkList(*ii);
10758   return S;
10759 }
10760
10761 /// FindBaseOffset - Return true if base is a frame index, which is known not
10762 // to alias with anything but itself.  Provides base object and offset as
10763 // results.
10764 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10765                            const GlobalValue *&GV, const void *&CV) {
10766   // Assume it is a primitive operation.
10767   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10768
10769   // If it's an adding a simple constant then integrate the offset.
10770   if (Base.getOpcode() == ISD::ADD) {
10771     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10772       Base = Base.getOperand(0);
10773       Offset += C->getZExtValue();
10774     }
10775   }
10776
10777   // Return the underlying GlobalValue, and update the Offset.  Return false
10778   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10779   // by multiple nodes with different offsets.
10780   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10781     GV = G->getGlobal();
10782     Offset += G->getOffset();
10783     return false;
10784   }
10785
10786   // Return the underlying Constant value, and update the Offset.  Return false
10787   // for ConstantSDNodes since the same constant pool entry may be represented
10788   // by multiple nodes with different offsets.
10789   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10790     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10791                                          : (const void *)C->getConstVal();
10792     Offset += C->getOffset();
10793     return false;
10794   }
10795   // If it's any of the following then it can't alias with anything but itself.
10796   return isa<FrameIndexSDNode>(Base);
10797 }
10798
10799 /// isAlias - Return true if there is any possibility that the two addresses
10800 /// overlap.
10801 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10802                           const Value *SrcValue1, int SrcValueOffset1,
10803                           unsigned SrcValueAlign1,
10804                           const MDNode *TBAAInfo1,
10805                           SDValue Ptr2, int64_t Size2,
10806                           const Value *SrcValue2, int SrcValueOffset2,
10807                           unsigned SrcValueAlign2,
10808                           const MDNode *TBAAInfo2) const {
10809   // If they are the same then they must be aliases.
10810   if (Ptr1 == Ptr2) return true;
10811
10812   // Gather base node and offset information.
10813   SDValue Base1, Base2;
10814   int64_t Offset1, Offset2;
10815   const GlobalValue *GV1, *GV2;
10816   const void *CV1, *CV2;
10817   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10818   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10819
10820   // If they have a same base address then check to see if they overlap.
10821   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10822     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10823
10824   // It is possible for different frame indices to alias each other, mostly
10825   // when tail call optimization reuses return address slots for arguments.
10826   // To catch this case, look up the actual index of frame indices to compute
10827   // the real alias relationship.
10828   if (isFrameIndex1 && isFrameIndex2) {
10829     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10830     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10831     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10832     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10833   }
10834
10835   // Otherwise, if we know what the bases are, and they aren't identical, then
10836   // we know they cannot alias.
10837   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10838     return false;
10839
10840   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10841   // compared to the size and offset of the access, we may be able to prove they
10842   // do not alias.  This check is conservative for now to catch cases created by
10843   // splitting vector types.
10844   if ((SrcValueAlign1 == SrcValueAlign2) &&
10845       (SrcValueOffset1 != SrcValueOffset2) &&
10846       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10847     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10848     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10849
10850     // There is no overlap between these relatively aligned accesses of similar
10851     // size, return no alias.
10852     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10853       return false;
10854   }
10855
10856   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10857     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10858   if (UseAA && SrcValue1 && SrcValue2) {
10859     // Use alias analysis information.
10860     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10861     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10862     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10863     AliasAnalysis::AliasResult AAResult =
10864       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10865                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10866     if (AAResult == AliasAnalysis::NoAlias)
10867       return false;
10868   }
10869
10870   // Otherwise we have to assume they alias.
10871   return true;
10872 }
10873
10874 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10875   SDValue Ptr0, Ptr1;
10876   int64_t Size0, Size1;
10877   const Value *SrcValue0, *SrcValue1;
10878   int SrcValueOffset0, SrcValueOffset1;
10879   unsigned SrcValueAlign0, SrcValueAlign1;
10880   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10881   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10882                 SrcValueAlign0, SrcTBAAInfo0);
10883   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10884                 SrcValueAlign1, SrcTBAAInfo1);
10885   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10886                  SrcValueAlign0, SrcTBAAInfo0,
10887                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10888                  SrcValueAlign1, SrcTBAAInfo1);
10889 }
10890
10891 /// FindAliasInfo - Extracts the relevant alias information from the memory
10892 /// node.  Returns true if the operand was a load.
10893 bool DAGCombiner::FindAliasInfo(SDNode *N,
10894                                 SDValue &Ptr, int64_t &Size,
10895                                 const Value *&SrcValue,
10896                                 int &SrcValueOffset,
10897                                 unsigned &SrcValueAlign,
10898                                 const MDNode *&TBAAInfo) const {
10899   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10900
10901   Ptr = LS->getBasePtr();
10902   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10903   SrcValue = LS->getSrcValue();
10904   SrcValueOffset = LS->getSrcValueOffset();
10905   SrcValueAlign = LS->getOriginalAlignment();
10906   TBAAInfo = LS->getTBAAInfo();
10907   return isa<LoadSDNode>(LS);
10908 }
10909
10910 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10911 /// looking for aliasing nodes and adding them to the Aliases vector.
10912 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10913                                    SmallVectorImpl<SDValue> &Aliases) {
10914   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10915   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10916
10917   // Get alias information for node.
10918   SDValue Ptr;
10919   int64_t Size;
10920   const Value *SrcValue;
10921   int SrcValueOffset;
10922   unsigned SrcValueAlign;
10923   const MDNode *SrcTBAAInfo;
10924   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10925                               SrcValueAlign, SrcTBAAInfo);
10926
10927   // Starting off.
10928   Chains.push_back(OriginalChain);
10929   unsigned Depth = 0;
10930
10931   // Look at each chain and determine if it is an alias.  If so, add it to the
10932   // aliases list.  If not, then continue up the chain looking for the next
10933   // candidate.
10934   while (!Chains.empty()) {
10935     SDValue Chain = Chains.back();
10936     Chains.pop_back();
10937
10938     // For TokenFactor nodes, look at each operand and only continue up the
10939     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10940     // find more and revert to original chain since the xform is unlikely to be
10941     // profitable.
10942     //
10943     // FIXME: The depth check could be made to return the last non-aliasing
10944     // chain we found before we hit a tokenfactor rather than the original
10945     // chain.
10946     if (Depth > 6 || Aliases.size() == 2) {
10947       Aliases.clear();
10948       Aliases.push_back(OriginalChain);
10949       break;
10950     }
10951
10952     // Don't bother if we've been before.
10953     if (!Visited.insert(Chain.getNode()))
10954       continue;
10955
10956     switch (Chain.getOpcode()) {
10957     case ISD::EntryToken:
10958       // Entry token is ideal chain operand, but handled in FindBetterChain.
10959       break;
10960
10961     case ISD::LOAD:
10962     case ISD::STORE: {
10963       // Get alias information for Chain.
10964       SDValue OpPtr;
10965       int64_t OpSize;
10966       const Value *OpSrcValue;
10967       int OpSrcValueOffset;
10968       unsigned OpSrcValueAlign;
10969       const MDNode *OpSrcTBAAInfo;
10970       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10971                                     OpSrcValue, OpSrcValueOffset,
10972                                     OpSrcValueAlign,
10973                                     OpSrcTBAAInfo);
10974
10975       // If chain is alias then stop here.
10976       if (!(IsLoad && IsOpLoad) &&
10977           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10978                   SrcTBAAInfo,
10979                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10980                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10981         Aliases.push_back(Chain);
10982       } else {
10983         // Look further up the chain.
10984         Chains.push_back(Chain.getOperand(0));
10985         ++Depth;
10986       }
10987       break;
10988     }
10989
10990     case ISD::TokenFactor:
10991       // We have to check each of the operands of the token factor for "small"
10992       // token factors, so we queue them up.  Adding the operands to the queue
10993       // (stack) in reverse order maintains the original order and increases the
10994       // likelihood that getNode will find a matching token factor (CSE.)
10995       if (Chain.getNumOperands() > 16) {
10996         Aliases.push_back(Chain);
10997         break;
10998       }
10999       for (unsigned n = Chain.getNumOperands(); n;)
11000         Chains.push_back(Chain.getOperand(--n));
11001       ++Depth;
11002       break;
11003
11004     default:
11005       // For all other instructions we will just have to take what we can get.
11006       Aliases.push_back(Chain);
11007       break;
11008     }
11009   }
11010 }
11011
11012 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11013 /// for a better chain (aliasing node.)
11014 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11015   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11016
11017   // Accumulate all the aliases to this node.
11018   GatherAllAliases(N, OldChain, Aliases);
11019
11020   // If no operands then chain to entry token.
11021   if (Aliases.size() == 0)
11022     return DAG.getEntryNode();
11023
11024   // If a single operand then chain to it.  We don't need to revisit it.
11025   if (Aliases.size() == 1)
11026     return Aliases[0];
11027
11028   // Construct a custom tailored token factor.
11029   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11030                      &Aliases[0], Aliases.size());
11031 }
11032
11033 // SelectionDAG::Combine - This is the entry point for the file.
11034 //
11035 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11036                            CodeGenOpt::Level OptLevel) {
11037   /// run - This is the main entry point to this class.
11038   ///
11039   DAGCombiner(*this, AA, OptLevel).Run(Level);
11040 }