Revert r191393 since it caused pr17380.
[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/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NodesCombined   , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
46 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
47
48 namespace {
49   static cl::opt<bool>
50     CombinerAA("combiner-alias-analysis", cl::Hidden,
51                cl::desc("Turn on alias analysis during testing"));
52
53   static cl::opt<bool>
54     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
55                cl::desc("Include global information in alias analysis"));
56
57 //------------------------------ DAGCombiner ---------------------------------//
58
59   class DAGCombiner {
60     SelectionDAG &DAG;
61     const TargetLowering &TLI;
62     CombineLevel Level;
63     CodeGenOpt::Level OptLevel;
64     bool LegalOperations;
65     bool LegalTypes;
66
67     // Worklist of all of the nodes that need to be simplified.
68     //
69     // This has the semantics that when adding to the worklist,
70     // the item added must be next to be processed. It should
71     // also only appear once. The naive approach to this takes
72     // linear time.
73     //
74     // To reduce the insert/remove time to logarithmic, we use
75     // a set and a vector to maintain our worklist.
76     //
77     // The set contains the items on the worklist, but does not
78     // maintain the order they should be visited.
79     //
80     // The vector maintains the order nodes should be visited, but may
81     // contain duplicate or removed nodes. When choosing a node to
82     // visit, we pop off the order stack until we find an item that is
83     // also in the contents set. All operations are O(log N).
84     SmallPtrSet<SDNode*, 64> WorkListContents;
85     SmallVector<SDNode*, 64> WorkListOrder;
86
87     // AA - Used for DAG load/store alias analysis.
88     AliasAnalysis &AA;
89
90     /// AddUsersToWorkList - When an instruction is simplified, add all users of
91     /// the instruction to the work lists because they might get more simplified
92     /// now.
93     ///
94     void AddUsersToWorkList(SDNode *N) {
95       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
96            UI != UE; ++UI)
97         AddToWorkList(*UI);
98     }
99
100     /// visit - call the node-specific routine that knows how to fold each
101     /// particular type of node.
102     SDValue visit(SDNode *N);
103
104   public:
105     /// AddToWorkList - Add to the work list making sure its instance is at the
106     /// back (next to be processed.)
107     void AddToWorkList(SDNode *N) {
108       WorkListContents.insert(N);
109       WorkListOrder.push_back(N);
110     }
111
112     /// removeFromWorkList - remove all instances of N from the worklist.
113     ///
114     void removeFromWorkList(SDNode *N) {
115       WorkListContents.erase(N);
116     }
117
118     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
119                       bool AddTo = true);
120
121     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
122       return CombineTo(N, &Res, 1, AddTo);
123     }
124
125     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126                       bool AddTo = true) {
127       SDValue To[] = { Res0, Res1 };
128       return CombineTo(N, To, 2, AddTo);
129     }
130
131     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
132
133   private:
134
135     /// SimplifyDemandedBits - Check the specified integer node value to see if
136     /// it can be simplified or if things it uses can be simplified by bit
137     /// propagation.  If so, return true.
138     bool SimplifyDemandedBits(SDValue Op) {
139       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
140       APInt Demanded = APInt::getAllOnesValue(BitWidth);
141       return SimplifyDemandedBits(Op, Demanded);
142     }
143
144     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145
146     bool CombineToPreIndexedLoadStore(SDNode *N);
147     bool CombineToPostIndexedLoadStore(SDNode *N);
148
149     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
150     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
151     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
152     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
153     SDValue PromoteIntBinOp(SDValue Op);
154     SDValue PromoteIntShiftOp(SDValue Op);
155     SDValue PromoteExtend(SDValue Op);
156     bool PromoteLoad(SDValue Op);
157
158     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
159                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
160                          ISD::NodeType ExtType);
161
162     /// combine - call the node-specific routine that knows how to fold each
163     /// particular type of node. If that doesn't do anything, try the
164     /// target-specific DAG combines.
165     SDValue combine(SDNode *N);
166
167     // Visitation implementation - Implement dag node combining for different
168     // node types.  The semantics are as follows:
169     // Return Value:
170     //   SDValue.getNode() == 0 - No change was made
171     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
172     //   otherwise              - N should be replaced by the returned Operand.
173     //
174     SDValue visitTokenFactor(SDNode *N);
175     SDValue visitMERGE_VALUES(SDNode *N);
176     SDValue visitADD(SDNode *N);
177     SDValue visitSUB(SDNode *N);
178     SDValue visitADDC(SDNode *N);
179     SDValue visitSUBC(SDNode *N);
180     SDValue visitADDE(SDNode *N);
181     SDValue visitSUBE(SDNode *N);
182     SDValue visitMUL(SDNode *N);
183     SDValue visitSDIV(SDNode *N);
184     SDValue visitUDIV(SDNode *N);
185     SDValue visitSREM(SDNode *N);
186     SDValue visitUREM(SDNode *N);
187     SDValue visitMULHU(SDNode *N);
188     SDValue visitMULHS(SDNode *N);
189     SDValue visitSMUL_LOHI(SDNode *N);
190     SDValue visitUMUL_LOHI(SDNode *N);
191     SDValue visitSMULO(SDNode *N);
192     SDValue visitUMULO(SDNode *N);
193     SDValue visitSDIVREM(SDNode *N);
194     SDValue visitUDIVREM(SDNode *N);
195     SDValue visitAND(SDNode *N);
196     SDValue visitOR(SDNode *N);
197     SDValue visitXOR(SDNode *N);
198     SDValue SimplifyVBinOp(SDNode *N);
199     SDValue SimplifyVUnaryOp(SDNode *N);
200     SDValue visitSHL(SDNode *N);
201     SDValue visitSRA(SDNode *N);
202     SDValue visitSRL(SDNode *N);
203     SDValue visitCTLZ(SDNode *N);
204     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
205     SDValue visitCTTZ(SDNode *N);
206     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
207     SDValue visitCTPOP(SDNode *N);
208     SDValue visitSELECT(SDNode *N);
209     SDValue visitVSELECT(SDNode *N);
210     SDValue visitSELECT_CC(SDNode *N);
211     SDValue visitSETCC(SDNode *N);
212     SDValue visitSIGN_EXTEND(SDNode *N);
213     SDValue visitZERO_EXTEND(SDNode *N);
214     SDValue visitANY_EXTEND(SDNode *N);
215     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
216     SDValue visitTRUNCATE(SDNode *N);
217     SDValue visitBITCAST(SDNode *N);
218     SDValue visitBUILD_PAIR(SDNode *N);
219     SDValue visitFADD(SDNode *N);
220     SDValue visitFSUB(SDNode *N);
221     SDValue visitFMUL(SDNode *N);
222     SDValue visitFMA(SDNode *N);
223     SDValue visitFDIV(SDNode *N);
224     SDValue visitFREM(SDNode *N);
225     SDValue visitFCOPYSIGN(SDNode *N);
226     SDValue visitSINT_TO_FP(SDNode *N);
227     SDValue visitUINT_TO_FP(SDNode *N);
228     SDValue visitFP_TO_SINT(SDNode *N);
229     SDValue visitFP_TO_UINT(SDNode *N);
230     SDValue visitFP_ROUND(SDNode *N);
231     SDValue visitFP_ROUND_INREG(SDNode *N);
232     SDValue visitFP_EXTEND(SDNode *N);
233     SDValue visitFNEG(SDNode *N);
234     SDValue visitFABS(SDNode *N);
235     SDValue visitFCEIL(SDNode *N);
236     SDValue visitFTRUNC(SDNode *N);
237     SDValue visitFFLOOR(SDNode *N);
238     SDValue visitBRCOND(SDNode *N);
239     SDValue visitBR_CC(SDNode *N);
240     SDValue visitLOAD(SDNode *N);
241     SDValue visitSTORE(SDNode *N);
242     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
243     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
244     SDValue visitBUILD_VECTOR(SDNode *N);
245     SDValue visitCONCAT_VECTORS(SDNode *N);
246     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
247     SDValue visitVECTOR_SHUFFLE(SDNode *N);
248
249     SDValue XformToShuffleWithZero(SDNode *N);
250     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
251
252     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
253
254     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
255     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
256     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
257     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
258                              SDValue N3, ISD::CondCode CC,
259                              bool NotExtCompare = false);
260     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
261                           SDLoc DL, bool foldBooleans = true);
262     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
263                                          unsigned HiOp);
264     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
265     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
266     SDValue BuildSDIV(SDNode *N);
267     SDValue BuildUDIV(SDNode *N);
268     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
269                                bool DemandHighBits = true);
270     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
271     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
272     SDValue ReduceLoadWidth(SDNode *N);
273     SDValue ReduceLoadOpStoreWidth(SDNode *N);
274     SDValue TransformFPLoadStorePair(SDNode *N);
275     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
276     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
277
278     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
279
280     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
281     /// looking for aliasing nodes and adding them to the Aliases vector.
282     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
283                           SmallVectorImpl<SDValue> &Aliases);
284
285     /// isAlias - Return true if there is any possibility that the two addresses
286     /// overlap.
287     bool isAlias(SDValue Ptr1, int64_t Size1,
288                  const Value *SrcValue1, int SrcValueOffset1,
289                  unsigned SrcValueAlign1,
290                  const MDNode *TBAAInfo1,
291                  SDValue Ptr2, int64_t Size2,
292                  const Value *SrcValue2, int SrcValueOffset2,
293                  unsigned SrcValueAlign2,
294                  const MDNode *TBAAInfo2) const;
295
296     /// isAlias - Return true if there is any possibility that the two addresses
297     /// overlap.
298     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
299
300     /// FindAliasInfo - Extracts the relevant alias information from the memory
301     /// node.  Returns true if the operand was a load.
302     bool FindAliasInfo(SDNode *N,
303                        SDValue &Ptr, int64_t &Size,
304                        const Value *&SrcValue, int &SrcValueOffset,
305                        unsigned &SrcValueAlignment,
306                        const MDNode *&TBAAInfo) const;
307
308     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
309     /// looking for a better chain (aliasing node.)
310     SDValue FindBetterChain(SDNode *N, SDValue Chain);
311
312     /// Merge consecutive store operations into a wide store.
313     /// This optimization uses wide integers or vectors when possible.
314     /// \return True if some memory operations were changed.
315     bool MergeConsecutiveStores(StoreSDNode *N);
316
317   public:
318     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
319       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
320         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
321
322     /// Run - runs the dag combiner on all nodes in the work list
323     void Run(CombineLevel AtLevel);
324
325     SelectionDAG &getDAG() const { return DAG; }
326
327     /// getShiftAmountTy - Returns a type large enough to hold any valid
328     /// shift amount - before type legalization these can be huge.
329     EVT getShiftAmountTy(EVT LHSTy) {
330       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
331       if (LHSTy.isVector())
332         return LHSTy;
333       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
334     }
335
336     /// isTypeLegal - This method returns true if we are running before type
337     /// legalization or if the specified VT is legal.
338     bool isTypeLegal(const EVT &VT) {
339       if (!LegalTypes) return true;
340       return TLI.isTypeLegal(VT);
341     }
342
343     /// getSetCCResultType - Convenience wrapper around
344     /// TargetLowering::getSetCCResultType
345     EVT getSetCCResultType(EVT VT) const {
346       return TLI.getSetCCResultType(*DAG.getContext(), VT);
347     }
348   };
349 }
350
351
352 namespace {
353 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
354 /// nodes from the worklist.
355 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
356   DAGCombiner &DC;
357 public:
358   explicit WorkListRemover(DAGCombiner &dc)
359     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
360
361   virtual void NodeDeleted(SDNode *N, SDNode *E) {
362     DC.removeFromWorkList(N);
363   }
364 };
365 }
366
367 //===----------------------------------------------------------------------===//
368 //  TargetLowering::DAGCombinerInfo implementation
369 //===----------------------------------------------------------------------===//
370
371 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
372   ((DAGCombiner*)DC)->AddToWorkList(N);
373 }
374
375 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
376   ((DAGCombiner*)DC)->removeFromWorkList(N);
377 }
378
379 SDValue TargetLowering::DAGCombinerInfo::
380 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
381   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
382 }
383
384 SDValue TargetLowering::DAGCombinerInfo::
385 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
386   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
387 }
388
389
390 SDValue TargetLowering::DAGCombinerInfo::
391 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
392   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
393 }
394
395 void TargetLowering::DAGCombinerInfo::
396 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
397   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
398 }
399
400 //===----------------------------------------------------------------------===//
401 // Helper Functions
402 //===----------------------------------------------------------------------===//
403
404 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
405 /// specified expression for the same cost as the expression itself, or 2 if we
406 /// can compute the negated form more cheaply than the expression itself.
407 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
408                                const TargetLowering &TLI,
409                                const TargetOptions *Options,
410                                unsigned Depth = 0) {
411   // fneg is removable even if it has multiple uses.
412   if (Op.getOpcode() == ISD::FNEG) return 2;
413
414   // Don't allow anything with multiple uses.
415   if (!Op.hasOneUse()) return 0;
416
417   // Don't recurse exponentially.
418   if (Depth > 6) return 0;
419
420   switch (Op.getOpcode()) {
421   default: return false;
422   case ISD::ConstantFP:
423     // Don't invert constant FP values after legalize.  The negated constant
424     // isn't necessarily legal.
425     return LegalOperations ? 0 : 1;
426   case ISD::FADD:
427     // FIXME: determine better conditions for this xform.
428     if (!Options->UnsafeFPMath) return 0;
429
430     // After operation legalization, it might not be legal to create new FSUBs.
431     if (LegalOperations &&
432         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
433       return 0;
434
435     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
436     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
437                                     Options, Depth + 1))
438       return V;
439     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
440     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
441                               Depth + 1);
442   case ISD::FSUB:
443     // We can't turn -(A-B) into B-A when we honor signed zeros.
444     if (!Options->UnsafeFPMath) return 0;
445
446     // fold (fneg (fsub A, B)) -> (fsub B, A)
447     return 1;
448
449   case ISD::FMUL:
450   case ISD::FDIV:
451     if (Options->HonorSignDependentRoundingFPMath()) return 0;
452
453     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
454     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
455                                     Options, Depth + 1))
456       return V;
457
458     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
459                               Depth + 1);
460
461   case ISD::FP_EXTEND:
462   case ISD::FP_ROUND:
463   case ISD::FSIN:
464     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
465                               Depth + 1);
466   }
467 }
468
469 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
470 /// returns the newly negated expression.
471 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
472                                     bool LegalOperations, unsigned Depth = 0) {
473   // fneg is removable even if it has multiple uses.
474   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
475
476   // Don't allow anything with multiple uses.
477   assert(Op.hasOneUse() && "Unknown reuse!");
478
479   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
480   switch (Op.getOpcode()) {
481   default: llvm_unreachable("Unknown code");
482   case ISD::ConstantFP: {
483     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
484     V.changeSign();
485     return DAG.getConstantFP(V, Op.getValueType());
486   }
487   case ISD::FADD:
488     // FIXME: determine better conditions for this xform.
489     assert(DAG.getTarget().Options.UnsafeFPMath);
490
491     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
492     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
493                            DAG.getTargetLoweringInfo(),
494                            &DAG.getTarget().Options, Depth+1))
495       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
496                          GetNegatedExpression(Op.getOperand(0), DAG,
497                                               LegalOperations, Depth+1),
498                          Op.getOperand(1));
499     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
500     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
501                        GetNegatedExpression(Op.getOperand(1), DAG,
502                                             LegalOperations, Depth+1),
503                        Op.getOperand(0));
504   case ISD::FSUB:
505     // We can't turn -(A-B) into B-A when we honor signed zeros.
506     assert(DAG.getTarget().Options.UnsafeFPMath);
507
508     // fold (fneg (fsub 0, B)) -> B
509     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
510       if (N0CFP->getValueAPF().isZero())
511         return Op.getOperand(1);
512
513     // fold (fneg (fsub A, B)) -> (fsub B, A)
514     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
515                        Op.getOperand(1), Op.getOperand(0));
516
517   case ISD::FMUL:
518   case ISD::FDIV:
519     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
520
521     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
522     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523                            DAG.getTargetLoweringInfo(),
524                            &DAG.getTarget().Options, Depth+1))
525       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
526                          GetNegatedExpression(Op.getOperand(0), DAG,
527                                               LegalOperations, Depth+1),
528                          Op.getOperand(1));
529
530     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
531     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
532                        Op.getOperand(0),
533                        GetNegatedExpression(Op.getOperand(1), DAG,
534                                             LegalOperations, Depth+1));
535
536   case ISD::FP_EXTEND:
537   case ISD::FSIN:
538     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
539                        GetNegatedExpression(Op.getOperand(0), DAG,
540                                             LegalOperations, Depth+1));
541   case ISD::FP_ROUND:
542       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
543                          GetNegatedExpression(Op.getOperand(0), DAG,
544                                               LegalOperations, Depth+1),
545                          Op.getOperand(1));
546   }
547 }
548
549
550 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
551 // that selects between the values 1 and 0, making it equivalent to a setcc.
552 // Also, set the incoming LHS, RHS, and CC references to the appropriate
553 // nodes based on the type of node we are checking.  This simplifies life a
554 // bit for the callers.
555 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
556                               SDValue &CC) {
557   if (N.getOpcode() == ISD::SETCC) {
558     LHS = N.getOperand(0);
559     RHS = N.getOperand(1);
560     CC  = N.getOperand(2);
561     return true;
562   }
563   if (N.getOpcode() == ISD::SELECT_CC &&
564       N.getOperand(2).getOpcode() == ISD::Constant &&
565       N.getOperand(3).getOpcode() == ISD::Constant &&
566       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
567       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
568     LHS = N.getOperand(0);
569     RHS = N.getOperand(1);
570     CC  = N.getOperand(4);
571     return true;
572   }
573   return false;
574 }
575
576 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
577 // one use.  If this is true, it allows the users to invert the operation for
578 // free when it is profitable to do so.
579 static bool isOneUseSetCC(SDValue N) {
580   SDValue N0, N1, N2;
581   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
582     return true;
583   return false;
584 }
585
586 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
587                                     SDValue N0, SDValue N1) {
588   EVT VT = N0.getValueType();
589   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
590     if (isa<ConstantSDNode>(N1)) {
591       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
592       SDValue OpNode =
593         DAG.FoldConstantArithmetic(Opc, VT,
594                                    cast<ConstantSDNode>(N0.getOperand(1)),
595                                    cast<ConstantSDNode>(N1));
596       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
597     }
598     if (N0.hasOneUse()) {
599       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
600       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
601                                    N0.getOperand(0), N1);
602       AddToWorkList(OpNode.getNode());
603       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
604     }
605   }
606
607   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
608     if (isa<ConstantSDNode>(N0)) {
609       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
610       SDValue OpNode =
611         DAG.FoldConstantArithmetic(Opc, VT,
612                                    cast<ConstantSDNode>(N1.getOperand(1)),
613                                    cast<ConstantSDNode>(N0));
614       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
615     }
616     if (N1.hasOneUse()) {
617       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
618       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
619                                    N1.getOperand(0), N0);
620       AddToWorkList(OpNode.getNode());
621       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
622     }
623   }
624
625   return SDValue();
626 }
627
628 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
629                                bool AddTo) {
630   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
631   ++NodesCombined;
632   DEBUG(dbgs() << "\nReplacing.1 ";
633         N->dump(&DAG);
634         dbgs() << "\nWith: ";
635         To[0].getNode()->dump(&DAG);
636         dbgs() << " and " << NumTo-1 << " other values\n";
637         for (unsigned i = 0, e = NumTo; i != e; ++i)
638           assert((!To[i].getNode() ||
639                   N->getValueType(i) == To[i].getValueType()) &&
640                  "Cannot combine value to value of different type!"));
641   WorkListRemover DeadNodes(*this);
642   DAG.ReplaceAllUsesWith(N, To);
643   if (AddTo) {
644     // Push the new nodes and any users onto the worklist
645     for (unsigned i = 0, e = NumTo; i != e; ++i) {
646       if (To[i].getNode()) {
647         AddToWorkList(To[i].getNode());
648         AddUsersToWorkList(To[i].getNode());
649       }
650     }
651   }
652
653   // Finally, if the node is now dead, remove it from the graph.  The node
654   // may not be dead if the replacement process recursively simplified to
655   // something else needing this node.
656   if (N->use_empty()) {
657     // Nodes can be reintroduced into the worklist.  Make sure we do not
658     // process a node that has been replaced.
659     removeFromWorkList(N);
660
661     // Finally, since the node is now dead, remove it from the graph.
662     DAG.DeleteNode(N);
663   }
664   return SDValue(N, 0);
665 }
666
667 void DAGCombiner::
668 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
669   // Replace all uses.  If any nodes become isomorphic to other nodes and
670   // are deleted, make sure to remove them from our worklist.
671   WorkListRemover DeadNodes(*this);
672   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
673
674   // Push the new node and any (possibly new) users onto the worklist.
675   AddToWorkList(TLO.New.getNode());
676   AddUsersToWorkList(TLO.New.getNode());
677
678   // Finally, if the node is now dead, remove it from the graph.  The node
679   // may not be dead if the replacement process recursively simplified to
680   // something else needing this node.
681   if (TLO.Old.getNode()->use_empty()) {
682     removeFromWorkList(TLO.Old.getNode());
683
684     // If the operands of this node are only used by the node, they will now
685     // be dead.  Make sure to visit them first to delete dead nodes early.
686     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
687       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
688         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
689
690     DAG.DeleteNode(TLO.Old.getNode());
691   }
692 }
693
694 /// SimplifyDemandedBits - Check the specified integer node value to see if
695 /// it can be simplified or if things it uses can be simplified by bit
696 /// propagation.  If so, return true.
697 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
698   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
699   APInt KnownZero, KnownOne;
700   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
701     return false;
702
703   // Revisit the node.
704   AddToWorkList(Op.getNode());
705
706   // Replace the old value with the new one.
707   ++NodesCombined;
708   DEBUG(dbgs() << "\nReplacing.2 ";
709         TLO.Old.getNode()->dump(&DAG);
710         dbgs() << "\nWith: ";
711         TLO.New.getNode()->dump(&DAG);
712         dbgs() << '\n');
713
714   CommitTargetLoweringOpt(TLO);
715   return true;
716 }
717
718 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
719   SDLoc dl(Load);
720   EVT VT = Load->getValueType(0);
721   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
722
723   DEBUG(dbgs() << "\nReplacing.9 ";
724         Load->dump(&DAG);
725         dbgs() << "\nWith: ";
726         Trunc.getNode()->dump(&DAG);
727         dbgs() << '\n');
728   WorkListRemover DeadNodes(*this);
729   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
730   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
731   removeFromWorkList(Load);
732   DAG.DeleteNode(Load);
733   AddToWorkList(Trunc.getNode());
734 }
735
736 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
737   Replace = false;
738   SDLoc dl(Op);
739   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
740     EVT MemVT = LD->getMemoryVT();
741     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
742       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
743                                                   : ISD::EXTLOAD)
744       : LD->getExtensionType();
745     Replace = true;
746     return DAG.getExtLoad(ExtType, dl, PVT,
747                           LD->getChain(), LD->getBasePtr(),
748                           LD->getPointerInfo(),
749                           MemVT, LD->isVolatile(),
750                           LD->isNonTemporal(), LD->getAlignment());
751   }
752
753   unsigned Opc = Op.getOpcode();
754   switch (Opc) {
755   default: break;
756   case ISD::AssertSext:
757     return DAG.getNode(ISD::AssertSext, dl, PVT,
758                        SExtPromoteOperand(Op.getOperand(0), PVT),
759                        Op.getOperand(1));
760   case ISD::AssertZext:
761     return DAG.getNode(ISD::AssertZext, dl, PVT,
762                        ZExtPromoteOperand(Op.getOperand(0), PVT),
763                        Op.getOperand(1));
764   case ISD::Constant: {
765     unsigned ExtOpc =
766       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
767     return DAG.getNode(ExtOpc, dl, PVT, Op);
768   }
769   }
770
771   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
772     return SDValue();
773   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
774 }
775
776 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
777   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
778     return SDValue();
779   EVT OldVT = Op.getValueType();
780   SDLoc dl(Op);
781   bool Replace = false;
782   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
783   if (NewOp.getNode() == 0)
784     return SDValue();
785   AddToWorkList(NewOp.getNode());
786
787   if (Replace)
788     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
789   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
790                      DAG.getValueType(OldVT));
791 }
792
793 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
794   EVT OldVT = Op.getValueType();
795   SDLoc dl(Op);
796   bool Replace = false;
797   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
798   if (NewOp.getNode() == 0)
799     return SDValue();
800   AddToWorkList(NewOp.getNode());
801
802   if (Replace)
803     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
804   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
805 }
806
807 /// PromoteIntBinOp - Promote the specified integer binary operation if the
808 /// target indicates it is beneficial. e.g. On x86, it's usually better to
809 /// promote i16 operations to i32 since i16 instructions are longer.
810 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
811   if (!LegalOperations)
812     return SDValue();
813
814   EVT VT = Op.getValueType();
815   if (VT.isVector() || !VT.isInteger())
816     return SDValue();
817
818   // If operation type is 'undesirable', e.g. i16 on x86, consider
819   // promoting it.
820   unsigned Opc = Op.getOpcode();
821   if (TLI.isTypeDesirableForOp(Opc, VT))
822     return SDValue();
823
824   EVT PVT = VT;
825   // Consult target whether it is a good idea to promote this operation and
826   // what's the right type to promote it to.
827   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
828     assert(PVT != VT && "Don't know what type to promote to!");
829
830     bool Replace0 = false;
831     SDValue N0 = Op.getOperand(0);
832     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
833     if (NN0.getNode() == 0)
834       return SDValue();
835
836     bool Replace1 = false;
837     SDValue N1 = Op.getOperand(1);
838     SDValue NN1;
839     if (N0 == N1)
840       NN1 = NN0;
841     else {
842       NN1 = PromoteOperand(N1, PVT, Replace1);
843       if (NN1.getNode() == 0)
844         return SDValue();
845     }
846
847     AddToWorkList(NN0.getNode());
848     if (NN1.getNode())
849       AddToWorkList(NN1.getNode());
850
851     if (Replace0)
852       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
853     if (Replace1)
854       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
855
856     DEBUG(dbgs() << "\nPromoting ";
857           Op.getNode()->dump(&DAG));
858     SDLoc dl(Op);
859     return DAG.getNode(ISD::TRUNCATE, dl, VT,
860                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
861   }
862   return SDValue();
863 }
864
865 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
866 /// target indicates it is beneficial. e.g. On x86, it's usually better to
867 /// promote i16 operations to i32 since i16 instructions are longer.
868 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
869   if (!LegalOperations)
870     return SDValue();
871
872   EVT VT = Op.getValueType();
873   if (VT.isVector() || !VT.isInteger())
874     return SDValue();
875
876   // If operation type is 'undesirable', e.g. i16 on x86, consider
877   // promoting it.
878   unsigned Opc = Op.getOpcode();
879   if (TLI.isTypeDesirableForOp(Opc, VT))
880     return SDValue();
881
882   EVT PVT = VT;
883   // Consult target whether it is a good idea to promote this operation and
884   // what's the right type to promote it to.
885   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
886     assert(PVT != VT && "Don't know what type to promote to!");
887
888     bool Replace = false;
889     SDValue N0 = Op.getOperand(0);
890     if (Opc == ISD::SRA)
891       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
892     else if (Opc == ISD::SRL)
893       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
894     else
895       N0 = PromoteOperand(N0, PVT, Replace);
896     if (N0.getNode() == 0)
897       return SDValue();
898
899     AddToWorkList(N0.getNode());
900     if (Replace)
901       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
902
903     DEBUG(dbgs() << "\nPromoting ";
904           Op.getNode()->dump(&DAG));
905     SDLoc dl(Op);
906     return DAG.getNode(ISD::TRUNCATE, dl, VT,
907                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
908   }
909   return SDValue();
910 }
911
912 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
913   if (!LegalOperations)
914     return SDValue();
915
916   EVT VT = Op.getValueType();
917   if (VT.isVector() || !VT.isInteger())
918     return SDValue();
919
920   // If operation type is 'undesirable', e.g. i16 on x86, consider
921   // promoting it.
922   unsigned Opc = Op.getOpcode();
923   if (TLI.isTypeDesirableForOp(Opc, VT))
924     return SDValue();
925
926   EVT PVT = VT;
927   // Consult target whether it is a good idea to promote this operation and
928   // what's the right type to promote it to.
929   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
930     assert(PVT != VT && "Don't know what type to promote to!");
931     // fold (aext (aext x)) -> (aext x)
932     // fold (aext (zext x)) -> (zext x)
933     // fold (aext (sext x)) -> (sext x)
934     DEBUG(dbgs() << "\nPromoting ";
935           Op.getNode()->dump(&DAG));
936     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
937   }
938   return SDValue();
939 }
940
941 bool DAGCombiner::PromoteLoad(SDValue Op) {
942   if (!LegalOperations)
943     return false;
944
945   EVT VT = Op.getValueType();
946   if (VT.isVector() || !VT.isInteger())
947     return false;
948
949   // If operation type is 'undesirable', e.g. i16 on x86, consider
950   // promoting it.
951   unsigned Opc = Op.getOpcode();
952   if (TLI.isTypeDesirableForOp(Opc, VT))
953     return false;
954
955   EVT PVT = VT;
956   // Consult target whether it is a good idea to promote this operation and
957   // what's the right type to promote it to.
958   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
959     assert(PVT != VT && "Don't know what type to promote to!");
960
961     SDLoc dl(Op);
962     SDNode *N = Op.getNode();
963     LoadSDNode *LD = cast<LoadSDNode>(N);
964     EVT MemVT = LD->getMemoryVT();
965     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
966       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
967                                                   : ISD::EXTLOAD)
968       : LD->getExtensionType();
969     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
970                                    LD->getChain(), LD->getBasePtr(),
971                                    LD->getPointerInfo(),
972                                    MemVT, LD->isVolatile(),
973                                    LD->isNonTemporal(), LD->getAlignment());
974     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
975
976     DEBUG(dbgs() << "\nPromoting ";
977           N->dump(&DAG);
978           dbgs() << "\nTo: ";
979           Result.getNode()->dump(&DAG);
980           dbgs() << '\n');
981     WorkListRemover DeadNodes(*this);
982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
983     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
984     removeFromWorkList(N);
985     DAG.DeleteNode(N);
986     AddToWorkList(Result.getNode());
987     return true;
988   }
989   return false;
990 }
991
992
993 //===----------------------------------------------------------------------===//
994 //  Main DAG Combiner implementation
995 //===----------------------------------------------------------------------===//
996
997 void DAGCombiner::Run(CombineLevel AtLevel) {
998   // set the instance variables, so that the various visit routines may use it.
999   Level = AtLevel;
1000   LegalOperations = Level >= AfterLegalizeVectorOps;
1001   LegalTypes = Level >= AfterLegalizeTypes;
1002
1003   // Add all the dag nodes to the worklist.
1004   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1005        E = DAG.allnodes_end(); I != E; ++I)
1006     AddToWorkList(I);
1007
1008   // Create a dummy node (which is not added to allnodes), that adds a reference
1009   // to the root node, preventing it from being deleted, and tracking any
1010   // changes of the root.
1011   HandleSDNode Dummy(DAG.getRoot());
1012
1013   // The root of the dag may dangle to deleted nodes until the dag combiner is
1014   // done.  Set it to null to avoid confusion.
1015   DAG.setRoot(SDValue());
1016
1017   // while the worklist isn't empty, find a node and
1018   // try and combine it.
1019   while (!WorkListContents.empty()) {
1020     SDNode *N;
1021     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1022     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1023     // worklist *should* contain, and check the node we want to visit is should
1024     // actually be visited.
1025     do {
1026       N = WorkListOrder.pop_back_val();
1027     } while (!WorkListContents.erase(N));
1028
1029     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1030     // N is deleted from the DAG, since they too may now be dead or may have a
1031     // reduced number of uses, allowing other xforms.
1032     if (N->use_empty() && N != &Dummy) {
1033       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1034         AddToWorkList(N->getOperand(i).getNode());
1035
1036       DAG.DeleteNode(N);
1037       continue;
1038     }
1039
1040     SDValue RV = combine(N);
1041
1042     if (RV.getNode() == 0)
1043       continue;
1044
1045     ++NodesCombined;
1046
1047     // If we get back the same node we passed in, rather than a new node or
1048     // zero, we know that the node must have defined multiple values and
1049     // CombineTo was used.  Since CombineTo takes care of the worklist
1050     // mechanics for us, we have no work to do in this case.
1051     if (RV.getNode() == N)
1052       continue;
1053
1054     assert(N->getOpcode() != ISD::DELETED_NODE &&
1055            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1056            "Node was deleted but visit returned new node!");
1057
1058     DEBUG(dbgs() << "\nReplacing.3 ";
1059           N->dump(&DAG);
1060           dbgs() << "\nWith: ";
1061           RV.getNode()->dump(&DAG);
1062           dbgs() << '\n');
1063
1064     // Transfer debug value.
1065     DAG.TransferDbgValues(SDValue(N, 0), RV);
1066     WorkListRemover DeadNodes(*this);
1067     if (N->getNumValues() == RV.getNode()->getNumValues())
1068       DAG.ReplaceAllUsesWith(N, RV.getNode());
1069     else {
1070       assert(N->getValueType(0) == RV.getValueType() &&
1071              N->getNumValues() == 1 && "Type mismatch");
1072       SDValue OpV = RV;
1073       DAG.ReplaceAllUsesWith(N, &OpV);
1074     }
1075
1076     // Push the new node and any users onto the worklist
1077     AddToWorkList(RV.getNode());
1078     AddUsersToWorkList(RV.getNode());
1079
1080     // Add any uses of the old node to the worklist in case this node is the
1081     // last one that uses them.  They may become dead after this node is
1082     // deleted.
1083     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1084       AddToWorkList(N->getOperand(i).getNode());
1085
1086     // Finally, if the node is now dead, remove it from the graph.  The node
1087     // may not be dead if the replacement process recursively simplified to
1088     // something else needing this node.
1089     if (N->use_empty()) {
1090       // Nodes can be reintroduced into the worklist.  Make sure we do not
1091       // process a node that has been replaced.
1092       removeFromWorkList(N);
1093
1094       // Finally, since the node is now dead, remove it from the graph.
1095       DAG.DeleteNode(N);
1096     }
1097   }
1098
1099   // If the root changed (e.g. it was a dead load, update the root).
1100   DAG.setRoot(Dummy.getValue());
1101   DAG.RemoveDeadNodes();
1102 }
1103
1104 SDValue DAGCombiner::visit(SDNode *N) {
1105   switch (N->getOpcode()) {
1106   default: break;
1107   case ISD::TokenFactor:        return visitTokenFactor(N);
1108   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1109   case ISD::ADD:                return visitADD(N);
1110   case ISD::SUB:                return visitSUB(N);
1111   case ISD::ADDC:               return visitADDC(N);
1112   case ISD::SUBC:               return visitSUBC(N);
1113   case ISD::ADDE:               return visitADDE(N);
1114   case ISD::SUBE:               return visitSUBE(N);
1115   case ISD::MUL:                return visitMUL(N);
1116   case ISD::SDIV:               return visitSDIV(N);
1117   case ISD::UDIV:               return visitUDIV(N);
1118   case ISD::SREM:               return visitSREM(N);
1119   case ISD::UREM:               return visitUREM(N);
1120   case ISD::MULHU:              return visitMULHU(N);
1121   case ISD::MULHS:              return visitMULHS(N);
1122   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1123   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1124   case ISD::SMULO:              return visitSMULO(N);
1125   case ISD::UMULO:              return visitUMULO(N);
1126   case ISD::SDIVREM:            return visitSDIVREM(N);
1127   case ISD::UDIVREM:            return visitUDIVREM(N);
1128   case ISD::AND:                return visitAND(N);
1129   case ISD::OR:                 return visitOR(N);
1130   case ISD::XOR:                return visitXOR(N);
1131   case ISD::SHL:                return visitSHL(N);
1132   case ISD::SRA:                return visitSRA(N);
1133   case ISD::SRL:                return visitSRL(N);
1134   case ISD::CTLZ:               return visitCTLZ(N);
1135   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1136   case ISD::CTTZ:               return visitCTTZ(N);
1137   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1138   case ISD::CTPOP:              return visitCTPOP(N);
1139   case ISD::SELECT:             return visitSELECT(N);
1140   case ISD::VSELECT:            return visitVSELECT(N);
1141   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1142   case ISD::SETCC:              return visitSETCC(N);
1143   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1144   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1145   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1146   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1147   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1148   case ISD::BITCAST:            return visitBITCAST(N);
1149   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1150   case ISD::FADD:               return visitFADD(N);
1151   case ISD::FSUB:               return visitFSUB(N);
1152   case ISD::FMUL:               return visitFMUL(N);
1153   case ISD::FMA:                return visitFMA(N);
1154   case ISD::FDIV:               return visitFDIV(N);
1155   case ISD::FREM:               return visitFREM(N);
1156   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1157   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1158   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1159   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1160   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1161   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1162   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1163   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1164   case ISD::FNEG:               return visitFNEG(N);
1165   case ISD::FABS:               return visitFABS(N);
1166   case ISD::FFLOOR:             return visitFFLOOR(N);
1167   case ISD::FCEIL:              return visitFCEIL(N);
1168   case ISD::FTRUNC:             return visitFTRUNC(N);
1169   case ISD::BRCOND:             return visitBRCOND(N);
1170   case ISD::BR_CC:              return visitBR_CC(N);
1171   case ISD::LOAD:               return visitLOAD(N);
1172   case ISD::STORE:              return visitSTORE(N);
1173   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1174   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1175   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1176   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1177   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1178   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1179   }
1180   return SDValue();
1181 }
1182
1183 SDValue DAGCombiner::combine(SDNode *N) {
1184   SDValue RV = visit(N);
1185
1186   // If nothing happened, try a target-specific DAG combine.
1187   if (RV.getNode() == 0) {
1188     assert(N->getOpcode() != ISD::DELETED_NODE &&
1189            "Node was deleted but visit returned NULL!");
1190
1191     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1192         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1193
1194       // Expose the DAG combiner to the target combiner impls.
1195       TargetLowering::DAGCombinerInfo
1196         DagCombineInfo(DAG, Level, false, this);
1197
1198       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1199     }
1200   }
1201
1202   // If nothing happened still, try promoting the operation.
1203   if (RV.getNode() == 0) {
1204     switch (N->getOpcode()) {
1205     default: break;
1206     case ISD::ADD:
1207     case ISD::SUB:
1208     case ISD::MUL:
1209     case ISD::AND:
1210     case ISD::OR:
1211     case ISD::XOR:
1212       RV = PromoteIntBinOp(SDValue(N, 0));
1213       break;
1214     case ISD::SHL:
1215     case ISD::SRA:
1216     case ISD::SRL:
1217       RV = PromoteIntShiftOp(SDValue(N, 0));
1218       break;
1219     case ISD::SIGN_EXTEND:
1220     case ISD::ZERO_EXTEND:
1221     case ISD::ANY_EXTEND:
1222       RV = PromoteExtend(SDValue(N, 0));
1223       break;
1224     case ISD::LOAD:
1225       if (PromoteLoad(SDValue(N, 0)))
1226         RV = SDValue(N, 0);
1227       break;
1228     }
1229   }
1230
1231   // If N is a commutative binary node, try commuting it to enable more
1232   // sdisel CSE.
1233   if (RV.getNode() == 0 &&
1234       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1235       N->getNumValues() == 1) {
1236     SDValue N0 = N->getOperand(0);
1237     SDValue N1 = N->getOperand(1);
1238
1239     // Constant operands are canonicalized to RHS.
1240     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1241       SDValue Ops[] = { N1, N0 };
1242       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1243                                             Ops, 2);
1244       if (CSENode)
1245         return SDValue(CSENode, 0);
1246     }
1247   }
1248
1249   return RV;
1250 }
1251
1252 /// getInputChainForNode - Given a node, return its input chain if it has one,
1253 /// otherwise return a null sd operand.
1254 static SDValue getInputChainForNode(SDNode *N) {
1255   if (unsigned NumOps = N->getNumOperands()) {
1256     if (N->getOperand(0).getValueType() == MVT::Other)
1257       return N->getOperand(0);
1258     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1259       return N->getOperand(NumOps-1);
1260     for (unsigned i = 1; i < NumOps-1; ++i)
1261       if (N->getOperand(i).getValueType() == MVT::Other)
1262         return N->getOperand(i);
1263   }
1264   return SDValue();
1265 }
1266
1267 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1268   // If N has two operands, where one has an input chain equal to the other,
1269   // the 'other' chain is redundant.
1270   if (N->getNumOperands() == 2) {
1271     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1272       return N->getOperand(0);
1273     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1274       return N->getOperand(1);
1275   }
1276
1277   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1278   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1279   SmallPtrSet<SDNode*, 16> SeenOps;
1280   bool Changed = false;             // If we should replace this token factor.
1281
1282   // Start out with this token factor.
1283   TFs.push_back(N);
1284
1285   // Iterate through token factors.  The TFs grows when new token factors are
1286   // encountered.
1287   for (unsigned i = 0; i < TFs.size(); ++i) {
1288     SDNode *TF = TFs[i];
1289
1290     // Check each of the operands.
1291     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1292       SDValue Op = TF->getOperand(i);
1293
1294       switch (Op.getOpcode()) {
1295       case ISD::EntryToken:
1296         // Entry tokens don't need to be added to the list. They are
1297         // rededundant.
1298         Changed = true;
1299         break;
1300
1301       case ISD::TokenFactor:
1302         if (Op.hasOneUse() &&
1303             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1304           // Queue up for processing.
1305           TFs.push_back(Op.getNode());
1306           // Clean up in case the token factor is removed.
1307           AddToWorkList(Op.getNode());
1308           Changed = true;
1309           break;
1310         }
1311         // Fall thru
1312
1313       default:
1314         // Only add if it isn't already in the list.
1315         if (SeenOps.insert(Op.getNode()))
1316           Ops.push_back(Op);
1317         else
1318           Changed = true;
1319         break;
1320       }
1321     }
1322   }
1323
1324   SDValue Result;
1325
1326   // If we've change things around then replace token factor.
1327   if (Changed) {
1328     if (Ops.empty()) {
1329       // The entry token is the only possible outcome.
1330       Result = DAG.getEntryNode();
1331     } else {
1332       // New and improved token factor.
1333       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1334                            MVT::Other, &Ops[0], Ops.size());
1335     }
1336
1337     // Don't add users to work list.
1338     return CombineTo(N, Result, false);
1339   }
1340
1341   return Result;
1342 }
1343
1344 /// MERGE_VALUES can always be eliminated.
1345 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1346   WorkListRemover DeadNodes(*this);
1347   // Replacing results may cause a different MERGE_VALUES to suddenly
1348   // be CSE'd with N, and carry its uses with it. Iterate until no
1349   // uses remain, to ensure that the node can be safely deleted.
1350   // First add the users of this node to the work list so that they
1351   // can be tried again once they have new operands.
1352   AddUsersToWorkList(N);
1353   do {
1354     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1355       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1356   } while (!N->use_empty());
1357   removeFromWorkList(N);
1358   DAG.DeleteNode(N);
1359   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1360 }
1361
1362 static
1363 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1364                               SelectionDAG &DAG) {
1365   EVT VT = N0.getValueType();
1366   SDValue N00 = N0.getOperand(0);
1367   SDValue N01 = N0.getOperand(1);
1368   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1369
1370   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1371       isa<ConstantSDNode>(N00.getOperand(1))) {
1372     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1373     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1374                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1375                                  N00.getOperand(0), N01),
1376                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1377                                  N00.getOperand(1), N01));
1378     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1379   }
1380
1381   return SDValue();
1382 }
1383
1384 SDValue DAGCombiner::visitADD(SDNode *N) {
1385   SDValue N0 = N->getOperand(0);
1386   SDValue N1 = N->getOperand(1);
1387   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1389   EVT VT = N0.getValueType();
1390
1391   // fold vector ops
1392   if (VT.isVector()) {
1393     SDValue FoldedVOp = SimplifyVBinOp(N);
1394     if (FoldedVOp.getNode()) return FoldedVOp;
1395
1396     // fold (add x, 0) -> x, vector edition
1397     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1398       return N0;
1399     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1400       return N1;
1401   }
1402
1403   // fold (add x, undef) -> undef
1404   if (N0.getOpcode() == ISD::UNDEF)
1405     return N0;
1406   if (N1.getOpcode() == ISD::UNDEF)
1407     return N1;
1408   // fold (add c1, c2) -> c1+c2
1409   if (N0C && N1C)
1410     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1411   // canonicalize constant to RHS
1412   if (N0C && !N1C)
1413     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1414   // fold (add x, 0) -> x
1415   if (N1C && N1C->isNullValue())
1416     return N0;
1417   // fold (add Sym, c) -> Sym+c
1418   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1419     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1420         GA->getOpcode() == ISD::GlobalAddress)
1421       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1422                                   GA->getOffset() +
1423                                     (uint64_t)N1C->getSExtValue());
1424   // fold ((c1-A)+c2) -> (c1+c2)-A
1425   if (N1C && N0.getOpcode() == ISD::SUB)
1426     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1427       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1428                          DAG.getConstant(N1C->getAPIntValue()+
1429                                          N0C->getAPIntValue(), VT),
1430                          N0.getOperand(1));
1431   // reassociate add
1432   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1433   if (RADD.getNode() != 0)
1434     return RADD;
1435   // fold ((0-A) + B) -> B-A
1436   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1437       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1438     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1439   // fold (A + (0-B)) -> A-B
1440   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1441       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1442     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1443   // fold (A+(B-A)) -> B
1444   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1445     return N1.getOperand(0);
1446   // fold ((B-A)+A) -> B
1447   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1448     return N0.getOperand(0);
1449   // fold (A+(B-(A+C))) to (B-C)
1450   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1451       N0 == N1.getOperand(1).getOperand(0))
1452     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1453                        N1.getOperand(1).getOperand(1));
1454   // fold (A+(B-(C+A))) to (B-C)
1455   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1456       N0 == N1.getOperand(1).getOperand(1))
1457     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1458                        N1.getOperand(1).getOperand(0));
1459   // fold (A+((B-A)+or-C)) to (B+or-C)
1460   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1461       N1.getOperand(0).getOpcode() == ISD::SUB &&
1462       N0 == N1.getOperand(0).getOperand(1))
1463     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1464                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1465
1466   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1467   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1468     SDValue N00 = N0.getOperand(0);
1469     SDValue N01 = N0.getOperand(1);
1470     SDValue N10 = N1.getOperand(0);
1471     SDValue N11 = N1.getOperand(1);
1472
1473     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1474       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1475                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1476                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1477   }
1478
1479   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1480     return SDValue(N, 0);
1481
1482   // fold (a+b) -> (a|b) iff a and b share no bits.
1483   if (VT.isInteger() && !VT.isVector()) {
1484     APInt LHSZero, LHSOne;
1485     APInt RHSZero, RHSOne;
1486     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1487
1488     if (LHSZero.getBoolValue()) {
1489       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1490
1491       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1492       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1493       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1494         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1495     }
1496   }
1497
1498   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1499   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1500     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1501     if (Result.getNode()) return Result;
1502   }
1503   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1504     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1505     if (Result.getNode()) return Result;
1506   }
1507
1508   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1509   if (N1.getOpcode() == ISD::SHL &&
1510       N1.getOperand(0).getOpcode() == ISD::SUB)
1511     if (ConstantSDNode *C =
1512           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1513       if (C->getAPIntValue() == 0)
1514         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1515                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1516                                        N1.getOperand(0).getOperand(1),
1517                                        N1.getOperand(1)));
1518   if (N0.getOpcode() == ISD::SHL &&
1519       N0.getOperand(0).getOpcode() == ISD::SUB)
1520     if (ConstantSDNode *C =
1521           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1522       if (C->getAPIntValue() == 0)
1523         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1524                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1525                                        N0.getOperand(0).getOperand(1),
1526                                        N0.getOperand(1)));
1527
1528   if (N1.getOpcode() == ISD::AND) {
1529     SDValue AndOp0 = N1.getOperand(0);
1530     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1531     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1532     unsigned DestBits = VT.getScalarType().getSizeInBits();
1533
1534     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1535     // and similar xforms where the inner op is either ~0 or 0.
1536     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1537       SDLoc DL(N);
1538       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1539     }
1540   }
1541
1542   // add (sext i1), X -> sub X, (zext i1)
1543   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1544       N0.getOperand(0).getValueType() == MVT::i1 &&
1545       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1546     SDLoc DL(N);
1547     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1548     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1549   }
1550
1551   return SDValue();
1552 }
1553
1554 SDValue DAGCombiner::visitADDC(SDNode *N) {
1555   SDValue N0 = N->getOperand(0);
1556   SDValue N1 = N->getOperand(1);
1557   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1558   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559   EVT VT = N0.getValueType();
1560
1561   // If the flag result is dead, turn this into an ADD.
1562   if (!N->hasAnyUseOfValue(1))
1563     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1564                      DAG.getNode(ISD::CARRY_FALSE,
1565                                  SDLoc(N), MVT::Glue));
1566
1567   // canonicalize constant to RHS.
1568   if (N0C && !N1C)
1569     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1570
1571   // fold (addc x, 0) -> x + no carry out
1572   if (N1C && N1C->isNullValue())
1573     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1574                                         SDLoc(N), MVT::Glue));
1575
1576   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1577   APInt LHSZero, LHSOne;
1578   APInt RHSZero, RHSOne;
1579   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1580
1581   if (LHSZero.getBoolValue()) {
1582     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1583
1584     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1586     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1587       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1588                        DAG.getNode(ISD::CARRY_FALSE,
1589                                    SDLoc(N), MVT::Glue));
1590   }
1591
1592   return SDValue();
1593 }
1594
1595 SDValue DAGCombiner::visitADDE(SDNode *N) {
1596   SDValue N0 = N->getOperand(0);
1597   SDValue N1 = N->getOperand(1);
1598   SDValue CarryIn = N->getOperand(2);
1599   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1600   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1601
1602   // canonicalize constant to RHS
1603   if (N0C && !N1C)
1604     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1605                        N1, N0, CarryIn);
1606
1607   // fold (adde x, y, false) -> (addc x, y)
1608   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1609     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1610
1611   return SDValue();
1612 }
1613
1614 // Since it may not be valid to emit a fold to zero for vector initializers
1615 // check if we can before folding.
1616 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1617                              SelectionDAG &DAG,
1618                              bool LegalOperations, bool LegalTypes) {
1619   if (!VT.isVector())
1620     return DAG.getConstant(0, VT);
1621   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1622     // Produce a vector of zeros.
1623     EVT ElemTy = VT.getVectorElementType();
1624     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1625                       TargetLowering::TypePromoteInteger)
1626       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1627     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1628            "Type for zero vector elements is not legal");
1629     SDValue El = DAG.getConstant(0, ElemTy);
1630     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1631     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1632       &Ops[0], Ops.size());
1633   }
1634   return SDValue();
1635 }
1636
1637 SDValue DAGCombiner::visitSUB(SDNode *N) {
1638   SDValue N0 = N->getOperand(0);
1639   SDValue N1 = N->getOperand(1);
1640   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1642   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1643     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1644   EVT VT = N0.getValueType();
1645
1646   // fold vector ops
1647   if (VT.isVector()) {
1648     SDValue FoldedVOp = SimplifyVBinOp(N);
1649     if (FoldedVOp.getNode()) return FoldedVOp;
1650
1651     // fold (sub x, 0) -> x, vector edition
1652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1653       return N0;
1654   }
1655
1656   // fold (sub x, x) -> 0
1657   // FIXME: Refactor this and xor and other similar operations together.
1658   if (N0 == N1)
1659     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1660   // fold (sub c1, c2) -> c1-c2
1661   if (N0C && N1C)
1662     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1663   // fold (sub x, c) -> (add x, -c)
1664   if (N1C)
1665     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1666                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1667   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1668   if (N0C && N0C->isAllOnesValue())
1669     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1670   // fold A-(A-B) -> B
1671   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1672     return N1.getOperand(1);
1673   // fold (A+B)-A -> B
1674   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1675     return N0.getOperand(1);
1676   // fold (A+B)-B -> A
1677   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1678     return N0.getOperand(0);
1679   // fold C2-(A+C1) -> (C2-C1)-A
1680   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1681     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1682                                    VT);
1683     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1684                        N1.getOperand(0));
1685   }
1686   // fold ((A+(B+or-C))-B) -> A+or-C
1687   if (N0.getOpcode() == ISD::ADD &&
1688       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1689        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1690       N0.getOperand(1).getOperand(0) == N1)
1691     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1692                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1693   // fold ((A+(C+B))-B) -> A+C
1694   if (N0.getOpcode() == ISD::ADD &&
1695       N0.getOperand(1).getOpcode() == ISD::ADD &&
1696       N0.getOperand(1).getOperand(1) == N1)
1697     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1698                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1699   // fold ((A-(B-C))-C) -> A-B
1700   if (N0.getOpcode() == ISD::SUB &&
1701       N0.getOperand(1).getOpcode() == ISD::SUB &&
1702       N0.getOperand(1).getOperand(1) == N1)
1703     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1704                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1705
1706   // If either operand of a sub is undef, the result is undef
1707   if (N0.getOpcode() == ISD::UNDEF)
1708     return N0;
1709   if (N1.getOpcode() == ISD::UNDEF)
1710     return N1;
1711
1712   // If the relocation model supports it, consider symbol offsets.
1713   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1714     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1715       // fold (sub Sym, c) -> Sym-c
1716       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1717         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1718                                     GA->getOffset() -
1719                                       (uint64_t)N1C->getSExtValue());
1720       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1721       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1722         if (GA->getGlobal() == GB->getGlobal())
1723           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1724                                  VT);
1725     }
1726
1727   return SDValue();
1728 }
1729
1730 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1731   SDValue N0 = N->getOperand(0);
1732   SDValue N1 = N->getOperand(1);
1733   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735   EVT VT = N0.getValueType();
1736
1737   // If the flag result is dead, turn this into an SUB.
1738   if (!N->hasAnyUseOfValue(1))
1739     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1740                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1741                                  MVT::Glue));
1742
1743   // fold (subc x, x) -> 0 + no borrow
1744   if (N0 == N1)
1745     return CombineTo(N, DAG.getConstant(0, VT),
1746                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1747                                  MVT::Glue));
1748
1749   // fold (subc x, 0) -> x + no borrow
1750   if (N1C && N1C->isNullValue())
1751     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1752                                         MVT::Glue));
1753
1754   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1755   if (N0C && N0C->isAllOnesValue())
1756     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1757                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1758                                  MVT::Glue));
1759
1760   return SDValue();
1761 }
1762
1763 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1764   SDValue N0 = N->getOperand(0);
1765   SDValue N1 = N->getOperand(1);
1766   SDValue CarryIn = N->getOperand(2);
1767
1768   // fold (sube x, y, false) -> (subc x, y)
1769   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1770     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1771
1772   return SDValue();
1773 }
1774
1775 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1776 /// all the same constant or undefined.
1777 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1778   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1779   if (!C)
1780     return false;
1781
1782   APInt SplatUndef;
1783   unsigned SplatBitSize;
1784   bool HasAnyUndefs;
1785   EVT EltVT = N->getValueType(0).getVectorElementType();
1786   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1787                              HasAnyUndefs) &&
1788           EltVT.getSizeInBits() >= SplatBitSize);
1789 }
1790
1791 SDValue DAGCombiner::visitMUL(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   EVT VT = N0.getValueType();
1795
1796   // fold (mul x, undef) -> 0
1797   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1798     return DAG.getConstant(0, VT);
1799
1800   bool N0IsConst = false;
1801   bool N1IsConst = false;
1802   APInt ConstValue0, ConstValue1;
1803   // fold vector ops
1804   if (VT.isVector()) {
1805     SDValue FoldedVOp = SimplifyVBinOp(N);
1806     if (FoldedVOp.getNode()) return FoldedVOp;
1807
1808     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1809     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1810   } else {
1811     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1812     ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1813     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1814     ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1815   }
1816
1817   // fold (mul c1, c2) -> c1*c2
1818   if (N0IsConst && N1IsConst)
1819     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1820
1821   // canonicalize constant to RHS
1822   if (N0IsConst && !N1IsConst)
1823     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1824   // fold (mul x, 0) -> 0
1825   if (N1IsConst && ConstValue1 == 0)
1826     return N1;
1827   // We require a splat of the entire scalar bit width for non-contiguous
1828   // bit patterns.
1829   bool IsFullSplat =
1830     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1831   // fold (mul x, 1) -> x
1832   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1833     return N0;
1834   // fold (mul x, -1) -> 0-x
1835   if (N1IsConst && ConstValue1.isAllOnesValue())
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837                        DAG.getConstant(0, VT), N0);
1838   // fold (mul x, (1 << c)) -> x << c
1839   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1840     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1841                        DAG.getConstant(ConstValue1.logBase2(),
1842                                        getShiftAmountTy(N0.getValueType())));
1843   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1844   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1845     unsigned Log2Val = (-ConstValue1).logBase2();
1846     // FIXME: If the input is something that is easily negated (e.g. a
1847     // single-use add), we should put the negate there.
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        DAG.getConstant(0, VT),
1850                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1851                             DAG.getConstant(Log2Val,
1852                                       getShiftAmountTy(N0.getValueType()))));
1853   }
1854
1855   APInt Val;
1856   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1857   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1858       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1859                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1860     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1861                              N1, N0.getOperand(1));
1862     AddToWorkList(C3.getNode());
1863     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1864                        N0.getOperand(0), C3);
1865   }
1866
1867   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1868   // use.
1869   {
1870     SDValue Sh(0,0), Y(0,0);
1871     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1872     if (N0.getOpcode() == ISD::SHL &&
1873         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1874                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1875         N0.getNode()->hasOneUse()) {
1876       Sh = N0; Y = N1;
1877     } else if (N1.getOpcode() == ISD::SHL &&
1878                isa<ConstantSDNode>(N1.getOperand(1)) &&
1879                N1.getNode()->hasOneUse()) {
1880       Sh = N1; Y = N0;
1881     }
1882
1883     if (Sh.getNode()) {
1884       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1885                                 Sh.getOperand(0), Y);
1886       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1887                          Mul, Sh.getOperand(1));
1888     }
1889   }
1890
1891   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1892   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1893       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1894                      isa<ConstantSDNode>(N0.getOperand(1))))
1895     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1896                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1897                                    N0.getOperand(0), N1),
1898                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1899                                    N0.getOperand(1), N1));
1900
1901   // reassociate mul
1902   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1903   if (RMUL.getNode() != 0)
1904     return RMUL;
1905
1906   return SDValue();
1907 }
1908
1909 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1910   SDValue N0 = N->getOperand(0);
1911   SDValue N1 = N->getOperand(1);
1912   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1913   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1914   EVT VT = N->getValueType(0);
1915
1916   // fold vector ops
1917   if (VT.isVector()) {
1918     SDValue FoldedVOp = SimplifyVBinOp(N);
1919     if (FoldedVOp.getNode()) return FoldedVOp;
1920   }
1921
1922   // fold (sdiv c1, c2) -> c1/c2
1923   if (N0C && N1C && !N1C->isNullValue())
1924     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1925   // fold (sdiv X, 1) -> X
1926   if (N1C && N1C->getAPIntValue() == 1LL)
1927     return N0;
1928   // fold (sdiv X, -1) -> 0-X
1929   if (N1C && N1C->isAllOnesValue())
1930     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1931                        DAG.getConstant(0, VT), N0);
1932   // If we know the sign bits of both operands are zero, strength reduce to a
1933   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1934   if (!VT.isVector()) {
1935     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1936       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1937                          N0, N1);
1938   }
1939   // fold (sdiv X, pow2) -> simple ops after legalize
1940   if (N1C && !N1C->isNullValue() &&
1941       (N1C->getAPIntValue().isPowerOf2() ||
1942        (-N1C->getAPIntValue()).isPowerOf2())) {
1943     // If dividing by powers of two is cheap, then don't perform the following
1944     // fold.
1945     if (TLI.isPow2DivCheap())
1946       return SDValue();
1947
1948     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1949
1950     // Splat the sign bit into the register
1951     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1952                               DAG.getConstant(VT.getSizeInBits()-1,
1953                                        getShiftAmountTy(N0.getValueType())));
1954     AddToWorkList(SGN.getNode());
1955
1956     // Add (N0 < 0) ? abs2 - 1 : 0;
1957     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1958                               DAG.getConstant(VT.getSizeInBits() - lg2,
1959                                        getShiftAmountTy(SGN.getValueType())));
1960     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1961     AddToWorkList(SRL.getNode());
1962     AddToWorkList(ADD.getNode());    // Divide by pow2
1963     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1964                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1965
1966     // If we're dividing by a positive value, we're done.  Otherwise, we must
1967     // negate the result.
1968     if (N1C->getAPIntValue().isNonNegative())
1969       return SRA;
1970
1971     AddToWorkList(SRA.getNode());
1972     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1973                        DAG.getConstant(0, VT), SRA);
1974   }
1975
1976   // if integer divide is expensive and we satisfy the requirements, emit an
1977   // alternate sequence.
1978   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1979     SDValue Op = BuildSDIV(N);
1980     if (Op.getNode()) return Op;
1981   }
1982
1983   // undef / X -> 0
1984   if (N0.getOpcode() == ISD::UNDEF)
1985     return DAG.getConstant(0, VT);
1986   // X / undef -> undef
1987   if (N1.getOpcode() == ISD::UNDEF)
1988     return N1;
1989
1990   return SDValue();
1991 }
1992
1993 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1994   SDValue N0 = N->getOperand(0);
1995   SDValue N1 = N->getOperand(1);
1996   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1998   EVT VT = N->getValueType(0);
1999
2000   // fold vector ops
2001   if (VT.isVector()) {
2002     SDValue FoldedVOp = SimplifyVBinOp(N);
2003     if (FoldedVOp.getNode()) return FoldedVOp;
2004   }
2005
2006   // fold (udiv c1, c2) -> c1/c2
2007   if (N0C && N1C && !N1C->isNullValue())
2008     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2009   // fold (udiv x, (1 << c)) -> x >>u c
2010   if (N1C && N1C->getAPIntValue().isPowerOf2())
2011     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2012                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2013                                        getShiftAmountTy(N0.getValueType())));
2014   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2015   if (N1.getOpcode() == ISD::SHL) {
2016     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2017       if (SHC->getAPIntValue().isPowerOf2()) {
2018         EVT ADDVT = N1.getOperand(1).getValueType();
2019         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2020                                   N1.getOperand(1),
2021                                   DAG.getConstant(SHC->getAPIntValue()
2022                                                                   .logBase2(),
2023                                                   ADDVT));
2024         AddToWorkList(Add.getNode());
2025         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2026       }
2027     }
2028   }
2029   // fold (udiv x, c) -> alternate
2030   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2031     SDValue Op = BuildUDIV(N);
2032     if (Op.getNode()) return Op;
2033   }
2034
2035   // undef / X -> 0
2036   if (N0.getOpcode() == ISD::UNDEF)
2037     return DAG.getConstant(0, VT);
2038   // X / undef -> undef
2039   if (N1.getOpcode() == ISD::UNDEF)
2040     return N1;
2041
2042   return SDValue();
2043 }
2044
2045 SDValue DAGCombiner::visitSREM(SDNode *N) {
2046   SDValue N0 = N->getOperand(0);
2047   SDValue N1 = N->getOperand(1);
2048   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2050   EVT VT = N->getValueType(0);
2051
2052   // fold (srem c1, c2) -> c1%c2
2053   if (N0C && N1C && !N1C->isNullValue())
2054     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2055   // If we know the sign bits of both operands are zero, strength reduce to a
2056   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2057   if (!VT.isVector()) {
2058     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2059       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2060   }
2061
2062   // If X/C can be simplified by the division-by-constant logic, lower
2063   // X%C to the equivalent of X-X/C*C.
2064   if (N1C && !N1C->isNullValue()) {
2065     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2066     AddToWorkList(Div.getNode());
2067     SDValue OptimizedDiv = combine(Div.getNode());
2068     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2069       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2070                                 OptimizedDiv, N1);
2071       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2072       AddToWorkList(Mul.getNode());
2073       return Sub;
2074     }
2075   }
2076
2077   // undef % X -> 0
2078   if (N0.getOpcode() == ISD::UNDEF)
2079     return DAG.getConstant(0, VT);
2080   // X % undef -> undef
2081   if (N1.getOpcode() == ISD::UNDEF)
2082     return N1;
2083
2084   return SDValue();
2085 }
2086
2087 SDValue DAGCombiner::visitUREM(SDNode *N) {
2088   SDValue N0 = N->getOperand(0);
2089   SDValue N1 = N->getOperand(1);
2090   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2091   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2092   EVT VT = N->getValueType(0);
2093
2094   // fold (urem c1, c2) -> c1%c2
2095   if (N0C && N1C && !N1C->isNullValue())
2096     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2097   // fold (urem x, pow2) -> (and x, pow2-1)
2098   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2099     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2100                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2101   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2102   if (N1.getOpcode() == ISD::SHL) {
2103     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2104       if (SHC->getAPIntValue().isPowerOf2()) {
2105         SDValue Add =
2106           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2107                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2108                                  VT));
2109         AddToWorkList(Add.getNode());
2110         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2111       }
2112     }
2113   }
2114
2115   // If X/C can be simplified by the division-by-constant logic, lower
2116   // X%C to the equivalent of X-X/C*C.
2117   if (N1C && !N1C->isNullValue()) {
2118     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2119     AddToWorkList(Div.getNode());
2120     SDValue OptimizedDiv = combine(Div.getNode());
2121     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2122       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2123                                 OptimizedDiv, N1);
2124       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2125       AddToWorkList(Mul.getNode());
2126       return Sub;
2127     }
2128   }
2129
2130   // undef % X -> 0
2131   if (N0.getOpcode() == ISD::UNDEF)
2132     return DAG.getConstant(0, VT);
2133   // X % undef -> undef
2134   if (N1.getOpcode() == ISD::UNDEF)
2135     return N1;
2136
2137   return SDValue();
2138 }
2139
2140 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2141   SDValue N0 = N->getOperand(0);
2142   SDValue N1 = N->getOperand(1);
2143   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2144   EVT VT = N->getValueType(0);
2145   SDLoc DL(N);
2146
2147   // fold (mulhs x, 0) -> 0
2148   if (N1C && N1C->isNullValue())
2149     return N1;
2150   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2151   if (N1C && N1C->getAPIntValue() == 1)
2152     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2153                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2154                                        getShiftAmountTy(N0.getValueType())));
2155   // fold (mulhs x, undef) -> 0
2156   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2157     return DAG.getConstant(0, VT);
2158
2159   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2160   // plus a shift.
2161   if (VT.isSimple() && !VT.isVector()) {
2162     MVT Simple = VT.getSimpleVT();
2163     unsigned SimpleSize = Simple.getSizeInBits();
2164     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2165     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2166       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2167       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2168       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2169       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2170             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2171       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2172     }
2173   }
2174
2175   return SDValue();
2176 }
2177
2178 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2179   SDValue N0 = N->getOperand(0);
2180   SDValue N1 = N->getOperand(1);
2181   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2182   EVT VT = N->getValueType(0);
2183   SDLoc DL(N);
2184
2185   // fold (mulhu x, 0) -> 0
2186   if (N1C && N1C->isNullValue())
2187     return N1;
2188   // fold (mulhu x, 1) -> 0
2189   if (N1C && N1C->getAPIntValue() == 1)
2190     return DAG.getConstant(0, N0.getValueType());
2191   // fold (mulhu x, undef) -> 0
2192   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2193     return DAG.getConstant(0, VT);
2194
2195   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2196   // plus a shift.
2197   if (VT.isSimple() && !VT.isVector()) {
2198     MVT Simple = VT.getSimpleVT();
2199     unsigned SimpleSize = Simple.getSizeInBits();
2200     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2201     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2202       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2203       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2204       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2205       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2206             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2207       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2208     }
2209   }
2210
2211   return SDValue();
2212 }
2213
2214 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2215 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2216 /// that are being performed. Return true if a simplification was made.
2217 ///
2218 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2219                                                 unsigned HiOp) {
2220   // If the high half is not needed, just compute the low half.
2221   bool HiExists = N->hasAnyUseOfValue(1);
2222   if (!HiExists &&
2223       (!LegalOperations ||
2224        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2225     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2226                               N->op_begin(), N->getNumOperands());
2227     return CombineTo(N, Res, Res);
2228   }
2229
2230   // If the low half is not needed, just compute the high half.
2231   bool LoExists = N->hasAnyUseOfValue(0);
2232   if (!LoExists &&
2233       (!LegalOperations ||
2234        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2235     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2236                               N->op_begin(), N->getNumOperands());
2237     return CombineTo(N, Res, Res);
2238   }
2239
2240   // If both halves are used, return as it is.
2241   if (LoExists && HiExists)
2242     return SDValue();
2243
2244   // If the two computed results can be simplified separately, separate them.
2245   if (LoExists) {
2246     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2247                              N->op_begin(), N->getNumOperands());
2248     AddToWorkList(Lo.getNode());
2249     SDValue LoOpt = combine(Lo.getNode());
2250     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2251         (!LegalOperations ||
2252          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2253       return CombineTo(N, LoOpt, LoOpt);
2254   }
2255
2256   if (HiExists) {
2257     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2258                              N->op_begin(), N->getNumOperands());
2259     AddToWorkList(Hi.getNode());
2260     SDValue HiOpt = combine(Hi.getNode());
2261     if (HiOpt.getNode() && HiOpt != Hi &&
2262         (!LegalOperations ||
2263          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2264       return CombineTo(N, HiOpt, HiOpt);
2265   }
2266
2267   return SDValue();
2268 }
2269
2270 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2271   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2272   if (Res.getNode()) return Res;
2273
2274   EVT VT = N->getValueType(0);
2275   SDLoc DL(N);
2276
2277   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2278   // plus a shift.
2279   if (VT.isSimple() && !VT.isVector()) {
2280     MVT Simple = VT.getSimpleVT();
2281     unsigned SimpleSize = Simple.getSizeInBits();
2282     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2283     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2284       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2285       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2286       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2287       // Compute the high part as N1.
2288       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2289             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2290       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2291       // Compute the low part as N0.
2292       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2293       return CombineTo(N, Lo, Hi);
2294     }
2295   }
2296
2297   return SDValue();
2298 }
2299
2300 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2301   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2302   if (Res.getNode()) return Res;
2303
2304   EVT VT = N->getValueType(0);
2305   SDLoc DL(N);
2306
2307   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2308   // plus a shift.
2309   if (VT.isSimple() && !VT.isVector()) {
2310     MVT Simple = VT.getSimpleVT();
2311     unsigned SimpleSize = Simple.getSizeInBits();
2312     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2315       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2316       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2317       // Compute the high part as N1.
2318       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2319             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2320       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2321       // Compute the low part as N0.
2322       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2323       return CombineTo(N, Lo, Hi);
2324     }
2325   }
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2331   // (smulo x, 2) -> (saddo x, x)
2332   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2333     if (C2->getAPIntValue() == 2)
2334       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2335                          N->getOperand(0), N->getOperand(0));
2336
2337   return SDValue();
2338 }
2339
2340 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2341   // (umulo x, 2) -> (uaddo x, x)
2342   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2343     if (C2->getAPIntValue() == 2)
2344       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2345                          N->getOperand(0), N->getOperand(0));
2346
2347   return SDValue();
2348 }
2349
2350 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2351   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2352   if (Res.getNode()) return Res;
2353
2354   return SDValue();
2355 }
2356
2357 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2358   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2359   if (Res.getNode()) return Res;
2360
2361   return SDValue();
2362 }
2363
2364 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2365 /// two operands of the same opcode, try to simplify it.
2366 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2367   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2368   EVT VT = N0.getValueType();
2369   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2370
2371   // Bail early if none of these transforms apply.
2372   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2373
2374   // For each of OP in AND/OR/XOR:
2375   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2376   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2377   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2378   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2379   //
2380   // do not sink logical op inside of a vector extend, since it may combine
2381   // into a vsetcc.
2382   EVT Op0VT = N0.getOperand(0).getValueType();
2383   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2384        N0.getOpcode() == ISD::SIGN_EXTEND ||
2385        // Avoid infinite looping with PromoteIntBinOp.
2386        (N0.getOpcode() == ISD::ANY_EXTEND &&
2387         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2388        (N0.getOpcode() == ISD::TRUNCATE &&
2389         (!TLI.isZExtFree(VT, Op0VT) ||
2390          !TLI.isTruncateFree(Op0VT, VT)) &&
2391         TLI.isTypeLegal(Op0VT))) &&
2392       !VT.isVector() &&
2393       Op0VT == N1.getOperand(0).getValueType() &&
2394       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2395     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2396                                  N0.getOperand(0).getValueType(),
2397                                  N0.getOperand(0), N1.getOperand(0));
2398     AddToWorkList(ORNode.getNode());
2399     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2400   }
2401
2402   // For each of OP in SHL/SRL/SRA/AND...
2403   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2404   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2405   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2406   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2407        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2408       N0.getOperand(1) == N1.getOperand(1)) {
2409     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2410                                  N0.getOperand(0).getValueType(),
2411                                  N0.getOperand(0), N1.getOperand(0));
2412     AddToWorkList(ORNode.getNode());
2413     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2414                        ORNode, N0.getOperand(1));
2415   }
2416
2417   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2418   // Only perform this optimization after type legalization and before
2419   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2420   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2421   // we don't want to undo this promotion.
2422   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2423   // on scalars.
2424   if ((N0.getOpcode() == ISD::BITCAST ||
2425        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2426       Level == AfterLegalizeTypes) {
2427     SDValue In0 = N0.getOperand(0);
2428     SDValue In1 = N1.getOperand(0);
2429     EVT In0Ty = In0.getValueType();
2430     EVT In1Ty = In1.getValueType();
2431     SDLoc DL(N);
2432     // If both incoming values are integers, and the original types are the
2433     // same.
2434     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2435       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2436       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2437       AddToWorkList(Op.getNode());
2438       return BC;
2439     }
2440   }
2441
2442   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2443   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2444   // If both shuffles use the same mask, and both shuffle within a single
2445   // vector, then it is worthwhile to move the swizzle after the operation.
2446   // The type-legalizer generates this pattern when loading illegal
2447   // vector types from memory. In many cases this allows additional shuffle
2448   // optimizations.
2449   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2450       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2451       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2452     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2453     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2454
2455     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2456            "Inputs to shuffles are not the same type");
2457
2458     unsigned NumElts = VT.getVectorNumElements();
2459
2460     // Check that both shuffles use the same mask. The masks are known to be of
2461     // the same length because the result vector type is the same.
2462     bool SameMask = true;
2463     for (unsigned i = 0; i != NumElts; ++i) {
2464       int Idx0 = SVN0->getMaskElt(i);
2465       int Idx1 = SVN1->getMaskElt(i);
2466       if (Idx0 != Idx1) {
2467         SameMask = false;
2468         break;
2469       }
2470     }
2471
2472     if (SameMask) {
2473       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2474                                N0.getOperand(0), N1.getOperand(0));
2475       AddToWorkList(Op.getNode());
2476       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2477                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2478     }
2479   }
2480
2481   return SDValue();
2482 }
2483
2484 SDValue DAGCombiner::visitAND(SDNode *N) {
2485   SDValue N0 = N->getOperand(0);
2486   SDValue N1 = N->getOperand(1);
2487   SDValue LL, LR, RL, RR, CC0, CC1;
2488   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2489   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2490   EVT VT = N1.getValueType();
2491   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2492
2493   // fold vector ops
2494   if (VT.isVector()) {
2495     SDValue FoldedVOp = SimplifyVBinOp(N);
2496     if (FoldedVOp.getNode()) return FoldedVOp;
2497
2498     // fold (and x, 0) -> 0, vector edition
2499     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2500       return N0;
2501     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2502       return N1;
2503
2504     // fold (and x, -1) -> x, vector edition
2505     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2506       return N1;
2507     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2508       return N0;
2509   }
2510
2511   // fold (and x, undef) -> 0
2512   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2513     return DAG.getConstant(0, VT);
2514   // fold (and c1, c2) -> c1&c2
2515   if (N0C && N1C)
2516     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2517   // canonicalize constant to RHS
2518   if (N0C && !N1C)
2519     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2520   // fold (and x, -1) -> x
2521   if (N1C && N1C->isAllOnesValue())
2522     return N0;
2523   // if (and x, c) is known to be zero, return 0
2524   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2525                                    APInt::getAllOnesValue(BitWidth)))
2526     return DAG.getConstant(0, VT);
2527   // reassociate and
2528   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2529   if (RAND.getNode() != 0)
2530     return RAND;
2531   // fold (and (or x, C), D) -> D if (C & D) == D
2532   if (N1C && N0.getOpcode() == ISD::OR)
2533     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2534       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2535         return N1;
2536   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2537   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2538     SDValue N0Op0 = N0.getOperand(0);
2539     APInt Mask = ~N1C->getAPIntValue();
2540     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2541     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2542       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2543                                  N0.getValueType(), N0Op0);
2544
2545       // Replace uses of the AND with uses of the Zero extend node.
2546       CombineTo(N, Zext);
2547
2548       // We actually want to replace all uses of the any_extend with the
2549       // zero_extend, to avoid duplicating things.  This will later cause this
2550       // AND to be folded.
2551       CombineTo(N0.getNode(), Zext);
2552       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2553     }
2554   }
2555   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2556   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2557   // already be zero by virtue of the width of the base type of the load.
2558   //
2559   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2560   // more cases.
2561   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2562        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2563       N0.getOpcode() == ISD::LOAD) {
2564     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2565                                          N0 : N0.getOperand(0) );
2566
2567     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2568     // This can be a pure constant or a vector splat, in which case we treat the
2569     // vector as a scalar and use the splat value.
2570     APInt Constant = APInt::getNullValue(1);
2571     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2572       Constant = C->getAPIntValue();
2573     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2574       APInt SplatValue, SplatUndef;
2575       unsigned SplatBitSize;
2576       bool HasAnyUndefs;
2577       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2578                                              SplatBitSize, HasAnyUndefs);
2579       if (IsSplat) {
2580         // Undef bits can contribute to a possible optimisation if set, so
2581         // set them.
2582         SplatValue |= SplatUndef;
2583
2584         // The splat value may be something like "0x00FFFFFF", which means 0 for
2585         // the first vector value and FF for the rest, repeating. We need a mask
2586         // that will apply equally to all members of the vector, so AND all the
2587         // lanes of the constant together.
2588         EVT VT = Vector->getValueType(0);
2589         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2590
2591         // If the splat value has been compressed to a bitlength lower
2592         // than the size of the vector lane, we need to re-expand it to
2593         // the lane size.
2594         if (BitWidth > SplatBitSize)
2595           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2596                SplatBitSize < BitWidth;
2597                SplatBitSize = SplatBitSize * 2)
2598             SplatValue |= SplatValue.shl(SplatBitSize);
2599
2600         Constant = APInt::getAllOnesValue(BitWidth);
2601         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2602           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2603       }
2604     }
2605
2606     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2607     // actually legal and isn't going to get expanded, else this is a false
2608     // optimisation.
2609     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2610                                                     Load->getMemoryVT());
2611
2612     // Resize the constant to the same size as the original memory access before
2613     // extension. If it is still the AllOnesValue then this AND is completely
2614     // unneeded.
2615     Constant =
2616       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2617
2618     bool B;
2619     switch (Load->getExtensionType()) {
2620     default: B = false; break;
2621     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2622     case ISD::ZEXTLOAD:
2623     case ISD::NON_EXTLOAD: B = true; break;
2624     }
2625
2626     if (B && Constant.isAllOnesValue()) {
2627       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2628       // preserve semantics once we get rid of the AND.
2629       SDValue NewLoad(Load, 0);
2630       if (Load->getExtensionType() == ISD::EXTLOAD) {
2631         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2632                               Load->getValueType(0), SDLoc(Load),
2633                               Load->getChain(), Load->getBasePtr(),
2634                               Load->getOffset(), Load->getMemoryVT(),
2635                               Load->getMemOperand());
2636         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2637         if (Load->getNumValues() == 3) {
2638           // PRE/POST_INC loads have 3 values.
2639           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2640                            NewLoad.getValue(2) };
2641           CombineTo(Load, To, 3, true);
2642         } else {
2643           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2644         }
2645       }
2646
2647       // Fold the AND away, taking care not to fold to the old load node if we
2648       // replaced it.
2649       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2650
2651       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2652     }
2653   }
2654   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2655   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2656     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2657     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2658
2659     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2660         LL.getValueType().isInteger()) {
2661       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2662       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2663         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2664                                      LR.getValueType(), LL, RL);
2665         AddToWorkList(ORNode.getNode());
2666         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2667       }
2668       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2669       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2670         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2671                                       LR.getValueType(), LL, RL);
2672         AddToWorkList(ANDNode.getNode());
2673         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2674       }
2675       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2676       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2677         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2678                                      LR.getValueType(), LL, RL);
2679         AddToWorkList(ORNode.getNode());
2680         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2681       }
2682     }
2683     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2684     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2685         Op0 == Op1 && LL.getValueType().isInteger() &&
2686       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2687                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2688                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2689                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2690       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2691                                     LL, DAG.getConstant(1, LL.getValueType()));
2692       AddToWorkList(ADDNode.getNode());
2693       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2694                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2695     }
2696     // canonicalize equivalent to ll == rl
2697     if (LL == RR && LR == RL) {
2698       Op1 = ISD::getSetCCSwappedOperands(Op1);
2699       std::swap(RL, RR);
2700     }
2701     if (LL == RL && LR == RR) {
2702       bool isInteger = LL.getValueType().isInteger();
2703       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2704       if (Result != ISD::SETCC_INVALID &&
2705           (!LegalOperations ||
2706            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2707             TLI.isOperationLegal(ISD::SETCC,
2708                             getSetCCResultType(N0.getSimpleValueType())))))
2709         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2710                             LL, LR, Result);
2711     }
2712   }
2713
2714   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2715   if (N0.getOpcode() == N1.getOpcode()) {
2716     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2717     if (Tmp.getNode()) return Tmp;
2718   }
2719
2720   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2721   // fold (and (sra)) -> (and (srl)) when possible.
2722   if (!VT.isVector() &&
2723       SimplifyDemandedBits(SDValue(N, 0)))
2724     return SDValue(N, 0);
2725
2726   // fold (zext_inreg (extload x)) -> (zextload x)
2727   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2728     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2729     EVT MemVT = LN0->getMemoryVT();
2730     // If we zero all the possible extended bits, then we can turn this into
2731     // a zextload if we are running before legalize or the operation is legal.
2732     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2733     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2734                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2735         ((!LegalOperations && !LN0->isVolatile()) ||
2736          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2737       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2738                                        LN0->getChain(), LN0->getBasePtr(),
2739                                        LN0->getPointerInfo(), MemVT,
2740                                        LN0->isVolatile(), LN0->isNonTemporal(),
2741                                        LN0->getAlignment());
2742       AddToWorkList(N);
2743       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2744       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2745     }
2746   }
2747   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2748   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2749       N0.hasOneUse()) {
2750     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2751     EVT MemVT = LN0->getMemoryVT();
2752     // If we zero all the possible extended bits, then we can turn this into
2753     // a zextload if we are running before legalize or the operation is legal.
2754     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2755     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2756                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2757         ((!LegalOperations && !LN0->isVolatile()) ||
2758          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2759       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2760                                        LN0->getChain(),
2761                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2762                                        MemVT,
2763                                        LN0->isVolatile(), LN0->isNonTemporal(),
2764                                        LN0->getAlignment());
2765       AddToWorkList(N);
2766       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2767       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2768     }
2769   }
2770
2771   // fold (and (load x), 255) -> (zextload x, i8)
2772   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2773   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2774   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2775               (N0.getOpcode() == ISD::ANY_EXTEND &&
2776                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2777     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2778     LoadSDNode *LN0 = HasAnyExt
2779       ? cast<LoadSDNode>(N0.getOperand(0))
2780       : cast<LoadSDNode>(N0);
2781     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2782         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2783       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2784       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2785         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2786         EVT LoadedVT = LN0->getMemoryVT();
2787
2788         if (ExtVT == LoadedVT &&
2789             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2790           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2791
2792           SDValue NewLoad =
2793             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2794                            LN0->getChain(), LN0->getBasePtr(),
2795                            LN0->getPointerInfo(),
2796                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2797                            LN0->getAlignment());
2798           AddToWorkList(N);
2799           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2800           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2801         }
2802
2803         // Do not change the width of a volatile load.
2804         // Do not generate loads of non-round integer types since these can
2805         // be expensive (and would be wrong if the type is not byte sized).
2806         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2807             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2808           EVT PtrType = LN0->getOperand(1).getValueType();
2809
2810           unsigned Alignment = LN0->getAlignment();
2811           SDValue NewPtr = LN0->getBasePtr();
2812
2813           // For big endian targets, we need to add an offset to the pointer
2814           // to load the correct bytes.  For little endian systems, we merely
2815           // need to read fewer bytes from the same pointer.
2816           if (TLI.isBigEndian()) {
2817             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2818             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2819             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2820             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2821                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2822             Alignment = MinAlign(Alignment, PtrOff);
2823           }
2824
2825           AddToWorkList(NewPtr.getNode());
2826
2827           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2828           SDValue Load =
2829             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2830                            LN0->getChain(), NewPtr,
2831                            LN0->getPointerInfo(),
2832                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2833                            Alignment);
2834           AddToWorkList(N);
2835           CombineTo(LN0, Load, Load.getValue(1));
2836           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2837         }
2838       }
2839     }
2840   }
2841
2842   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2843       VT.getSizeInBits() <= 64) {
2844     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2845       APInt ADDC = ADDI->getAPIntValue();
2846       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2847         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2848         // immediate for an add, but it is legal if its top c2 bits are set,
2849         // transform the ADD so the immediate doesn't need to be materialized
2850         // in a register.
2851         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2852           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2853                                              SRLI->getZExtValue());
2854           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2855             ADDC |= Mask;
2856             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2857               SDValue NewAdd =
2858                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2859                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2860               CombineTo(N0.getNode(), NewAdd);
2861               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2862             }
2863           }
2864         }
2865       }
2866     }
2867   }
2868
2869   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2870   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2871     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2872                                        N0.getOperand(1), false);
2873     if (BSwap.getNode())
2874       return BSwap;
2875   }
2876
2877   return SDValue();
2878 }
2879
2880 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2881 ///
2882 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2883                                         bool DemandHighBits) {
2884   if (!LegalOperations)
2885     return SDValue();
2886
2887   EVT VT = N->getValueType(0);
2888   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2889     return SDValue();
2890   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2891     return SDValue();
2892
2893   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2894   bool LookPassAnd0 = false;
2895   bool LookPassAnd1 = false;
2896   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2897       std::swap(N0, N1);
2898   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2899       std::swap(N0, N1);
2900   if (N0.getOpcode() == ISD::AND) {
2901     if (!N0.getNode()->hasOneUse())
2902       return SDValue();
2903     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2904     if (!N01C || N01C->getZExtValue() != 0xFF00)
2905       return SDValue();
2906     N0 = N0.getOperand(0);
2907     LookPassAnd0 = true;
2908   }
2909
2910   if (N1.getOpcode() == ISD::AND) {
2911     if (!N1.getNode()->hasOneUse())
2912       return SDValue();
2913     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2914     if (!N11C || N11C->getZExtValue() != 0xFF)
2915       return SDValue();
2916     N1 = N1.getOperand(0);
2917     LookPassAnd1 = true;
2918   }
2919
2920   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2921     std::swap(N0, N1);
2922   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2923     return SDValue();
2924   if (!N0.getNode()->hasOneUse() ||
2925       !N1.getNode()->hasOneUse())
2926     return SDValue();
2927
2928   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2929   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2930   if (!N01C || !N11C)
2931     return SDValue();
2932   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2933     return SDValue();
2934
2935   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2936   SDValue N00 = N0->getOperand(0);
2937   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2938     if (!N00.getNode()->hasOneUse())
2939       return SDValue();
2940     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2941     if (!N001C || N001C->getZExtValue() != 0xFF)
2942       return SDValue();
2943     N00 = N00.getOperand(0);
2944     LookPassAnd0 = true;
2945   }
2946
2947   SDValue N10 = N1->getOperand(0);
2948   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2949     if (!N10.getNode()->hasOneUse())
2950       return SDValue();
2951     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2952     if (!N101C || N101C->getZExtValue() != 0xFF00)
2953       return SDValue();
2954     N10 = N10.getOperand(0);
2955     LookPassAnd1 = true;
2956   }
2957
2958   if (N00 != N10)
2959     return SDValue();
2960
2961   // Make sure everything beyond the low halfword gets set to zero since the SRL
2962   // 16 will clear the top bits.
2963   unsigned OpSizeInBits = VT.getSizeInBits();
2964   if (DemandHighBits && OpSizeInBits > 16) {
2965     // If the left-shift isn't masked out then the only way this is a bswap is
2966     // if all bits beyond the low 8 are 0. In that case the entire pattern
2967     // reduces to a left shift anyway: leave it for other parts of the combiner.
2968     if (!LookPassAnd0)
2969       return SDValue();
2970
2971     // However, if the right shift isn't masked out then it might be because
2972     // it's not needed. See if we can spot that too.
2973     if (!LookPassAnd1 &&
2974         !DAG.MaskedValueIsZero(
2975             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2976       return SDValue();
2977   }
2978
2979   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2980   if (OpSizeInBits > 16)
2981     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2982                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2983   return Res;
2984 }
2985
2986 /// isBSwapHWordElement - Return true if the specified node is an element
2987 /// that makes up a 32-bit packed halfword byteswap. i.e.
2988 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2989 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2990   if (!N.getNode()->hasOneUse())
2991     return false;
2992
2993   unsigned Opc = N.getOpcode();
2994   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2995     return false;
2996
2997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2998   if (!N1C)
2999     return false;
3000
3001   unsigned Num;
3002   switch (N1C->getZExtValue()) {
3003   default:
3004     return false;
3005   case 0xFF:       Num = 0; break;
3006   case 0xFF00:     Num = 1; break;
3007   case 0xFF0000:   Num = 2; break;
3008   case 0xFF000000: Num = 3; break;
3009   }
3010
3011   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3012   SDValue N0 = N.getOperand(0);
3013   if (Opc == ISD::AND) {
3014     if (Num == 0 || Num == 2) {
3015       // (x >> 8) & 0xff
3016       // (x >> 8) & 0xff0000
3017       if (N0.getOpcode() != ISD::SRL)
3018         return false;
3019       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3020       if (!C || C->getZExtValue() != 8)
3021         return false;
3022     } else {
3023       // (x << 8) & 0xff00
3024       // (x << 8) & 0xff000000
3025       if (N0.getOpcode() != ISD::SHL)
3026         return false;
3027       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028       if (!C || C->getZExtValue() != 8)
3029         return false;
3030     }
3031   } else if (Opc == ISD::SHL) {
3032     // (x & 0xff) << 8
3033     // (x & 0xff0000) << 8
3034     if (Num != 0 && Num != 2)
3035       return false;
3036     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3037     if (!C || C->getZExtValue() != 8)
3038       return false;
3039   } else { // Opc == ISD::SRL
3040     // (x & 0xff00) >> 8
3041     // (x & 0xff000000) >> 8
3042     if (Num != 1 && Num != 3)
3043       return false;
3044     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3045     if (!C || C->getZExtValue() != 8)
3046       return false;
3047   }
3048
3049   if (Parts[Num])
3050     return false;
3051
3052   Parts[Num] = N0.getOperand(0).getNode();
3053   return true;
3054 }
3055
3056 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3057 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3058 /// => (rotl (bswap x), 16)
3059 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3060   if (!LegalOperations)
3061     return SDValue();
3062
3063   EVT VT = N->getValueType(0);
3064   if (VT != MVT::i32)
3065     return SDValue();
3066   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3067     return SDValue();
3068
3069   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3070   // Look for either
3071   // (or (or (and), (and)), (or (and), (and)))
3072   // (or (or (or (and), (and)), (and)), (and))
3073   if (N0.getOpcode() != ISD::OR)
3074     return SDValue();
3075   SDValue N00 = N0.getOperand(0);
3076   SDValue N01 = N0.getOperand(1);
3077
3078   if (N1.getOpcode() == ISD::OR &&
3079       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3080     // (or (or (and), (and)), (or (and), (and)))
3081     SDValue N000 = N00.getOperand(0);
3082     if (!isBSwapHWordElement(N000, Parts))
3083       return SDValue();
3084
3085     SDValue N001 = N00.getOperand(1);
3086     if (!isBSwapHWordElement(N001, Parts))
3087       return SDValue();
3088     SDValue N010 = N01.getOperand(0);
3089     if (!isBSwapHWordElement(N010, Parts))
3090       return SDValue();
3091     SDValue N011 = N01.getOperand(1);
3092     if (!isBSwapHWordElement(N011, Parts))
3093       return SDValue();
3094   } else {
3095     // (or (or (or (and), (and)), (and)), (and))
3096     if (!isBSwapHWordElement(N1, Parts))
3097       return SDValue();
3098     if (!isBSwapHWordElement(N01, Parts))
3099       return SDValue();
3100     if (N00.getOpcode() != ISD::OR)
3101       return SDValue();
3102     SDValue N000 = N00.getOperand(0);
3103     if (!isBSwapHWordElement(N000, Parts))
3104       return SDValue();
3105     SDValue N001 = N00.getOperand(1);
3106     if (!isBSwapHWordElement(N001, Parts))
3107       return SDValue();
3108   }
3109
3110   // Make sure the parts are all coming from the same node.
3111   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3112     return SDValue();
3113
3114   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3115                               SDValue(Parts[0],0));
3116
3117   // Result of the bswap should be rotated by 16. If it's not legal, then
3118   // do  (x << 16) | (x >> 16).
3119   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3120   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3121     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3122   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3123     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3124   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3125                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3126                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3127 }
3128
3129 SDValue DAGCombiner::visitOR(SDNode *N) {
3130   SDValue N0 = N->getOperand(0);
3131   SDValue N1 = N->getOperand(1);
3132   SDValue LL, LR, RL, RR, CC0, CC1;
3133   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3134   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3135   EVT VT = N1.getValueType();
3136
3137   // fold vector ops
3138   if (VT.isVector()) {
3139     SDValue FoldedVOp = SimplifyVBinOp(N);
3140     if (FoldedVOp.getNode()) return FoldedVOp;
3141
3142     // fold (or x, 0) -> x, vector edition
3143     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3144       return N1;
3145     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3146       return N0;
3147
3148     // fold (or x, -1) -> -1, vector edition
3149     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3150       return N0;
3151     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3152       return N1;
3153   }
3154
3155   // fold (or x, undef) -> -1
3156   if (!LegalOperations &&
3157       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3158     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3159     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3160   }
3161   // fold (or c1, c2) -> c1|c2
3162   if (N0C && N1C)
3163     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3164   // canonicalize constant to RHS
3165   if (N0C && !N1C)
3166     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3167   // fold (or x, 0) -> x
3168   if (N1C && N1C->isNullValue())
3169     return N0;
3170   // fold (or x, -1) -> -1
3171   if (N1C && N1C->isAllOnesValue())
3172     return N1;
3173   // fold (or x, c) -> c iff (x & ~c) == 0
3174   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3175     return N1;
3176
3177   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3178   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3179   if (BSwap.getNode() != 0)
3180     return BSwap;
3181   BSwap = MatchBSwapHWordLow(N, N0, N1);
3182   if (BSwap.getNode() != 0)
3183     return BSwap;
3184
3185   // reassociate or
3186   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3187   if (ROR.getNode() != 0)
3188     return ROR;
3189   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3190   // iff (c1 & c2) == 0.
3191   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3192              isa<ConstantSDNode>(N0.getOperand(1))) {
3193     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3194     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3195       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3196                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3197                                      N0.getOperand(0), N1),
3198                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3199   }
3200   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3201   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3202     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3203     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3204
3205     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3206         LL.getValueType().isInteger()) {
3207       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3208       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3209       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3210           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3211         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3212                                      LR.getValueType(), LL, RL);
3213         AddToWorkList(ORNode.getNode());
3214         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3215       }
3216       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3217       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3218       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3219           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3220         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3221                                       LR.getValueType(), LL, RL);
3222         AddToWorkList(ANDNode.getNode());
3223         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3224       }
3225     }
3226     // canonicalize equivalent to ll == rl
3227     if (LL == RR && LR == RL) {
3228       Op1 = ISD::getSetCCSwappedOperands(Op1);
3229       std::swap(RL, RR);
3230     }
3231     if (LL == RL && LR == RR) {
3232       bool isInteger = LL.getValueType().isInteger();
3233       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3234       if (Result != ISD::SETCC_INVALID &&
3235           (!LegalOperations ||
3236            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3237             TLI.isOperationLegal(ISD::SETCC,
3238               getSetCCResultType(N0.getValueType())))))
3239         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3240                             LL, LR, Result);
3241     }
3242   }
3243
3244   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3245   if (N0.getOpcode() == N1.getOpcode()) {
3246     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3247     if (Tmp.getNode()) return Tmp;
3248   }
3249
3250   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3251   if (N0.getOpcode() == ISD::AND &&
3252       N1.getOpcode() == ISD::AND &&
3253       N0.getOperand(1).getOpcode() == ISD::Constant &&
3254       N1.getOperand(1).getOpcode() == ISD::Constant &&
3255       // Don't increase # computations.
3256       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3257     // We can only do this xform if we know that bits from X that are set in C2
3258     // but not in C1 are already zero.  Likewise for Y.
3259     const APInt &LHSMask =
3260       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3261     const APInt &RHSMask =
3262       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3263
3264     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3265         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3266       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3267                               N0.getOperand(0), N1.getOperand(0));
3268       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3269                          DAG.getConstant(LHSMask | RHSMask, VT));
3270     }
3271   }
3272
3273   // See if this is some rotate idiom.
3274   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3275     return SDValue(Rot, 0);
3276
3277   // Simplify the operands using demanded-bits information.
3278   if (!VT.isVector() &&
3279       SimplifyDemandedBits(SDValue(N, 0)))
3280     return SDValue(N, 0);
3281
3282   return SDValue();
3283 }
3284
3285 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3286 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3287   if (Op.getOpcode() == ISD::AND) {
3288     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3289       Mask = Op.getOperand(1);
3290       Op = Op.getOperand(0);
3291     } else {
3292       return false;
3293     }
3294   }
3295
3296   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3297     Shift = Op;
3298     return true;
3299   }
3300
3301   return false;
3302 }
3303
3304 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3305 // idioms for rotate, and if the target supports rotation instructions, generate
3306 // a rot[lr].
3307 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3308   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3309   EVT VT = LHS.getValueType();
3310   if (!TLI.isTypeLegal(VT)) return 0;
3311
3312   // The target must have at least one rotate flavor.
3313   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3314   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3315   if (!HasROTL && !HasROTR) return 0;
3316
3317   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3318   SDValue LHSShift;   // The shift.
3319   SDValue LHSMask;    // AND value if any.
3320   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3321     return 0; // Not part of a rotate.
3322
3323   SDValue RHSShift;   // The shift.
3324   SDValue RHSMask;    // AND value if any.
3325   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3326     return 0; // Not part of a rotate.
3327
3328   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3329     return 0;   // Not shifting the same value.
3330
3331   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3332     return 0;   // Shifts must disagree.
3333
3334   // Canonicalize shl to left side in a shl/srl pair.
3335   if (RHSShift.getOpcode() == ISD::SHL) {
3336     std::swap(LHS, RHS);
3337     std::swap(LHSShift, RHSShift);
3338     std::swap(LHSMask , RHSMask );
3339   }
3340
3341   unsigned OpSizeInBits = VT.getSizeInBits();
3342   SDValue LHSShiftArg = LHSShift.getOperand(0);
3343   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3344   SDValue RHSShiftArg = RHSShift.getOperand(0);
3345   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3346
3347   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3348   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3349   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3350       RHSShiftAmt.getOpcode() == ISD::Constant) {
3351     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3352     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3353     if ((LShVal + RShVal) != OpSizeInBits)
3354       return 0;
3355
3356     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3357                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3358
3359     // If there is an AND of either shifted operand, apply it to the result.
3360     if (LHSMask.getNode() || RHSMask.getNode()) {
3361       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3362
3363       if (LHSMask.getNode()) {
3364         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3365         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3366       }
3367       if (RHSMask.getNode()) {
3368         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3369         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3370       }
3371
3372       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3373     }
3374
3375     return Rot.getNode();
3376   }
3377
3378   // If there is a mask here, and we have a variable shift, we can't be sure
3379   // that we're masking out the right stuff.
3380   if (LHSMask.getNode() || RHSMask.getNode())
3381     return 0;
3382
3383   // If the shift amount is sign/zext/any-extended just peel it off.
3384   SDValue LExtOp0 = LHSShiftAmt;
3385   SDValue RExtOp0 = RHSShiftAmt;
3386   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3387        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3388        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3389        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3390       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3391        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3392        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3393        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3394     LExtOp0 = LHSShiftAmt.getOperand(0);
3395     RExtOp0 = RHSShiftAmt.getOperand(0);
3396   }
3397
3398   if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3399     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3400     //   (rotl x, y)
3401     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3402     //   (rotr x, (sub 32, y))
3403     if (ConstantSDNode *SUBC =
3404             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3405       if (SUBC->getAPIntValue() == OpSizeInBits) {
3406         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3407                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3408       } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3409                  LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3410         // fold (or (shl (*ext x), (*ext y)),
3411         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3412         //   (*ext (rotl x, y))
3413         // fold (or (shl (*ext x), (*ext y)),
3414         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3415         //   (*ext (rotr x, (sub 32, y)))
3416         SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3417         EVT LArgVT = LArgExtOp0.getValueType();
3418         if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3419           SDValue V =
3420               DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3421                           LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3422           return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3423         }
3424       }
3425     }
3426   } else if (LExtOp0.getOpcode() == ISD::SUB &&
3427              RExtOp0 == LExtOp0.getOperand(1)) {
3428     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3429     //   (rotr x, y)
3430     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3431     //   (rotl x, (sub 32, y))
3432     if (ConstantSDNode *SUBC =
3433             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3434       if (SUBC->getAPIntValue() == OpSizeInBits) {
3435         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3436                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3437       } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3438                  RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3439         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3440         //          (srl (*ext x), (*ext y))) ->
3441         //   (*ext (rotl x, y))
3442         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3443         //          (srl (*ext x), (*ext y))) ->
3444         //   (*ext (rotr x, (sub 32, y)))
3445         SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3446         EVT RArgVT = RArgExtOp0.getValueType();
3447         if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3448           SDValue V =
3449               DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3450                           RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3451           return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3452         }
3453       }
3454     }
3455   }
3456
3457   return 0;
3458 }
3459
3460 SDValue DAGCombiner::visitXOR(SDNode *N) {
3461   SDValue N0 = N->getOperand(0);
3462   SDValue N1 = N->getOperand(1);
3463   SDValue LHS, RHS, CC;
3464   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3465   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3466   EVT VT = N0.getValueType();
3467
3468   // fold vector ops
3469   if (VT.isVector()) {
3470     SDValue FoldedVOp = SimplifyVBinOp(N);
3471     if (FoldedVOp.getNode()) return FoldedVOp;
3472
3473     // fold (xor x, 0) -> x, vector edition
3474     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3475       return N1;
3476     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3477       return N0;
3478   }
3479
3480   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3481   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3482     return DAG.getConstant(0, VT);
3483   // fold (xor x, undef) -> undef
3484   if (N0.getOpcode() == ISD::UNDEF)
3485     return N0;
3486   if (N1.getOpcode() == ISD::UNDEF)
3487     return N1;
3488   // fold (xor c1, c2) -> c1^c2
3489   if (N0C && N1C)
3490     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3491   // canonicalize constant to RHS
3492   if (N0C && !N1C)
3493     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3494   // fold (xor x, 0) -> x
3495   if (N1C && N1C->isNullValue())
3496     return N0;
3497   // reassociate xor
3498   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3499   if (RXOR.getNode() != 0)
3500     return RXOR;
3501
3502   // fold !(x cc y) -> (x !cc y)
3503   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3504     bool isInt = LHS.getValueType().isInteger();
3505     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3506                                                isInt);
3507
3508     if (!LegalOperations ||
3509         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3510       switch (N0.getOpcode()) {
3511       default:
3512         llvm_unreachable("Unhandled SetCC Equivalent!");
3513       case ISD::SETCC:
3514         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3515       case ISD::SELECT_CC:
3516         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3517                                N0.getOperand(3), NotCC);
3518       }
3519     }
3520   }
3521
3522   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3523   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3524       N0.getNode()->hasOneUse() &&
3525       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3526     SDValue V = N0.getOperand(0);
3527     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3528                     DAG.getConstant(1, V.getValueType()));
3529     AddToWorkList(V.getNode());
3530     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3531   }
3532
3533   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3534   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3535       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3536     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3537     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3538       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3539       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3540       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3541       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3542       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3543     }
3544   }
3545   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3546   if (N1C && N1C->isAllOnesValue() &&
3547       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3548     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3549     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3550       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3551       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3552       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3553       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3554       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3555     }
3556   }
3557   // fold (xor (and x, y), y) -> (and (not x), y)
3558   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3559       N0->getOperand(1) == N1) {
3560     SDValue X = N0->getOperand(0);
3561     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3562     AddToWorkList(NotX.getNode());
3563     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3564   }
3565   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3566   if (N1C && N0.getOpcode() == ISD::XOR) {
3567     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3568     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3569     if (N00C)
3570       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3571                          DAG.getConstant(N1C->getAPIntValue() ^
3572                                          N00C->getAPIntValue(), VT));
3573     if (N01C)
3574       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3575                          DAG.getConstant(N1C->getAPIntValue() ^
3576                                          N01C->getAPIntValue(), VT));
3577   }
3578   // fold (xor x, x) -> 0
3579   if (N0 == N1)
3580     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3581
3582   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3583   if (N0.getOpcode() == N1.getOpcode()) {
3584     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3585     if (Tmp.getNode()) return Tmp;
3586   }
3587
3588   // Simplify the expression using non-local knowledge.
3589   if (!VT.isVector() &&
3590       SimplifyDemandedBits(SDValue(N, 0)))
3591     return SDValue(N, 0);
3592
3593   return SDValue();
3594 }
3595
3596 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3597 /// the shift amount is a constant.
3598 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3599   SDNode *LHS = N->getOperand(0).getNode();
3600   if (!LHS->hasOneUse()) return SDValue();
3601
3602   // We want to pull some binops through shifts, so that we have (and (shift))
3603   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3604   // thing happens with address calculations, so it's important to canonicalize
3605   // it.
3606   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3607
3608   switch (LHS->getOpcode()) {
3609   default: return SDValue();
3610   case ISD::OR:
3611   case ISD::XOR:
3612     HighBitSet = false; // We can only transform sra if the high bit is clear.
3613     break;
3614   case ISD::AND:
3615     HighBitSet = true;  // We can only transform sra if the high bit is set.
3616     break;
3617   case ISD::ADD:
3618     if (N->getOpcode() != ISD::SHL)
3619       return SDValue(); // only shl(add) not sr[al](add).
3620     HighBitSet = false; // We can only transform sra if the high bit is clear.
3621     break;
3622   }
3623
3624   // We require the RHS of the binop to be a constant as well.
3625   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3626   if (!BinOpCst) return SDValue();
3627
3628   // FIXME: disable this unless the input to the binop is a shift by a constant.
3629   // If it is not a shift, it pessimizes some common cases like:
3630   //
3631   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3632   //    int bar(int *X, int i) { return X[i & 255]; }
3633   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3634   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3635        BinOpLHSVal->getOpcode() != ISD::SRA &&
3636        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3637       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3638     return SDValue();
3639
3640   EVT VT = N->getValueType(0);
3641
3642   // If this is a signed shift right, and the high bit is modified by the
3643   // logical operation, do not perform the transformation. The highBitSet
3644   // boolean indicates the value of the high bit of the constant which would
3645   // cause it to be modified for this operation.
3646   if (N->getOpcode() == ISD::SRA) {
3647     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3648     if (BinOpRHSSignSet != HighBitSet)
3649       return SDValue();
3650   }
3651
3652   // Fold the constants, shifting the binop RHS by the shift amount.
3653   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3654                                N->getValueType(0),
3655                                LHS->getOperand(1), N->getOperand(1));
3656
3657   // Create the new shift.
3658   SDValue NewShift = DAG.getNode(N->getOpcode(),
3659                                  SDLoc(LHS->getOperand(0)),
3660                                  VT, LHS->getOperand(0), N->getOperand(1));
3661
3662   // Create the new binop.
3663   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3664 }
3665
3666 SDValue DAGCombiner::visitSHL(SDNode *N) {
3667   SDValue N0 = N->getOperand(0);
3668   SDValue N1 = N->getOperand(1);
3669   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3670   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3671   EVT VT = N0.getValueType();
3672   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3673
3674   // fold (shl c1, c2) -> c1<<c2
3675   if (N0C && N1C)
3676     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3677   // fold (shl 0, x) -> 0
3678   if (N0C && N0C->isNullValue())
3679     return N0;
3680   // fold (shl x, c >= size(x)) -> undef
3681   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3682     return DAG.getUNDEF(VT);
3683   // fold (shl x, 0) -> x
3684   if (N1C && N1C->isNullValue())
3685     return N0;
3686   // fold (shl undef, x) -> 0
3687   if (N0.getOpcode() == ISD::UNDEF)
3688     return DAG.getConstant(0, VT);
3689   // if (shl x, c) is known to be zero, return 0
3690   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3691                             APInt::getAllOnesValue(OpSizeInBits)))
3692     return DAG.getConstant(0, VT);
3693   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3694   if (N1.getOpcode() == ISD::TRUNCATE &&
3695       N1.getOperand(0).getOpcode() == ISD::AND &&
3696       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3697     SDValue N101 = N1.getOperand(0).getOperand(1);
3698     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3699       EVT TruncVT = N1.getValueType();
3700       SDValue N100 = N1.getOperand(0).getOperand(0);
3701       APInt TruncC = N101C->getAPIntValue();
3702       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3703       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3704                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3705                                      DAG.getNode(ISD::TRUNCATE,
3706                                                  SDLoc(N),
3707                                                  TruncVT, N100),
3708                                      DAG.getConstant(TruncC, TruncVT)));
3709     }
3710   }
3711
3712   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3713     return SDValue(N, 0);
3714
3715   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3716   if (N1C && N0.getOpcode() == ISD::SHL &&
3717       N0.getOperand(1).getOpcode() == ISD::Constant) {
3718     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3719     uint64_t c2 = N1C->getZExtValue();
3720     if (c1 + c2 >= OpSizeInBits)
3721       return DAG.getConstant(0, VT);
3722     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3723                        DAG.getConstant(c1 + c2, N1.getValueType()));
3724   }
3725
3726   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3727   // For this to be valid, the second form must not preserve any of the bits
3728   // that are shifted out by the inner shift in the first form.  This means
3729   // the outer shift size must be >= the number of bits added by the ext.
3730   // As a corollary, we don't care what kind of ext it is.
3731   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3732               N0.getOpcode() == ISD::ANY_EXTEND ||
3733               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3734       N0.getOperand(0).getOpcode() == ISD::SHL &&
3735       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3736     uint64_t c1 =
3737       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3738     uint64_t c2 = N1C->getZExtValue();
3739     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3740     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3741     if (c2 >= OpSizeInBits - InnerShiftSize) {
3742       if (c1 + c2 >= OpSizeInBits)
3743         return DAG.getConstant(0, VT);
3744       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3745                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3746                                      N0.getOperand(0)->getOperand(0)),
3747                          DAG.getConstant(c1 + c2, N1.getValueType()));
3748     }
3749   }
3750
3751   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3752   //                               (and (srl x, (sub c1, c2), MASK)
3753   // Only fold this if the inner shift has no other uses -- if it does, folding
3754   // this will increase the total number of instructions.
3755   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3756       N0.getOperand(1).getOpcode() == ISD::Constant) {
3757     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3758     if (c1 < VT.getSizeInBits()) {
3759       uint64_t c2 = N1C->getZExtValue();
3760       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3761                                          VT.getSizeInBits() - c1);
3762       SDValue Shift;
3763       if (c2 > c1) {
3764         Mask = Mask.shl(c2-c1);
3765         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3766                             DAG.getConstant(c2-c1, N1.getValueType()));
3767       } else {
3768         Mask = Mask.lshr(c1-c2);
3769         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3770                             DAG.getConstant(c1-c2, N1.getValueType()));
3771       }
3772       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3773                          DAG.getConstant(Mask, VT));
3774     }
3775   }
3776   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3777   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3778     SDValue HiBitsMask =
3779       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3780                                             VT.getSizeInBits() -
3781                                               N1C->getZExtValue()),
3782                       VT);
3783     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3784                        HiBitsMask);
3785   }
3786
3787   if (N1C) {
3788     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3789     if (NewSHL.getNode())
3790       return NewSHL;
3791   }
3792
3793   return SDValue();
3794 }
3795
3796 SDValue DAGCombiner::visitSRA(SDNode *N) {
3797   SDValue N0 = N->getOperand(0);
3798   SDValue N1 = N->getOperand(1);
3799   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3800   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3801   EVT VT = N0.getValueType();
3802   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3803
3804   // fold (sra c1, c2) -> (sra c1, c2)
3805   if (N0C && N1C)
3806     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3807   // fold (sra 0, x) -> 0
3808   if (N0C && N0C->isNullValue())
3809     return N0;
3810   // fold (sra -1, x) -> -1
3811   if (N0C && N0C->isAllOnesValue())
3812     return N0;
3813   // fold (sra x, (setge c, size(x))) -> undef
3814   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3815     return DAG.getUNDEF(VT);
3816   // fold (sra x, 0) -> x
3817   if (N1C && N1C->isNullValue())
3818     return N0;
3819   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3820   // sext_inreg.
3821   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3822     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3823     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3824     if (VT.isVector())
3825       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3826                                ExtVT, VT.getVectorNumElements());
3827     if ((!LegalOperations ||
3828          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3829       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3830                          N0.getOperand(0), DAG.getValueType(ExtVT));
3831   }
3832
3833   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3834   if (N1C && N0.getOpcode() == ISD::SRA) {
3835     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3836       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3837       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3838       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3839                          DAG.getConstant(Sum, N1C->getValueType(0)));
3840     }
3841   }
3842
3843   // fold (sra (shl X, m), (sub result_size, n))
3844   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3845   // result_size - n != m.
3846   // If truncate is free for the target sext(shl) is likely to result in better
3847   // code.
3848   if (N0.getOpcode() == ISD::SHL) {
3849     // Get the two constanst of the shifts, CN0 = m, CN = n.
3850     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3851     if (N01C && N1C) {
3852       // Determine what the truncate's result bitsize and type would be.
3853       EVT TruncVT =
3854         EVT::getIntegerVT(*DAG.getContext(),
3855                           OpSizeInBits - N1C->getZExtValue());
3856       // Determine the residual right-shift amount.
3857       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3858
3859       // If the shift is not a no-op (in which case this should be just a sign
3860       // extend already), the truncated to type is legal, sign_extend is legal
3861       // on that type, and the truncate to that type is both legal and free,
3862       // perform the transform.
3863       if ((ShiftAmt > 0) &&
3864           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3865           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3866           TLI.isTruncateFree(VT, TruncVT)) {
3867
3868           SDValue Amt = DAG.getConstant(ShiftAmt,
3869               getShiftAmountTy(N0.getOperand(0).getValueType()));
3870           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3871                                       N0.getOperand(0), Amt);
3872           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3873                                       Shift);
3874           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3875                              N->getValueType(0), Trunc);
3876       }
3877     }
3878   }
3879
3880   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3881   if (N1.getOpcode() == ISD::TRUNCATE &&
3882       N1.getOperand(0).getOpcode() == ISD::AND &&
3883       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3884     SDValue N101 = N1.getOperand(0).getOperand(1);
3885     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3886       EVT TruncVT = N1.getValueType();
3887       SDValue N100 = N1.getOperand(0).getOperand(0);
3888       APInt TruncC = N101C->getAPIntValue();
3889       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3890       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3891                          DAG.getNode(ISD::AND, SDLoc(N),
3892                                      TruncVT,
3893                                      DAG.getNode(ISD::TRUNCATE,
3894                                                  SDLoc(N),
3895                                                  TruncVT, N100),
3896                                      DAG.getConstant(TruncC, TruncVT)));
3897     }
3898   }
3899
3900   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3901   //      if c1 is equal to the number of bits the trunc removes
3902   if (N0.getOpcode() == ISD::TRUNCATE &&
3903       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3904        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3905       N0.getOperand(0).hasOneUse() &&
3906       N0.getOperand(0).getOperand(1).hasOneUse() &&
3907       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3908     EVT LargeVT = N0.getOperand(0).getValueType();
3909     ConstantSDNode *LargeShiftAmt =
3910       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3911
3912     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3913         LargeShiftAmt->getZExtValue()) {
3914       SDValue Amt =
3915         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3916               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3917       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3918                                 N0.getOperand(0).getOperand(0), Amt);
3919       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3920     }
3921   }
3922
3923   // Simplify, based on bits shifted out of the LHS.
3924   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3925     return SDValue(N, 0);
3926
3927
3928   // If the sign bit is known to be zero, switch this to a SRL.
3929   if (DAG.SignBitIsZero(N0))
3930     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3931
3932   if (N1C) {
3933     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3934     if (NewSRA.getNode())
3935       return NewSRA;
3936   }
3937
3938   return SDValue();
3939 }
3940
3941 SDValue DAGCombiner::visitSRL(SDNode *N) {
3942   SDValue N0 = N->getOperand(0);
3943   SDValue N1 = N->getOperand(1);
3944   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3945   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3946   EVT VT = N0.getValueType();
3947   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3948
3949   // fold (srl c1, c2) -> c1 >>u c2
3950   if (N0C && N1C)
3951     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3952   // fold (srl 0, x) -> 0
3953   if (N0C && N0C->isNullValue())
3954     return N0;
3955   // fold (srl x, c >= size(x)) -> undef
3956   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3957     return DAG.getUNDEF(VT);
3958   // fold (srl x, 0) -> x
3959   if (N1C && N1C->isNullValue())
3960     return N0;
3961   // if (srl x, c) is known to be zero, return 0
3962   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3963                                    APInt::getAllOnesValue(OpSizeInBits)))
3964     return DAG.getConstant(0, VT);
3965
3966   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3967   if (N1C && N0.getOpcode() == ISD::SRL &&
3968       N0.getOperand(1).getOpcode() == ISD::Constant) {
3969     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3970     uint64_t c2 = N1C->getZExtValue();
3971     if (c1 + c2 >= OpSizeInBits)
3972       return DAG.getConstant(0, VT);
3973     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3974                        DAG.getConstant(c1 + c2, N1.getValueType()));
3975   }
3976
3977   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3978   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3979       N0.getOperand(0).getOpcode() == ISD::SRL &&
3980       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3981     uint64_t c1 =
3982       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3983     uint64_t c2 = N1C->getZExtValue();
3984     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3985     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3986     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3987     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3988     if (c1 + OpSizeInBits == InnerShiftSize) {
3989       if (c1 + c2 >= InnerShiftSize)
3990         return DAG.getConstant(0, VT);
3991       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3992                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3993                                      N0.getOperand(0)->getOperand(0),
3994                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3995     }
3996   }
3997
3998   // fold (srl (shl x, c), c) -> (and x, cst2)
3999   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4000       N0.getValueSizeInBits() <= 64) {
4001     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4002     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4003                        DAG.getConstant(~0ULL >> ShAmt, VT));
4004   }
4005
4006   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4007   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4008     // Shifting in all undef bits?
4009     EVT SmallVT = N0.getOperand(0).getValueType();
4010     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4011       return DAG.getUNDEF(VT);
4012
4013     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4014       uint64_t ShiftAmt = N1C->getZExtValue();
4015       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4016                                        N0.getOperand(0),
4017                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4018       AddToWorkList(SmallShift.getNode());
4019       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4020       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4021                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4022                          DAG.getConstant(Mask, VT));
4023     }
4024   }
4025
4026   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4027   // bit, which is unmodified by sra.
4028   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4029     if (N0.getOpcode() == ISD::SRA)
4030       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4031   }
4032
4033   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4034   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4035       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4036     APInt KnownZero, KnownOne;
4037     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4038
4039     // If any of the input bits are KnownOne, then the input couldn't be all
4040     // zeros, thus the result of the srl will always be zero.
4041     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4042
4043     // If all of the bits input the to ctlz node are known to be zero, then
4044     // the result of the ctlz is "32" and the result of the shift is one.
4045     APInt UnknownBits = ~KnownZero;
4046     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4047
4048     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4049     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4050       // Okay, we know that only that the single bit specified by UnknownBits
4051       // could be set on input to the CTLZ node. If this bit is set, the SRL
4052       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4053       // to an SRL/XOR pair, which is likely to simplify more.
4054       unsigned ShAmt = UnknownBits.countTrailingZeros();
4055       SDValue Op = N0.getOperand(0);
4056
4057       if (ShAmt) {
4058         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4059                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4060         AddToWorkList(Op.getNode());
4061       }
4062
4063       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4064                          Op, DAG.getConstant(1, VT));
4065     }
4066   }
4067
4068   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4069   if (N1.getOpcode() == ISD::TRUNCATE &&
4070       N1.getOperand(0).getOpcode() == ISD::AND &&
4071       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4072     SDValue N101 = N1.getOperand(0).getOperand(1);
4073     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4074       EVT TruncVT = N1.getValueType();
4075       SDValue N100 = N1.getOperand(0).getOperand(0);
4076       APInt TruncC = N101C->getAPIntValue();
4077       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4078       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4079                          DAG.getNode(ISD::AND, SDLoc(N),
4080                                      TruncVT,
4081                                      DAG.getNode(ISD::TRUNCATE,
4082                                                  SDLoc(N),
4083                                                  TruncVT, N100),
4084                                      DAG.getConstant(TruncC, TruncVT)));
4085     }
4086   }
4087
4088   // fold operands of srl based on knowledge that the low bits are not
4089   // demanded.
4090   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4091     return SDValue(N, 0);
4092
4093   if (N1C) {
4094     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4095     if (NewSRL.getNode())
4096       return NewSRL;
4097   }
4098
4099   // Attempt to convert a srl of a load into a narrower zero-extending load.
4100   SDValue NarrowLoad = ReduceLoadWidth(N);
4101   if (NarrowLoad.getNode())
4102     return NarrowLoad;
4103
4104   // Here is a common situation. We want to optimize:
4105   //
4106   //   %a = ...
4107   //   %b = and i32 %a, 2
4108   //   %c = srl i32 %b, 1
4109   //   brcond i32 %c ...
4110   //
4111   // into
4112   //
4113   //   %a = ...
4114   //   %b = and %a, 2
4115   //   %c = setcc eq %b, 0
4116   //   brcond %c ...
4117   //
4118   // However when after the source operand of SRL is optimized into AND, the SRL
4119   // itself may not be optimized further. Look for it and add the BRCOND into
4120   // the worklist.
4121   if (N->hasOneUse()) {
4122     SDNode *Use = *N->use_begin();
4123     if (Use->getOpcode() == ISD::BRCOND)
4124       AddToWorkList(Use);
4125     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4126       // Also look pass the truncate.
4127       Use = *Use->use_begin();
4128       if (Use->getOpcode() == ISD::BRCOND)
4129         AddToWorkList(Use);
4130     }
4131   }
4132
4133   return SDValue();
4134 }
4135
4136 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4137   SDValue N0 = N->getOperand(0);
4138   EVT VT = N->getValueType(0);
4139
4140   // fold (ctlz c1) -> c2
4141   if (isa<ConstantSDNode>(N0))
4142     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4143   return SDValue();
4144 }
4145
4146 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4147   SDValue N0 = N->getOperand(0);
4148   EVT VT = N->getValueType(0);
4149
4150   // fold (ctlz_zero_undef c1) -> c2
4151   if (isa<ConstantSDNode>(N0))
4152     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4153   return SDValue();
4154 }
4155
4156 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4157   SDValue N0 = N->getOperand(0);
4158   EVT VT = N->getValueType(0);
4159
4160   // fold (cttz c1) -> c2
4161   if (isa<ConstantSDNode>(N0))
4162     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4163   return SDValue();
4164 }
4165
4166 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4167   SDValue N0 = N->getOperand(0);
4168   EVT VT = N->getValueType(0);
4169
4170   // fold (cttz_zero_undef c1) -> c2
4171   if (isa<ConstantSDNode>(N0))
4172     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4173   return SDValue();
4174 }
4175
4176 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4177   SDValue N0 = N->getOperand(0);
4178   EVT VT = N->getValueType(0);
4179
4180   // fold (ctpop c1) -> c2
4181   if (isa<ConstantSDNode>(N0))
4182     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4183   return SDValue();
4184 }
4185
4186 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4187   SDValue N0 = N->getOperand(0);
4188   SDValue N1 = N->getOperand(1);
4189   SDValue N2 = N->getOperand(2);
4190   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4191   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4192   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4193   EVT VT = N->getValueType(0);
4194   EVT VT0 = N0.getValueType();
4195
4196   // fold (select C, X, X) -> X
4197   if (N1 == N2)
4198     return N1;
4199   // fold (select true, X, Y) -> X
4200   if (N0C && !N0C->isNullValue())
4201     return N1;
4202   // fold (select false, X, Y) -> Y
4203   if (N0C && N0C->isNullValue())
4204     return N2;
4205   // fold (select C, 1, X) -> (or C, X)
4206   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4207     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4208   // fold (select C, 0, 1) -> (xor C, 1)
4209   if (VT.isInteger() &&
4210       (VT0 == MVT::i1 ||
4211        (VT0.isInteger() &&
4212         TLI.getBooleanContents(false) ==
4213         TargetLowering::ZeroOrOneBooleanContent)) &&
4214       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4215     SDValue XORNode;
4216     if (VT == VT0)
4217       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4218                          N0, DAG.getConstant(1, VT0));
4219     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4220                           N0, DAG.getConstant(1, VT0));
4221     AddToWorkList(XORNode.getNode());
4222     if (VT.bitsGT(VT0))
4223       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4224     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4225   }
4226   // fold (select C, 0, X) -> (and (not C), X)
4227   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4228     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4229     AddToWorkList(NOTNode.getNode());
4230     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4231   }
4232   // fold (select C, X, 1) -> (or (not C), X)
4233   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4234     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4235     AddToWorkList(NOTNode.getNode());
4236     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4237   }
4238   // fold (select C, X, 0) -> (and C, X)
4239   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4240     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4241   // fold (select X, X, Y) -> (or X, Y)
4242   // fold (select X, 1, Y) -> (or X, Y)
4243   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4244     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4245   // fold (select X, Y, X) -> (and X, Y)
4246   // fold (select X, Y, 0) -> (and X, Y)
4247   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4248     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4249
4250   // If we can fold this based on the true/false value, do so.
4251   if (SimplifySelectOps(N, N1, N2))
4252     return SDValue(N, 0);  // Don't revisit N.
4253
4254   // fold selects based on a setcc into other things, such as min/max/abs
4255   if (N0.getOpcode() == ISD::SETCC) {
4256     // FIXME:
4257     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4258     // having to say they don't support SELECT_CC on every type the DAG knows
4259     // about, since there is no way to mark an opcode illegal at all value types
4260     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4261         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4262       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4263                          N0.getOperand(0), N0.getOperand(1),
4264                          N1, N2, N0.getOperand(2));
4265     return SimplifySelect(SDLoc(N), N0, N1, N2);
4266   }
4267
4268   return SDValue();
4269 }
4270
4271 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4272   SDValue N0 = N->getOperand(0);
4273   SDValue N1 = N->getOperand(1);
4274   SDValue N2 = N->getOperand(2);
4275   SDLoc DL(N);
4276
4277   // Canonicalize integer abs.
4278   // vselect (setg[te] X,  0),  X, -X ->
4279   // vselect (setgt    X, -1),  X, -X ->
4280   // vselect (setl[te] X,  0), -X,  X ->
4281   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4282   if (N0.getOpcode() == ISD::SETCC) {
4283     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4284     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4285     bool isAbs = false;
4286     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4287
4288     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4289          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4290         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4291       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4292     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4293              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4294       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4295
4296     if (isAbs) {
4297       EVT VT = LHS.getValueType();
4298       SDValue Shift = DAG.getNode(
4299           ISD::SRA, DL, VT, LHS,
4300           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4301       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4302       AddToWorkList(Shift.getNode());
4303       AddToWorkList(Add.getNode());
4304       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4305     }
4306   }
4307
4308   return SDValue();
4309 }
4310
4311 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4312   SDValue N0 = N->getOperand(0);
4313   SDValue N1 = N->getOperand(1);
4314   SDValue N2 = N->getOperand(2);
4315   SDValue N3 = N->getOperand(3);
4316   SDValue N4 = N->getOperand(4);
4317   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4318
4319   // fold select_cc lhs, rhs, x, x, cc -> x
4320   if (N2 == N3)
4321     return N2;
4322
4323   // Determine if the condition we're dealing with is constant
4324   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4325                               N0, N1, CC, SDLoc(N), false);
4326   if (SCC.getNode()) {
4327     AddToWorkList(SCC.getNode());
4328
4329     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4330       if (!SCCC->isNullValue())
4331         return N2;    // cond always true -> true val
4332       else
4333         return N3;    // cond always false -> false val
4334     }
4335
4336     // Fold to a simpler select_cc
4337     if (SCC.getOpcode() == ISD::SETCC)
4338       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4339                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4340                          SCC.getOperand(2));
4341   }
4342
4343   // If we can fold this based on the true/false value, do so.
4344   if (SimplifySelectOps(N, N2, N3))
4345     return SDValue(N, 0);  // Don't revisit N.
4346
4347   // fold select_cc into other things, such as min/max/abs
4348   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4349 }
4350
4351 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4352   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4353                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4354                        SDLoc(N));
4355 }
4356
4357 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4358 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4359 // transformation. Returns true if extension are possible and the above
4360 // mentioned transformation is profitable.
4361 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4362                                     unsigned ExtOpc,
4363                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4364                                     const TargetLowering &TLI) {
4365   bool HasCopyToRegUses = false;
4366   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4367   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4368                             UE = N0.getNode()->use_end();
4369        UI != UE; ++UI) {
4370     SDNode *User = *UI;
4371     if (User == N)
4372       continue;
4373     if (UI.getUse().getResNo() != N0.getResNo())
4374       continue;
4375     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4376     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4377       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4378       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4379         // Sign bits will be lost after a zext.
4380         return false;
4381       bool Add = false;
4382       for (unsigned i = 0; i != 2; ++i) {
4383         SDValue UseOp = User->getOperand(i);
4384         if (UseOp == N0)
4385           continue;
4386         if (!isa<ConstantSDNode>(UseOp))
4387           return false;
4388         Add = true;
4389       }
4390       if (Add)
4391         ExtendNodes.push_back(User);
4392       continue;
4393     }
4394     // If truncates aren't free and there are users we can't
4395     // extend, it isn't worthwhile.
4396     if (!isTruncFree)
4397       return false;
4398     // Remember if this value is live-out.
4399     if (User->getOpcode() == ISD::CopyToReg)
4400       HasCopyToRegUses = true;
4401   }
4402
4403   if (HasCopyToRegUses) {
4404     bool BothLiveOut = false;
4405     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4406          UI != UE; ++UI) {
4407       SDUse &Use = UI.getUse();
4408       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4409         BothLiveOut = true;
4410         break;
4411       }
4412     }
4413     if (BothLiveOut)
4414       // Both unextended and extended values are live out. There had better be
4415       // a good reason for the transformation.
4416       return ExtendNodes.size();
4417   }
4418   return true;
4419 }
4420
4421 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4422                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4423                                   ISD::NodeType ExtType) {
4424   // Extend SetCC uses if necessary.
4425   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4426     SDNode *SetCC = SetCCs[i];
4427     SmallVector<SDValue, 4> Ops;
4428
4429     for (unsigned j = 0; j != 2; ++j) {
4430       SDValue SOp = SetCC->getOperand(j);
4431       if (SOp == Trunc)
4432         Ops.push_back(ExtLoad);
4433       else
4434         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4435     }
4436
4437     Ops.push_back(SetCC->getOperand(2));
4438     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4439                                  &Ops[0], Ops.size()));
4440   }
4441 }
4442
4443 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4444   SDValue N0 = N->getOperand(0);
4445   EVT VT = N->getValueType(0);
4446
4447   // fold (sext c1) -> c1
4448   if (isa<ConstantSDNode>(N0))
4449     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4450
4451   // fold (sext (sext x)) -> (sext x)
4452   // fold (sext (aext x)) -> (sext x)
4453   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4454     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4455                        N0.getOperand(0));
4456
4457   if (N0.getOpcode() == ISD::TRUNCATE) {
4458     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4459     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4460     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4461     if (NarrowLoad.getNode()) {
4462       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4463       if (NarrowLoad.getNode() != N0.getNode()) {
4464         CombineTo(N0.getNode(), NarrowLoad);
4465         // CombineTo deleted the truncate, if needed, but not what's under it.
4466         AddToWorkList(oye);
4467       }
4468       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4469     }
4470
4471     // See if the value being truncated is already sign extended.  If so, just
4472     // eliminate the trunc/sext pair.
4473     SDValue Op = N0.getOperand(0);
4474     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4475     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4476     unsigned DestBits = VT.getScalarType().getSizeInBits();
4477     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4478
4479     if (OpBits == DestBits) {
4480       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4481       // bits, it is already ready.
4482       if (NumSignBits > DestBits-MidBits)
4483         return Op;
4484     } else if (OpBits < DestBits) {
4485       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4486       // bits, just sext from i32.
4487       if (NumSignBits > OpBits-MidBits)
4488         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4489     } else {
4490       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4491       // bits, just truncate to i32.
4492       if (NumSignBits > OpBits-MidBits)
4493         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4494     }
4495
4496     // fold (sext (truncate x)) -> (sextinreg x).
4497     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4498                                                  N0.getValueType())) {
4499       if (OpBits < DestBits)
4500         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4501       else if (OpBits > DestBits)
4502         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4503       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4504                          DAG.getValueType(N0.getValueType()));
4505     }
4506   }
4507
4508   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4509   // None of the supported targets knows how to perform load and sign extend
4510   // on vectors in one instruction.  We only perform this transformation on
4511   // scalars.
4512   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4513       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4514        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4515     bool DoXform = true;
4516     SmallVector<SDNode*, 4> SetCCs;
4517     if (!N0.hasOneUse())
4518       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4519     if (DoXform) {
4520       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4521       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4522                                        LN0->getChain(),
4523                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4524                                        N0.getValueType(),
4525                                        LN0->isVolatile(), LN0->isNonTemporal(),
4526                                        LN0->getAlignment());
4527       CombineTo(N, ExtLoad);
4528       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4529                                   N0.getValueType(), ExtLoad);
4530       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4531       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4532                       ISD::SIGN_EXTEND);
4533       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4534     }
4535   }
4536
4537   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4538   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4539   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4540       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4541     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4542     EVT MemVT = LN0->getMemoryVT();
4543     if ((!LegalOperations && !LN0->isVolatile()) ||
4544         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4545       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4546                                        LN0->getChain(),
4547                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4548                                        MemVT,
4549                                        LN0->isVolatile(), LN0->isNonTemporal(),
4550                                        LN0->getAlignment());
4551       CombineTo(N, ExtLoad);
4552       CombineTo(N0.getNode(),
4553                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4554                             N0.getValueType(), ExtLoad),
4555                 ExtLoad.getValue(1));
4556       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4557     }
4558   }
4559
4560   // fold (sext (and/or/xor (load x), cst)) ->
4561   //      (and/or/xor (sextload x), (sext cst))
4562   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4563        N0.getOpcode() == ISD::XOR) &&
4564       isa<LoadSDNode>(N0.getOperand(0)) &&
4565       N0.getOperand(1).getOpcode() == ISD::Constant &&
4566       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4567       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4568     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4569     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4570       bool DoXform = true;
4571       SmallVector<SDNode*, 4> SetCCs;
4572       if (!N0.hasOneUse())
4573         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4574                                           SetCCs, TLI);
4575       if (DoXform) {
4576         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4577                                          LN0->getChain(), LN0->getBasePtr(),
4578                                          LN0->getPointerInfo(),
4579                                          LN0->getMemoryVT(),
4580                                          LN0->isVolatile(),
4581                                          LN0->isNonTemporal(),
4582                                          LN0->getAlignment());
4583         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4584         Mask = Mask.sext(VT.getSizeInBits());
4585         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4586                                   ExtLoad, DAG.getConstant(Mask, VT));
4587         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4588                                     SDLoc(N0.getOperand(0)),
4589                                     N0.getOperand(0).getValueType(), ExtLoad);
4590         CombineTo(N, And);
4591         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4592         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4593                         ISD::SIGN_EXTEND);
4594         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4595       }
4596     }
4597   }
4598
4599   if (N0.getOpcode() == ISD::SETCC) {
4600     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4601     // Only do this before legalize for now.
4602     if (VT.isVector() && !LegalOperations &&
4603         TLI.getBooleanContents(true) ==
4604           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4605       EVT N0VT = N0.getOperand(0).getValueType();
4606       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4607       // of the same size as the compared operands. Only optimize sext(setcc())
4608       // if this is the case.
4609       EVT SVT = getSetCCResultType(N0VT);
4610
4611       // We know that the # elements of the results is the same as the
4612       // # elements of the compare (and the # elements of the compare result
4613       // for that matter).  Check to see that they are the same size.  If so,
4614       // we know that the element size of the sext'd result matches the
4615       // element size of the compare operands.
4616       if (VT.getSizeInBits() == SVT.getSizeInBits())
4617         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4618                              N0.getOperand(1),
4619                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4620
4621       // If the desired elements are smaller or larger than the source
4622       // elements we can use a matching integer vector type and then
4623       // truncate/sign extend
4624       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4625       if (SVT == MatchingVectorType) {
4626         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4627                                N0.getOperand(0), N0.getOperand(1),
4628                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4629         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4630       }
4631     }
4632
4633     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4634     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4635     SDValue NegOne =
4636       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4637     SDValue SCC =
4638       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4639                        NegOne, DAG.getConstant(0, VT),
4640                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4641     if (SCC.getNode()) return SCC;
4642     if (!VT.isVector() &&
4643         (!LegalOperations ||
4644          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4645       return DAG.getSelect(SDLoc(N), VT,
4646                            DAG.getSetCC(SDLoc(N),
4647                                         getSetCCResultType(VT),
4648                                         N0.getOperand(0), N0.getOperand(1),
4649                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4650                            NegOne, DAG.getConstant(0, VT));
4651     }
4652   }
4653
4654   // fold (sext x) -> (zext x) if the sign bit is known zero.
4655   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4656       DAG.SignBitIsZero(N0))
4657     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4658
4659   return SDValue();
4660 }
4661
4662 // isTruncateOf - If N is a truncate of some other value, return true, record
4663 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4664 // This function computes KnownZero to avoid a duplicated call to
4665 // ComputeMaskedBits in the caller.
4666 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4667                          APInt &KnownZero) {
4668   APInt KnownOne;
4669   if (N->getOpcode() == ISD::TRUNCATE) {
4670     Op = N->getOperand(0);
4671     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4672     return true;
4673   }
4674
4675   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4676       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4677     return false;
4678
4679   SDValue Op0 = N->getOperand(0);
4680   SDValue Op1 = N->getOperand(1);
4681   assert(Op0.getValueType() == Op1.getValueType());
4682
4683   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4684   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4685   if (COp0 && COp0->isNullValue())
4686     Op = Op1;
4687   else if (COp1 && COp1->isNullValue())
4688     Op = Op0;
4689   else
4690     return false;
4691
4692   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4693
4694   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4695     return false;
4696
4697   return true;
4698 }
4699
4700 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4701   SDValue N0 = N->getOperand(0);
4702   EVT VT = N->getValueType(0);
4703
4704   // fold (zext c1) -> c1
4705   if (isa<ConstantSDNode>(N0))
4706     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4707   // fold (zext (zext x)) -> (zext x)
4708   // fold (zext (aext x)) -> (zext x)
4709   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4710     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4711                        N0.getOperand(0));
4712
4713   // fold (zext (truncate x)) -> (zext x) or
4714   //      (zext (truncate x)) -> (truncate x)
4715   // This is valid when the truncated bits of x are already zero.
4716   // FIXME: We should extend this to work for vectors too.
4717   SDValue Op;
4718   APInt KnownZero;
4719   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4720     APInt TruncatedBits =
4721       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4722       APInt(Op.getValueSizeInBits(), 0) :
4723       APInt::getBitsSet(Op.getValueSizeInBits(),
4724                         N0.getValueSizeInBits(),
4725                         std::min(Op.getValueSizeInBits(),
4726                                  VT.getSizeInBits()));
4727     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4728       if (VT.bitsGT(Op.getValueType()))
4729         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4730       if (VT.bitsLT(Op.getValueType()))
4731         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4732
4733       return Op;
4734     }
4735   }
4736
4737   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4738   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4739   if (N0.getOpcode() == ISD::TRUNCATE) {
4740     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4741     if (NarrowLoad.getNode()) {
4742       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4743       if (NarrowLoad.getNode() != N0.getNode()) {
4744         CombineTo(N0.getNode(), NarrowLoad);
4745         // CombineTo deleted the truncate, if needed, but not what's under it.
4746         AddToWorkList(oye);
4747       }
4748       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4749     }
4750   }
4751
4752   // fold (zext (truncate x)) -> (and x, mask)
4753   if (N0.getOpcode() == ISD::TRUNCATE &&
4754       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4755
4756     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4757     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4758     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4759     if (NarrowLoad.getNode()) {
4760       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4761       if (NarrowLoad.getNode() != N0.getNode()) {
4762         CombineTo(N0.getNode(), NarrowLoad);
4763         // CombineTo deleted the truncate, if needed, but not what's under it.
4764         AddToWorkList(oye);
4765       }
4766       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4767     }
4768
4769     SDValue Op = N0.getOperand(0);
4770     if (Op.getValueType().bitsLT(VT)) {
4771       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4772       AddToWorkList(Op.getNode());
4773     } else if (Op.getValueType().bitsGT(VT)) {
4774       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4775       AddToWorkList(Op.getNode());
4776     }
4777     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4778                                   N0.getValueType().getScalarType());
4779   }
4780
4781   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4782   // if either of the casts is not free.
4783   if (N0.getOpcode() == ISD::AND &&
4784       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4785       N0.getOperand(1).getOpcode() == ISD::Constant &&
4786       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4787                            N0.getValueType()) ||
4788        !TLI.isZExtFree(N0.getValueType(), VT))) {
4789     SDValue X = N0.getOperand(0).getOperand(0);
4790     if (X.getValueType().bitsLT(VT)) {
4791       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4792     } else if (X.getValueType().bitsGT(VT)) {
4793       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4794     }
4795     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4796     Mask = Mask.zext(VT.getSizeInBits());
4797     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4798                        X, DAG.getConstant(Mask, VT));
4799   }
4800
4801   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4802   // None of the supported targets knows how to perform load and vector_zext
4803   // on vectors in one instruction.  We only perform this transformation on
4804   // scalars.
4805   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4806       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4807        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4808     bool DoXform = true;
4809     SmallVector<SDNode*, 4> SetCCs;
4810     if (!N0.hasOneUse())
4811       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4812     if (DoXform) {
4813       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4814       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4815                                        LN0->getChain(),
4816                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4817                                        N0.getValueType(),
4818                                        LN0->isVolatile(), LN0->isNonTemporal(),
4819                                        LN0->getAlignment());
4820       CombineTo(N, ExtLoad);
4821       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4822                                   N0.getValueType(), ExtLoad);
4823       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4824
4825       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4826                       ISD::ZERO_EXTEND);
4827       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4828     }
4829   }
4830
4831   // fold (zext (and/or/xor (load x), cst)) ->
4832   //      (and/or/xor (zextload x), (zext cst))
4833   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4834        N0.getOpcode() == ISD::XOR) &&
4835       isa<LoadSDNode>(N0.getOperand(0)) &&
4836       N0.getOperand(1).getOpcode() == ISD::Constant &&
4837       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4838       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4839     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4840     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4841       bool DoXform = true;
4842       SmallVector<SDNode*, 4> SetCCs;
4843       if (!N0.hasOneUse())
4844         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4845                                           SetCCs, TLI);
4846       if (DoXform) {
4847         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4848                                          LN0->getChain(), LN0->getBasePtr(),
4849                                          LN0->getPointerInfo(),
4850                                          LN0->getMemoryVT(),
4851                                          LN0->isVolatile(),
4852                                          LN0->isNonTemporal(),
4853                                          LN0->getAlignment());
4854         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4855         Mask = Mask.zext(VT.getSizeInBits());
4856         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4857                                   ExtLoad, DAG.getConstant(Mask, VT));
4858         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4859                                     SDLoc(N0.getOperand(0)),
4860                                     N0.getOperand(0).getValueType(), ExtLoad);
4861         CombineTo(N, And);
4862         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4863         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4864                         ISD::ZERO_EXTEND);
4865         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4866       }
4867     }
4868   }
4869
4870   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4871   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4872   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4873       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4874     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4875     EVT MemVT = LN0->getMemoryVT();
4876     if ((!LegalOperations && !LN0->isVolatile()) ||
4877         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4878       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4879                                        LN0->getChain(),
4880                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4881                                        MemVT,
4882                                        LN0->isVolatile(), LN0->isNonTemporal(),
4883                                        LN0->getAlignment());
4884       CombineTo(N, ExtLoad);
4885       CombineTo(N0.getNode(),
4886                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4887                             ExtLoad),
4888                 ExtLoad.getValue(1));
4889       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4890     }
4891   }
4892
4893   if (N0.getOpcode() == ISD::SETCC) {
4894     if (!LegalOperations && VT.isVector()) {
4895       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4896       // Only do this before legalize for now.
4897       EVT N0VT = N0.getOperand(0).getValueType();
4898       EVT EltVT = VT.getVectorElementType();
4899       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4900                                     DAG.getConstant(1, EltVT));
4901       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4902         // We know that the # elements of the results is the same as the
4903         // # elements of the compare (and the # elements of the compare result
4904         // for that matter).  Check to see that they are the same size.  If so,
4905         // we know that the element size of the sext'd result matches the
4906         // element size of the compare operands.
4907         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4908                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4909                                          N0.getOperand(1),
4910                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4911                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4912                                        &OneOps[0], OneOps.size()));
4913
4914       // If the desired elements are smaller or larger than the source
4915       // elements we can use a matching integer vector type and then
4916       // truncate/sign extend
4917       EVT MatchingElementType =
4918         EVT::getIntegerVT(*DAG.getContext(),
4919                           N0VT.getScalarType().getSizeInBits());
4920       EVT MatchingVectorType =
4921         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4922                          N0VT.getVectorNumElements());
4923       SDValue VsetCC =
4924         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4925                       N0.getOperand(1),
4926                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4927       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4928                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4929                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4930                                      &OneOps[0], OneOps.size()));
4931     }
4932
4933     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4934     SDValue SCC =
4935       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4936                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4937                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4938     if (SCC.getNode()) return SCC;
4939   }
4940
4941   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4942   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4943       isa<ConstantSDNode>(N0.getOperand(1)) &&
4944       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4945       N0.hasOneUse()) {
4946     SDValue ShAmt = N0.getOperand(1);
4947     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4948     if (N0.getOpcode() == ISD::SHL) {
4949       SDValue InnerZExt = N0.getOperand(0);
4950       // If the original shl may be shifting out bits, do not perform this
4951       // transformation.
4952       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4953         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4954       if (ShAmtVal > KnownZeroBits)
4955         return SDValue();
4956     }
4957
4958     SDLoc DL(N);
4959
4960     // Ensure that the shift amount is wide enough for the shifted value.
4961     if (VT.getSizeInBits() >= 256)
4962       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4963
4964     return DAG.getNode(N0.getOpcode(), DL, VT,
4965                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4966                        ShAmt);
4967   }
4968
4969   return SDValue();
4970 }
4971
4972 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4973   SDValue N0 = N->getOperand(0);
4974   EVT VT = N->getValueType(0);
4975
4976   // fold (aext c1) -> c1
4977   if (isa<ConstantSDNode>(N0))
4978     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4979   // fold (aext (aext x)) -> (aext x)
4980   // fold (aext (zext x)) -> (zext x)
4981   // fold (aext (sext x)) -> (sext x)
4982   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4983       N0.getOpcode() == ISD::ZERO_EXTEND ||
4984       N0.getOpcode() == ISD::SIGN_EXTEND)
4985     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4986
4987   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4988   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4989   if (N0.getOpcode() == ISD::TRUNCATE) {
4990     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4991     if (NarrowLoad.getNode()) {
4992       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4993       if (NarrowLoad.getNode() != N0.getNode()) {
4994         CombineTo(N0.getNode(), NarrowLoad);
4995         // CombineTo deleted the truncate, if needed, but not what's under it.
4996         AddToWorkList(oye);
4997       }
4998       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4999     }
5000   }
5001
5002   // fold (aext (truncate x))
5003   if (N0.getOpcode() == ISD::TRUNCATE) {
5004     SDValue TruncOp = N0.getOperand(0);
5005     if (TruncOp.getValueType() == VT)
5006       return TruncOp; // x iff x size == zext size.
5007     if (TruncOp.getValueType().bitsGT(VT))
5008       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5009     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5010   }
5011
5012   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5013   // if the trunc is not free.
5014   if (N0.getOpcode() == ISD::AND &&
5015       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5016       N0.getOperand(1).getOpcode() == ISD::Constant &&
5017       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5018                           N0.getValueType())) {
5019     SDValue X = N0.getOperand(0).getOperand(0);
5020     if (X.getValueType().bitsLT(VT)) {
5021       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5022     } else if (X.getValueType().bitsGT(VT)) {
5023       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5024     }
5025     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5026     Mask = Mask.zext(VT.getSizeInBits());
5027     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5028                        X, DAG.getConstant(Mask, VT));
5029   }
5030
5031   // fold (aext (load x)) -> (aext (truncate (extload x)))
5032   // None of the supported targets knows how to perform load and any_ext
5033   // on vectors in one instruction.  We only perform this transformation on
5034   // scalars.
5035   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5036       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5037        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5038     bool DoXform = true;
5039     SmallVector<SDNode*, 4> SetCCs;
5040     if (!N0.hasOneUse())
5041       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5042     if (DoXform) {
5043       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5044       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5045                                        LN0->getChain(),
5046                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5047                                        N0.getValueType(),
5048                                        LN0->isVolatile(), LN0->isNonTemporal(),
5049                                        LN0->getAlignment());
5050       CombineTo(N, ExtLoad);
5051       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5052                                   N0.getValueType(), ExtLoad);
5053       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5054       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5055                       ISD::ANY_EXTEND);
5056       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5057     }
5058   }
5059
5060   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5061   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5062   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5063   if (N0.getOpcode() == ISD::LOAD &&
5064       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5065       N0.hasOneUse()) {
5066     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5067     EVT MemVT = LN0->getMemoryVT();
5068     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5069                                      VT, LN0->getChain(), LN0->getBasePtr(),
5070                                      LN0->getPointerInfo(), MemVT,
5071                                      LN0->isVolatile(), LN0->isNonTemporal(),
5072                                      LN0->getAlignment());
5073     CombineTo(N, ExtLoad);
5074     CombineTo(N0.getNode(),
5075               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5076                           N0.getValueType(), ExtLoad),
5077               ExtLoad.getValue(1));
5078     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5079   }
5080
5081   if (N0.getOpcode() == ISD::SETCC) {
5082     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5083     // Only do this before legalize for now.
5084     if (VT.isVector() && !LegalOperations) {
5085       EVT N0VT = N0.getOperand(0).getValueType();
5086         // We know that the # elements of the results is the same as the
5087         // # elements of the compare (and the # elements of the compare result
5088         // for that matter).  Check to see that they are the same size.  If so,
5089         // we know that the element size of the sext'd result matches the
5090         // element size of the compare operands.
5091       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5092         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5093                              N0.getOperand(1),
5094                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5095       // If the desired elements are smaller or larger than the source
5096       // elements we can use a matching integer vector type and then
5097       // truncate/sign extend
5098       else {
5099         EVT MatchingElementType =
5100           EVT::getIntegerVT(*DAG.getContext(),
5101                             N0VT.getScalarType().getSizeInBits());
5102         EVT MatchingVectorType =
5103           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5104                            N0VT.getVectorNumElements());
5105         SDValue VsetCC =
5106           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5107                         N0.getOperand(1),
5108                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5109         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5110       }
5111     }
5112
5113     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5114     SDValue SCC =
5115       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5116                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5117                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5118     if (SCC.getNode())
5119       return SCC;
5120   }
5121
5122   return SDValue();
5123 }
5124
5125 /// GetDemandedBits - See if the specified operand can be simplified with the
5126 /// knowledge that only the bits specified by Mask are used.  If so, return the
5127 /// simpler operand, otherwise return a null SDValue.
5128 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5129   switch (V.getOpcode()) {
5130   default: break;
5131   case ISD::Constant: {
5132     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5133     assert(CV != 0 && "Const value should be ConstSDNode.");
5134     const APInt &CVal = CV->getAPIntValue();
5135     APInt NewVal = CVal & Mask;
5136     if (NewVal != CVal)
5137       return DAG.getConstant(NewVal, V.getValueType());
5138     break;
5139   }
5140   case ISD::OR:
5141   case ISD::XOR:
5142     // If the LHS or RHS don't contribute bits to the or, drop them.
5143     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5144       return V.getOperand(1);
5145     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5146       return V.getOperand(0);
5147     break;
5148   case ISD::SRL:
5149     // Only look at single-use SRLs.
5150     if (!V.getNode()->hasOneUse())
5151       break;
5152     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5153       // See if we can recursively simplify the LHS.
5154       unsigned Amt = RHSC->getZExtValue();
5155
5156       // Watch out for shift count overflow though.
5157       if (Amt >= Mask.getBitWidth()) break;
5158       APInt NewMask = Mask << Amt;
5159       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5160       if (SimplifyLHS.getNode())
5161         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5162                            SimplifyLHS, V.getOperand(1));
5163     }
5164   }
5165   return SDValue();
5166 }
5167
5168 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5169 /// bits and then truncated to a narrower type and where N is a multiple
5170 /// of number of bits of the narrower type, transform it to a narrower load
5171 /// from address + N / num of bits of new type. If the result is to be
5172 /// extended, also fold the extension to form a extending load.
5173 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5174   unsigned Opc = N->getOpcode();
5175
5176   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5177   SDValue N0 = N->getOperand(0);
5178   EVT VT = N->getValueType(0);
5179   EVT ExtVT = VT;
5180
5181   // This transformation isn't valid for vector loads.
5182   if (VT.isVector())
5183     return SDValue();
5184
5185   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5186   // extended to VT.
5187   if (Opc == ISD::SIGN_EXTEND_INREG) {
5188     ExtType = ISD::SEXTLOAD;
5189     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5190   } else if (Opc == ISD::SRL) {
5191     // Another special-case: SRL is basically zero-extending a narrower value.
5192     ExtType = ISD::ZEXTLOAD;
5193     N0 = SDValue(N, 0);
5194     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5195     if (!N01) return SDValue();
5196     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5197                               VT.getSizeInBits() - N01->getZExtValue());
5198   }
5199   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5200     return SDValue();
5201
5202   unsigned EVTBits = ExtVT.getSizeInBits();
5203
5204   // Do not generate loads of non-round integer types since these can
5205   // be expensive (and would be wrong if the type is not byte sized).
5206   if (!ExtVT.isRound())
5207     return SDValue();
5208
5209   unsigned ShAmt = 0;
5210   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5211     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5212       ShAmt = N01->getZExtValue();
5213       // Is the shift amount a multiple of size of VT?
5214       if ((ShAmt & (EVTBits-1)) == 0) {
5215         N0 = N0.getOperand(0);
5216         // Is the load width a multiple of size of VT?
5217         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5218           return SDValue();
5219       }
5220
5221       // At this point, we must have a load or else we can't do the transform.
5222       if (!isa<LoadSDNode>(N0)) return SDValue();
5223
5224       // Because a SRL must be assumed to *need* to zero-extend the high bits
5225       // (as opposed to anyext the high bits), we can't combine the zextload
5226       // lowering of SRL and an sextload.
5227       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5228         return SDValue();
5229
5230       // If the shift amount is larger than the input type then we're not
5231       // accessing any of the loaded bytes.  If the load was a zextload/extload
5232       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5233       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5234         return SDValue();
5235     }
5236   }
5237
5238   // If the load is shifted left (and the result isn't shifted back right),
5239   // we can fold the truncate through the shift.
5240   unsigned ShLeftAmt = 0;
5241   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5242       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5243     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5244       ShLeftAmt = N01->getZExtValue();
5245       N0 = N0.getOperand(0);
5246     }
5247   }
5248
5249   // If we haven't found a load, we can't narrow it.  Don't transform one with
5250   // multiple uses, this would require adding a new load.
5251   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5252     return SDValue();
5253
5254   // Don't change the width of a volatile load.
5255   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5256   if (LN0->isVolatile())
5257     return SDValue();
5258
5259   // Verify that we are actually reducing a load width here.
5260   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5261     return SDValue();
5262
5263   // For the transform to be legal, the load must produce only two values
5264   // (the value loaded and the chain).  Don't transform a pre-increment
5265   // load, for example, which produces an extra value.  Otherwise the
5266   // transformation is not equivalent, and the downstream logic to replace
5267   // uses gets things wrong.
5268   if (LN0->getNumValues() > 2)
5269     return SDValue();
5270
5271   // If the load that we're shrinking is an extload and we're not just
5272   // discarding the extension we can't simply shrink the load. Bail.
5273   // TODO: It would be possible to merge the extensions in some cases.
5274   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5275       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5276     return SDValue();
5277
5278   EVT PtrType = N0.getOperand(1).getValueType();
5279
5280   if (PtrType == MVT::Untyped || PtrType.isExtended())
5281     // It's not possible to generate a constant of extended or untyped type.
5282     return SDValue();
5283
5284   // For big endian targets, we need to adjust the offset to the pointer to
5285   // load the correct bytes.
5286   if (TLI.isBigEndian()) {
5287     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5288     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5289     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5290   }
5291
5292   uint64_t PtrOff = ShAmt / 8;
5293   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5294   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5295                                PtrType, LN0->getBasePtr(),
5296                                DAG.getConstant(PtrOff, PtrType));
5297   AddToWorkList(NewPtr.getNode());
5298
5299   SDValue Load;
5300   if (ExtType == ISD::NON_EXTLOAD)
5301     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5302                         LN0->getPointerInfo().getWithOffset(PtrOff),
5303                         LN0->isVolatile(), LN0->isNonTemporal(),
5304                         LN0->isInvariant(), NewAlign);
5305   else
5306     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5307                           LN0->getPointerInfo().getWithOffset(PtrOff),
5308                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5309                           NewAlign);
5310
5311   // Replace the old load's chain with the new load's chain.
5312   WorkListRemover DeadNodes(*this);
5313   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5314
5315   // Shift the result left, if we've swallowed a left shift.
5316   SDValue Result = Load;
5317   if (ShLeftAmt != 0) {
5318     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5319     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5320       ShImmTy = VT;
5321     // If the shift amount is as large as the result size (but, presumably,
5322     // no larger than the source) then the useful bits of the result are
5323     // zero; we can't simply return the shortened shift, because the result
5324     // of that operation is undefined.
5325     if (ShLeftAmt >= VT.getSizeInBits())
5326       Result = DAG.getConstant(0, VT);
5327     else
5328       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5329                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5330   }
5331
5332   // Return the new loaded value.
5333   return Result;
5334 }
5335
5336 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5337   SDValue N0 = N->getOperand(0);
5338   SDValue N1 = N->getOperand(1);
5339   EVT VT = N->getValueType(0);
5340   EVT EVT = cast<VTSDNode>(N1)->getVT();
5341   unsigned VTBits = VT.getScalarType().getSizeInBits();
5342   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5343
5344   // fold (sext_in_reg c1) -> c1
5345   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5346     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5347
5348   // If the input is already sign extended, just drop the extension.
5349   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5350     return N0;
5351
5352   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5353   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5354       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5355     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5356                        N0.getOperand(0), N1);
5357
5358   // fold (sext_in_reg (sext x)) -> (sext x)
5359   // fold (sext_in_reg (aext x)) -> (sext x)
5360   // if x is small enough.
5361   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5362     SDValue N00 = N0.getOperand(0);
5363     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5364         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5365       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5366   }
5367
5368   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5369   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5370     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5371
5372   // fold operands of sext_in_reg based on knowledge that the top bits are not
5373   // demanded.
5374   if (SimplifyDemandedBits(SDValue(N, 0)))
5375     return SDValue(N, 0);
5376
5377   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5378   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5379   SDValue NarrowLoad = ReduceLoadWidth(N);
5380   if (NarrowLoad.getNode())
5381     return NarrowLoad;
5382
5383   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5384   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5385   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5386   if (N0.getOpcode() == ISD::SRL) {
5387     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5388       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5389         // We can turn this into an SRA iff the input to the SRL is already sign
5390         // extended enough.
5391         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5392         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5393           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5394                              N0.getOperand(0), N0.getOperand(1));
5395       }
5396   }
5397
5398   // fold (sext_inreg (extload x)) -> (sextload x)
5399   if (ISD::isEXTLoad(N0.getNode()) &&
5400       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5401       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5402       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5403        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5404     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5405     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5406                                      LN0->getChain(),
5407                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5408                                      EVT,
5409                                      LN0->isVolatile(), LN0->isNonTemporal(),
5410                                      LN0->getAlignment());
5411     CombineTo(N, ExtLoad);
5412     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5413     AddToWorkList(ExtLoad.getNode());
5414     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5415   }
5416   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5417   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5418       N0.hasOneUse() &&
5419       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5420       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5421        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5422     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5423     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5424                                      LN0->getChain(),
5425                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5426                                      EVT,
5427                                      LN0->isVolatile(), LN0->isNonTemporal(),
5428                                      LN0->getAlignment());
5429     CombineTo(N, ExtLoad);
5430     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5431     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5432   }
5433
5434   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5435   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5436     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5437                                        N0.getOperand(1), false);
5438     if (BSwap.getNode() != 0)
5439       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5440                          BSwap, N1);
5441   }
5442
5443   return SDValue();
5444 }
5445
5446 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5447   SDValue N0 = N->getOperand(0);
5448   EVT VT = N->getValueType(0);
5449   bool isLE = TLI.isLittleEndian();
5450
5451   // noop truncate
5452   if (N0.getValueType() == N->getValueType(0))
5453     return N0;
5454   // fold (truncate c1) -> c1
5455   if (isa<ConstantSDNode>(N0))
5456     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5457   // fold (truncate (truncate x)) -> (truncate x)
5458   if (N0.getOpcode() == ISD::TRUNCATE)
5459     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5460   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5461   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5462       N0.getOpcode() == ISD::SIGN_EXTEND ||
5463       N0.getOpcode() == ISD::ANY_EXTEND) {
5464     if (N0.getOperand(0).getValueType().bitsLT(VT))
5465       // if the source is smaller than the dest, we still need an extend
5466       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5467                          N0.getOperand(0));
5468     if (N0.getOperand(0).getValueType().bitsGT(VT))
5469       // if the source is larger than the dest, than we just need the truncate
5470       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5471     // if the source and dest are the same type, we can drop both the extend
5472     // and the truncate.
5473     return N0.getOperand(0);
5474   }
5475
5476   // Fold extract-and-trunc into a narrow extract. For example:
5477   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5478   //   i32 y = TRUNCATE(i64 x)
5479   //        -- becomes --
5480   //   v16i8 b = BITCAST (v2i64 val)
5481   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5482   //
5483   // Note: We only run this optimization after type legalization (which often
5484   // creates this pattern) and before operation legalization after which
5485   // we need to be more careful about the vector instructions that we generate.
5486   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5487       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5488
5489     EVT VecTy = N0.getOperand(0).getValueType();
5490     EVT ExTy = N0.getValueType();
5491     EVT TrTy = N->getValueType(0);
5492
5493     unsigned NumElem = VecTy.getVectorNumElements();
5494     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5495
5496     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5497     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5498
5499     SDValue EltNo = N0->getOperand(1);
5500     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5501       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5502       EVT IndexTy = TLI.getVectorIdxTy();
5503       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5504
5505       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5506                               NVT, N0.getOperand(0));
5507
5508       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5509                          SDLoc(N), TrTy, V,
5510                          DAG.getConstant(Index, IndexTy));
5511     }
5512   }
5513
5514   // Fold a series of buildvector, bitcast, and truncate if possible.
5515   // For example fold
5516   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5517   //   (2xi32 (buildvector x, y)).
5518   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5519       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5520       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5521       N0.getOperand(0).hasOneUse()) {
5522
5523     SDValue BuildVect = N0.getOperand(0);
5524     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5525     EVT TruncVecEltTy = VT.getVectorElementType();
5526
5527     // Check that the element types match.
5528     if (BuildVectEltTy == TruncVecEltTy) {
5529       // Now we only need to compute the offset of the truncated elements.
5530       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5531       unsigned TruncVecNumElts = VT.getVectorNumElements();
5532       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5533
5534       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5535              "Invalid number of elements");
5536
5537       SmallVector<SDValue, 8> Opnds;
5538       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5539         Opnds.push_back(BuildVect.getOperand(i));
5540
5541       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5542                          Opnds.size());
5543     }
5544   }
5545
5546   // See if we can simplify the input to this truncate through knowledge that
5547   // only the low bits are being used.
5548   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5549   // Currently we only perform this optimization on scalars because vectors
5550   // may have different active low bits.
5551   if (!VT.isVector()) {
5552     SDValue Shorter =
5553       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5554                                                VT.getSizeInBits()));
5555     if (Shorter.getNode())
5556       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5557   }
5558   // fold (truncate (load x)) -> (smaller load x)
5559   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5560   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5561     SDValue Reduced = ReduceLoadWidth(N);
5562     if (Reduced.getNode())
5563       return Reduced;
5564   }
5565   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5566   // where ... are all 'undef'.
5567   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5568     SmallVector<EVT, 8> VTs;
5569     SDValue V;
5570     unsigned Idx = 0;
5571     unsigned NumDefs = 0;
5572
5573     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5574       SDValue X = N0.getOperand(i);
5575       if (X.getOpcode() != ISD::UNDEF) {
5576         V = X;
5577         Idx = i;
5578         NumDefs++;
5579       }
5580       // Stop if more than one members are non-undef.
5581       if (NumDefs > 1)
5582         break;
5583       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5584                                      VT.getVectorElementType(),
5585                                      X.getValueType().getVectorNumElements()));
5586     }
5587
5588     if (NumDefs == 0)
5589       return DAG.getUNDEF(VT);
5590
5591     if (NumDefs == 1) {
5592       assert(V.getNode() && "The single defined operand is empty!");
5593       SmallVector<SDValue, 8> Opnds;
5594       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5595         if (i != Idx) {
5596           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5597           continue;
5598         }
5599         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5600         AddToWorkList(NV.getNode());
5601         Opnds.push_back(NV);
5602       }
5603       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5604                          &Opnds[0], Opnds.size());
5605     }
5606   }
5607
5608   // Simplify the operands using demanded-bits information.
5609   if (!VT.isVector() &&
5610       SimplifyDemandedBits(SDValue(N, 0)))
5611     return SDValue(N, 0);
5612
5613   return SDValue();
5614 }
5615
5616 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5617   SDValue Elt = N->getOperand(i);
5618   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5619     return Elt.getNode();
5620   return Elt.getOperand(Elt.getResNo()).getNode();
5621 }
5622
5623 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5624 /// if load locations are consecutive.
5625 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5626   assert(N->getOpcode() == ISD::BUILD_PAIR);
5627
5628   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5629   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5630   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5631       LD1->getPointerInfo().getAddrSpace() !=
5632          LD2->getPointerInfo().getAddrSpace())
5633     return SDValue();
5634   EVT LD1VT = LD1->getValueType(0);
5635
5636   if (ISD::isNON_EXTLoad(LD2) &&
5637       LD2->hasOneUse() &&
5638       // If both are volatile this would reduce the number of volatile loads.
5639       // If one is volatile it might be ok, but play conservative and bail out.
5640       !LD1->isVolatile() &&
5641       !LD2->isVolatile() &&
5642       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5643     unsigned Align = LD1->getAlignment();
5644     unsigned NewAlign = TLI.getDataLayout()->
5645       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5646
5647     if (NewAlign <= Align &&
5648         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5649       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5650                          LD1->getBasePtr(), LD1->getPointerInfo(),
5651                          false, false, false, Align);
5652   }
5653
5654   return SDValue();
5655 }
5656
5657 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5658   SDValue N0 = N->getOperand(0);
5659   EVT VT = N->getValueType(0);
5660
5661   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5662   // Only do this before legalize, since afterward the target may be depending
5663   // on the bitconvert.
5664   // First check to see if this is all constant.
5665   if (!LegalTypes &&
5666       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5667       VT.isVector()) {
5668     bool isSimple = true;
5669     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5670       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5671           N0.getOperand(i).getOpcode() != ISD::Constant &&
5672           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5673         isSimple = false;
5674         break;
5675       }
5676
5677     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5678     assert(!DestEltVT.isVector() &&
5679            "Element type of vector ValueType must not be vector!");
5680     if (isSimple)
5681       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5682   }
5683
5684   // If the input is a constant, let getNode fold it.
5685   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5686     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5687     if (Res.getNode() != N) {
5688       if (!LegalOperations ||
5689           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5690         return Res;
5691
5692       // Folding it resulted in an illegal node, and it's too late to
5693       // do that. Clean up the old node and forego the transformation.
5694       // Ideally this won't happen very often, because instcombine
5695       // and the earlier dagcombine runs (where illegal nodes are
5696       // permitted) should have folded most of them already.
5697       DAG.DeleteNode(Res.getNode());
5698     }
5699   }
5700
5701   // (conv (conv x, t1), t2) -> (conv x, t2)
5702   if (N0.getOpcode() == ISD::BITCAST)
5703     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5704                        N0.getOperand(0));
5705
5706   // fold (conv (load x)) -> (load (conv*)x)
5707   // If the resultant load doesn't need a higher alignment than the original!
5708   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5709       // Do not change the width of a volatile load.
5710       !cast<LoadSDNode>(N0)->isVolatile() &&
5711       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5712     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5713     unsigned Align = TLI.getDataLayout()->
5714       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5715     unsigned OrigAlign = LN0->getAlignment();
5716
5717     if (Align <= OrigAlign) {
5718       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5719                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5720                                  LN0->isVolatile(), LN0->isNonTemporal(),
5721                                  LN0->isInvariant(), OrigAlign);
5722       AddToWorkList(N);
5723       CombineTo(N0.getNode(),
5724                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5725                             N0.getValueType(), Load),
5726                 Load.getValue(1));
5727       return Load;
5728     }
5729   }
5730
5731   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5732   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5733   // This often reduces constant pool loads.
5734   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5735        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5736       N0.getNode()->hasOneUse() && VT.isInteger() &&
5737       !VT.isVector() && !N0.getValueType().isVector()) {
5738     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5739                                   N0.getOperand(0));
5740     AddToWorkList(NewConv.getNode());
5741
5742     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5743     if (N0.getOpcode() == ISD::FNEG)
5744       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5745                          NewConv, DAG.getConstant(SignBit, VT));
5746     assert(N0.getOpcode() == ISD::FABS);
5747     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5748                        NewConv, DAG.getConstant(~SignBit, VT));
5749   }
5750
5751   // fold (bitconvert (fcopysign cst, x)) ->
5752   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5753   // Note that we don't handle (copysign x, cst) because this can always be
5754   // folded to an fneg or fabs.
5755   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5756       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5757       VT.isInteger() && !VT.isVector()) {
5758     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5759     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5760     if (isTypeLegal(IntXVT)) {
5761       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5762                               IntXVT, N0.getOperand(1));
5763       AddToWorkList(X.getNode());
5764
5765       // If X has a different width than the result/lhs, sext it or truncate it.
5766       unsigned VTWidth = VT.getSizeInBits();
5767       if (OrigXWidth < VTWidth) {
5768         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5769         AddToWorkList(X.getNode());
5770       } else if (OrigXWidth > VTWidth) {
5771         // To get the sign bit in the right place, we have to shift it right
5772         // before truncating.
5773         X = DAG.getNode(ISD::SRL, SDLoc(X),
5774                         X.getValueType(), X,
5775                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5776         AddToWorkList(X.getNode());
5777         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5778         AddToWorkList(X.getNode());
5779       }
5780
5781       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5782       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5783                       X, DAG.getConstant(SignBit, VT));
5784       AddToWorkList(X.getNode());
5785
5786       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5787                                 VT, N0.getOperand(0));
5788       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5789                         Cst, DAG.getConstant(~SignBit, VT));
5790       AddToWorkList(Cst.getNode());
5791
5792       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5793     }
5794   }
5795
5796   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5797   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5798     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5799     if (CombineLD.getNode())
5800       return CombineLD;
5801   }
5802
5803   return SDValue();
5804 }
5805
5806 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5807   EVT VT = N->getValueType(0);
5808   return CombineConsecutiveLoads(N, VT);
5809 }
5810
5811 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5812 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5813 /// destination element value type.
5814 SDValue DAGCombiner::
5815 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5816   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5817
5818   // If this is already the right type, we're done.
5819   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5820
5821   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5822   unsigned DstBitSize = DstEltVT.getSizeInBits();
5823
5824   // If this is a conversion of N elements of one type to N elements of another
5825   // type, convert each element.  This handles FP<->INT cases.
5826   if (SrcBitSize == DstBitSize) {
5827     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5828                               BV->getValueType(0).getVectorNumElements());
5829
5830     // Due to the FP element handling below calling this routine recursively,
5831     // we can end up with a scalar-to-vector node here.
5832     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5833       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5834                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5835                                      DstEltVT, BV->getOperand(0)));
5836
5837     SmallVector<SDValue, 8> Ops;
5838     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5839       SDValue Op = BV->getOperand(i);
5840       // If the vector element type is not legal, the BUILD_VECTOR operands
5841       // are promoted and implicitly truncated.  Make that explicit here.
5842       if (Op.getValueType() != SrcEltVT)
5843         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5844       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5845                                 DstEltVT, Op));
5846       AddToWorkList(Ops.back().getNode());
5847     }
5848     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5849                        &Ops[0], Ops.size());
5850   }
5851
5852   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5853   // handle annoying details of growing/shrinking FP values, we convert them to
5854   // int first.
5855   if (SrcEltVT.isFloatingPoint()) {
5856     // Convert the input float vector to a int vector where the elements are the
5857     // same sizes.
5858     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5859     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5860     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5861     SrcEltVT = IntVT;
5862   }
5863
5864   // Now we know the input is an integer vector.  If the output is a FP type,
5865   // convert to integer first, then to FP of the right size.
5866   if (DstEltVT.isFloatingPoint()) {
5867     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5868     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5869     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5870
5871     // Next, convert to FP elements of the same size.
5872     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5873   }
5874
5875   // Okay, we know the src/dst types are both integers of differing types.
5876   // Handling growing first.
5877   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5878   if (SrcBitSize < DstBitSize) {
5879     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5880
5881     SmallVector<SDValue, 8> Ops;
5882     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5883          i += NumInputsPerOutput) {
5884       bool isLE = TLI.isLittleEndian();
5885       APInt NewBits = APInt(DstBitSize, 0);
5886       bool EltIsUndef = true;
5887       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5888         // Shift the previously computed bits over.
5889         NewBits <<= SrcBitSize;
5890         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5891         if (Op.getOpcode() == ISD::UNDEF) continue;
5892         EltIsUndef = false;
5893
5894         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5895                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5896       }
5897
5898       if (EltIsUndef)
5899         Ops.push_back(DAG.getUNDEF(DstEltVT));
5900       else
5901         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5902     }
5903
5904     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5905     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5906                        &Ops[0], Ops.size());
5907   }
5908
5909   // Finally, this must be the case where we are shrinking elements: each input
5910   // turns into multiple outputs.
5911   bool isS2V = ISD::isScalarToVector(BV);
5912   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5913   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5914                             NumOutputsPerInput*BV->getNumOperands());
5915   SmallVector<SDValue, 8> Ops;
5916
5917   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5918     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5919       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5920         Ops.push_back(DAG.getUNDEF(DstEltVT));
5921       continue;
5922     }
5923
5924     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5925                   getAPIntValue().zextOrTrunc(SrcBitSize);
5926
5927     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5928       APInt ThisVal = OpVal.trunc(DstBitSize);
5929       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5930       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5931         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5932         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5933                            Ops[0]);
5934       OpVal = OpVal.lshr(DstBitSize);
5935     }
5936
5937     // For big endian targets, swap the order of the pieces of each element.
5938     if (TLI.isBigEndian())
5939       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5940   }
5941
5942   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5943                      &Ops[0], Ops.size());
5944 }
5945
5946 SDValue DAGCombiner::visitFADD(SDNode *N) {
5947   SDValue N0 = N->getOperand(0);
5948   SDValue N1 = N->getOperand(1);
5949   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5950   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5951   EVT VT = N->getValueType(0);
5952
5953   // fold vector ops
5954   if (VT.isVector()) {
5955     SDValue FoldedVOp = SimplifyVBinOp(N);
5956     if (FoldedVOp.getNode()) return FoldedVOp;
5957   }
5958
5959   // fold (fadd c1, c2) -> c1 + c2
5960   if (N0CFP && N1CFP)
5961     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5962   // canonicalize constant to RHS
5963   if (N0CFP && !N1CFP)
5964     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5965   // fold (fadd A, 0) -> A
5966   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5967       N1CFP->getValueAPF().isZero())
5968     return N0;
5969   // fold (fadd A, (fneg B)) -> (fsub A, B)
5970   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5971     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5972     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5973                        GetNegatedExpression(N1, DAG, LegalOperations));
5974   // fold (fadd (fneg A), B) -> (fsub B, A)
5975   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5976     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5977     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5978                        GetNegatedExpression(N0, DAG, LegalOperations));
5979
5980   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5981   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5982       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5983       isa<ConstantFPSDNode>(N0.getOperand(1)))
5984     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5985                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
5986                                    N0.getOperand(1), N1));
5987
5988   // No FP constant should be created after legalization as Instruction
5989   // Selection pass has hard time in dealing with FP constant.
5990   //
5991   // We don't need test this condition for transformation like following, as
5992   // the DAG being transformed implies it is legal to take FP constant as
5993   // operand.
5994   //
5995   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5996   //
5997   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5998
5999   // If allow, fold (fadd (fneg x), x) -> 0.0
6000   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6001       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6002     return DAG.getConstantFP(0.0, VT);
6003
6004     // If allow, fold (fadd x, (fneg x)) -> 0.0
6005   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6006       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6007     return DAG.getConstantFP(0.0, VT);
6008
6009   // In unsafe math mode, we can fold chains of FADD's of the same value
6010   // into multiplications.  This transform is not safe in general because
6011   // we are reducing the number of rounding steps.
6012   if (DAG.getTarget().Options.UnsafeFPMath &&
6013       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6014       !N0CFP && !N1CFP) {
6015     if (N0.getOpcode() == ISD::FMUL) {
6016       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6017       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6018
6019       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6020       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6021         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6022                                      SDValue(CFP00, 0),
6023                                      DAG.getConstantFP(1.0, VT));
6024         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6025                            N1, NewCFP);
6026       }
6027
6028       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6029       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6030         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6031                                      SDValue(CFP01, 0),
6032                                      DAG.getConstantFP(1.0, VT));
6033         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6034                            N1, NewCFP);
6035       }
6036
6037       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6038       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6039           N1.getOperand(0) == N1.getOperand(1) &&
6040           N0.getOperand(1) == N1.getOperand(0)) {
6041         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6042                                      SDValue(CFP00, 0),
6043                                      DAG.getConstantFP(2.0, VT));
6044         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6045                            N0.getOperand(1), NewCFP);
6046       }
6047
6048       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6049       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6050           N1.getOperand(0) == N1.getOperand(1) &&
6051           N0.getOperand(0) == N1.getOperand(0)) {
6052         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6053                                      SDValue(CFP01, 0),
6054                                      DAG.getConstantFP(2.0, VT));
6055         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6056                            N0.getOperand(0), NewCFP);
6057       }
6058     }
6059
6060     if (N1.getOpcode() == ISD::FMUL) {
6061       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6062       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6063
6064       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6065       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6066         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6067                                      SDValue(CFP10, 0),
6068                                      DAG.getConstantFP(1.0, VT));
6069         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6070                            N0, NewCFP);
6071       }
6072
6073       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6074       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6075         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6076                                      SDValue(CFP11, 0),
6077                                      DAG.getConstantFP(1.0, VT));
6078         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6079                            N0, NewCFP);
6080       }
6081
6082
6083       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6084       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6085           N0.getOperand(0) == N0.getOperand(1) &&
6086           N1.getOperand(1) == N0.getOperand(0)) {
6087         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6088                                      SDValue(CFP10, 0),
6089                                      DAG.getConstantFP(2.0, VT));
6090         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6091                            N1.getOperand(1), NewCFP);
6092       }
6093
6094       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6095       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6096           N0.getOperand(0) == N0.getOperand(1) &&
6097           N1.getOperand(0) == N0.getOperand(0)) {
6098         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6099                                      SDValue(CFP11, 0),
6100                                      DAG.getConstantFP(2.0, VT));
6101         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6102                            N1.getOperand(0), NewCFP);
6103       }
6104     }
6105
6106     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6107       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6108       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6109       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6110           (N0.getOperand(0) == N1))
6111         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6112                            N1, DAG.getConstantFP(3.0, VT));
6113     }
6114
6115     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6116       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6117       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6118       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6119           N1.getOperand(0) == N0)
6120         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6121                            N0, DAG.getConstantFP(3.0, VT));
6122     }
6123
6124     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6125     if (AllowNewFpConst &&
6126         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6127         N0.getOperand(0) == N0.getOperand(1) &&
6128         N1.getOperand(0) == N1.getOperand(1) &&
6129         N0.getOperand(0) == N1.getOperand(0))
6130       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6131                          N0.getOperand(0),
6132                          DAG.getConstantFP(4.0, VT));
6133   }
6134
6135   // FADD -> FMA combines:
6136   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6137        DAG.getTarget().Options.UnsafeFPMath) &&
6138       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6139       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6140
6141     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6142     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6143       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6144                          N0.getOperand(0), N0.getOperand(1), N1);
6145
6146     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6147     // Note: Commutes FADD operands.
6148     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6149       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6150                          N1.getOperand(0), N1.getOperand(1), N0);
6151   }
6152
6153   return SDValue();
6154 }
6155
6156 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6157   SDValue N0 = N->getOperand(0);
6158   SDValue N1 = N->getOperand(1);
6159   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6160   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6161   EVT VT = N->getValueType(0);
6162   SDLoc dl(N);
6163
6164   // fold vector ops
6165   if (VT.isVector()) {
6166     SDValue FoldedVOp = SimplifyVBinOp(N);
6167     if (FoldedVOp.getNode()) return FoldedVOp;
6168   }
6169
6170   // fold (fsub c1, c2) -> c1-c2
6171   if (N0CFP && N1CFP)
6172     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6173   // fold (fsub A, 0) -> A
6174   if (DAG.getTarget().Options.UnsafeFPMath &&
6175       N1CFP && N1CFP->getValueAPF().isZero())
6176     return N0;
6177   // fold (fsub 0, B) -> -B
6178   if (DAG.getTarget().Options.UnsafeFPMath &&
6179       N0CFP && N0CFP->getValueAPF().isZero()) {
6180     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6181       return GetNegatedExpression(N1, DAG, LegalOperations);
6182     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6183       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6184   }
6185   // fold (fsub A, (fneg B)) -> (fadd A, B)
6186   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6187     return DAG.getNode(ISD::FADD, dl, VT, N0,
6188                        GetNegatedExpression(N1, DAG, LegalOperations));
6189
6190   // If 'unsafe math' is enabled, fold
6191   //    (fsub x, x) -> 0.0 &
6192   //    (fsub x, (fadd x, y)) -> (fneg y) &
6193   //    (fsub x, (fadd y, x)) -> (fneg y)
6194   if (DAG.getTarget().Options.UnsafeFPMath) {
6195     if (N0 == N1)
6196       return DAG.getConstantFP(0.0f, VT);
6197
6198     if (N1.getOpcode() == ISD::FADD) {
6199       SDValue N10 = N1->getOperand(0);
6200       SDValue N11 = N1->getOperand(1);
6201
6202       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6203                                           &DAG.getTarget().Options))
6204         return GetNegatedExpression(N11, DAG, LegalOperations);
6205
6206       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6207                                           &DAG.getTarget().Options))
6208         return GetNegatedExpression(N10, DAG, LegalOperations);
6209     }
6210   }
6211
6212   // FSUB -> FMA combines:
6213   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6214        DAG.getTarget().Options.UnsafeFPMath) &&
6215       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6216       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6217
6218     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6219     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6220       return DAG.getNode(ISD::FMA, dl, VT,
6221                          N0.getOperand(0), N0.getOperand(1),
6222                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6223
6224     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6225     // Note: Commutes FSUB operands.
6226     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6227       return DAG.getNode(ISD::FMA, dl, VT,
6228                          DAG.getNode(ISD::FNEG, dl, VT,
6229                          N1.getOperand(0)),
6230                          N1.getOperand(1), N0);
6231
6232     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6233     if (N0.getOpcode() == ISD::FNEG &&
6234         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6235         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6236       SDValue N00 = N0.getOperand(0).getOperand(0);
6237       SDValue N01 = N0.getOperand(0).getOperand(1);
6238       return DAG.getNode(ISD::FMA, dl, VT,
6239                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6240                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6241     }
6242   }
6243
6244   return SDValue();
6245 }
6246
6247 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6248   SDValue N0 = N->getOperand(0);
6249   SDValue N1 = N->getOperand(1);
6250   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6251   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6252   EVT VT = N->getValueType(0);
6253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6254
6255   // fold vector ops
6256   if (VT.isVector()) {
6257     SDValue FoldedVOp = SimplifyVBinOp(N);
6258     if (FoldedVOp.getNode()) return FoldedVOp;
6259   }
6260
6261   // fold (fmul c1, c2) -> c1*c2
6262   if (N0CFP && N1CFP)
6263     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6264   // canonicalize constant to RHS
6265   if (N0CFP && !N1CFP)
6266     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6267   // fold (fmul A, 0) -> 0
6268   if (DAG.getTarget().Options.UnsafeFPMath &&
6269       N1CFP && N1CFP->getValueAPF().isZero())
6270     return N1;
6271   // fold (fmul A, 0) -> 0, vector edition.
6272   if (DAG.getTarget().Options.UnsafeFPMath &&
6273       ISD::isBuildVectorAllZeros(N1.getNode()))
6274     return N1;
6275   // fold (fmul A, 1.0) -> A
6276   if (N1CFP && N1CFP->isExactlyValue(1.0))
6277     return N0;
6278   // fold (fmul X, 2.0) -> (fadd X, X)
6279   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6280     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6281   // fold (fmul X, -1.0) -> (fneg X)
6282   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6283     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6284       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6285
6286   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6287   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6288                                        &DAG.getTarget().Options)) {
6289     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6290                                          &DAG.getTarget().Options)) {
6291       // Both can be negated for free, check to see if at least one is cheaper
6292       // negated.
6293       if (LHSNeg == 2 || RHSNeg == 2)
6294         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6295                            GetNegatedExpression(N0, DAG, LegalOperations),
6296                            GetNegatedExpression(N1, DAG, LegalOperations));
6297     }
6298   }
6299
6300   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6301   if (DAG.getTarget().Options.UnsafeFPMath &&
6302       N1CFP && N0.getOpcode() == ISD::FMUL &&
6303       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6304     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6305                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6306                                    N0.getOperand(1), N1));
6307
6308   return SDValue();
6309 }
6310
6311 SDValue DAGCombiner::visitFMA(SDNode *N) {
6312   SDValue N0 = N->getOperand(0);
6313   SDValue N1 = N->getOperand(1);
6314   SDValue N2 = N->getOperand(2);
6315   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6316   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6317   EVT VT = N->getValueType(0);
6318   SDLoc dl(N);
6319
6320   if (DAG.getTarget().Options.UnsafeFPMath) {
6321     if (N0CFP && N0CFP->isZero())
6322       return N2;
6323     if (N1CFP && N1CFP->isZero())
6324       return N2;
6325   }
6326   if (N0CFP && N0CFP->isExactlyValue(1.0))
6327     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6328   if (N1CFP && N1CFP->isExactlyValue(1.0))
6329     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6330
6331   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6332   if (N0CFP && !N1CFP)
6333     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6334
6335   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6336   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6337       N2.getOpcode() == ISD::FMUL &&
6338       N0 == N2.getOperand(0) &&
6339       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6340     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6341                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6342   }
6343
6344
6345   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6346   if (DAG.getTarget().Options.UnsafeFPMath &&
6347       N0.getOpcode() == ISD::FMUL && N1CFP &&
6348       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6349     return DAG.getNode(ISD::FMA, dl, VT,
6350                        N0.getOperand(0),
6351                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6352                        N2);
6353   }
6354
6355   // (fma x, 1, y) -> (fadd x, y)
6356   // (fma x, -1, y) -> (fadd (fneg x), y)
6357   if (N1CFP) {
6358     if (N1CFP->isExactlyValue(1.0))
6359       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6360
6361     if (N1CFP->isExactlyValue(-1.0) &&
6362         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6363       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6364       AddToWorkList(RHSNeg.getNode());
6365       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6366     }
6367   }
6368
6369   // (fma x, c, x) -> (fmul x, (c+1))
6370   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6371     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6372                        DAG.getNode(ISD::FADD, dl, VT,
6373                                    N1, DAG.getConstantFP(1.0, VT)));
6374
6375   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6376   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6377       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6378     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6379                        DAG.getNode(ISD::FADD, dl, VT,
6380                                    N1, DAG.getConstantFP(-1.0, VT)));
6381
6382
6383   return SDValue();
6384 }
6385
6386 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6387   SDValue N0 = N->getOperand(0);
6388   SDValue N1 = N->getOperand(1);
6389   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6390   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6391   EVT VT = N->getValueType(0);
6392   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6393
6394   // fold vector ops
6395   if (VT.isVector()) {
6396     SDValue FoldedVOp = SimplifyVBinOp(N);
6397     if (FoldedVOp.getNode()) return FoldedVOp;
6398   }
6399
6400   // fold (fdiv c1, c2) -> c1/c2
6401   if (N0CFP && N1CFP)
6402     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6403
6404   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6405   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6406     // Compute the reciprocal 1.0 / c2.
6407     APFloat N1APF = N1CFP->getValueAPF();
6408     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6409     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6410     // Only do the transform if the reciprocal is a legal fp immediate that
6411     // isn't too nasty (eg NaN, denormal, ...).
6412     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6413         (!LegalOperations ||
6414          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6415          // backend)... we should handle this gracefully after Legalize.
6416          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6417          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6418          TLI.isFPImmLegal(Recip, VT)))
6419       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6420                          DAG.getConstantFP(Recip, VT));
6421   }
6422
6423   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6424   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6425                                        &DAG.getTarget().Options)) {
6426     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6427                                          &DAG.getTarget().Options)) {
6428       // Both can be negated for free, check to see if at least one is cheaper
6429       // negated.
6430       if (LHSNeg == 2 || RHSNeg == 2)
6431         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6432                            GetNegatedExpression(N0, DAG, LegalOperations),
6433                            GetNegatedExpression(N1, DAG, LegalOperations));
6434     }
6435   }
6436
6437   return SDValue();
6438 }
6439
6440 SDValue DAGCombiner::visitFREM(SDNode *N) {
6441   SDValue N0 = N->getOperand(0);
6442   SDValue N1 = N->getOperand(1);
6443   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6444   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6445   EVT VT = N->getValueType(0);
6446
6447   // fold (frem c1, c2) -> fmod(c1,c2)
6448   if (N0CFP && N1CFP)
6449     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6450
6451   return SDValue();
6452 }
6453
6454 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6455   SDValue N0 = N->getOperand(0);
6456   SDValue N1 = N->getOperand(1);
6457   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6458   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6459   EVT VT = N->getValueType(0);
6460
6461   if (N0CFP && N1CFP)  // Constant fold
6462     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6463
6464   if (N1CFP) {
6465     const APFloat& V = N1CFP->getValueAPF();
6466     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6467     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6468     if (!V.isNegative()) {
6469       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6470         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6471     } else {
6472       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6473         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6474                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6475     }
6476   }
6477
6478   // copysign(fabs(x), y) -> copysign(x, y)
6479   // copysign(fneg(x), y) -> copysign(x, y)
6480   // copysign(copysign(x,z), y) -> copysign(x, y)
6481   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6482       N0.getOpcode() == ISD::FCOPYSIGN)
6483     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6484                        N0.getOperand(0), N1);
6485
6486   // copysign(x, abs(y)) -> abs(x)
6487   if (N1.getOpcode() == ISD::FABS)
6488     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6489
6490   // copysign(x, copysign(y,z)) -> copysign(x, z)
6491   if (N1.getOpcode() == ISD::FCOPYSIGN)
6492     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6493                        N0, N1.getOperand(1));
6494
6495   // copysign(x, fp_extend(y)) -> copysign(x, y)
6496   // copysign(x, fp_round(y)) -> copysign(x, y)
6497   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6498     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6499                        N0, N1.getOperand(0));
6500
6501   return SDValue();
6502 }
6503
6504 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6505   SDValue N0 = N->getOperand(0);
6506   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6507   EVT VT = N->getValueType(0);
6508   EVT OpVT = N0.getValueType();
6509
6510   // fold (sint_to_fp c1) -> c1fp
6511   if (N0C &&
6512       // ...but only if the target supports immediate floating-point values
6513       (!LegalOperations ||
6514        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6515     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6516
6517   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6518   // but UINT_TO_FP is legal on this target, try to convert.
6519   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6520       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6521     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6522     if (DAG.SignBitIsZero(N0))
6523       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6524   }
6525
6526   // The next optimizations are desireable only if SELECT_CC can be lowered.
6527   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6528   // having to say they don't support SELECT_CC on every type the DAG knows
6529   // about, since there is no way to mark an opcode illegal at all value types
6530   // (See also visitSELECT)
6531   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6532     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6533     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6534         !VT.isVector() &&
6535         (!LegalOperations ||
6536          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6537       SDValue Ops[] =
6538         { N0.getOperand(0), N0.getOperand(1),
6539           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6540           N0.getOperand(2) };
6541       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6542     }
6543
6544     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6545     //      (select_cc x, y, 1.0, 0.0,, cc)
6546     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6547         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6548         (!LegalOperations ||
6549          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6550       SDValue Ops[] =
6551         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6552           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6553           N0.getOperand(0).getOperand(2) };
6554       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6555     }
6556   }
6557
6558   return SDValue();
6559 }
6560
6561 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6562   SDValue N0 = N->getOperand(0);
6563   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6564   EVT VT = N->getValueType(0);
6565   EVT OpVT = N0.getValueType();
6566
6567   // fold (uint_to_fp c1) -> c1fp
6568   if (N0C &&
6569       // ...but only if the target supports immediate floating-point values
6570       (!LegalOperations ||
6571        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6572     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6573
6574   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6575   // but SINT_TO_FP is legal on this target, try to convert.
6576   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6577       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6578     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6579     if (DAG.SignBitIsZero(N0))
6580       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6581   }
6582
6583   // The next optimizations are desireable only if SELECT_CC can be lowered.
6584   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6585   // having to say they don't support SELECT_CC on every type the DAG knows
6586   // about, since there is no way to mark an opcode illegal at all value types
6587   // (See also visitSELECT)
6588   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6589     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6590
6591     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6592         (!LegalOperations ||
6593          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6594       SDValue Ops[] =
6595         { N0.getOperand(0), N0.getOperand(1),
6596           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6597           N0.getOperand(2) };
6598       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6599     }
6600   }
6601
6602   return SDValue();
6603 }
6604
6605 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6606   SDValue N0 = N->getOperand(0);
6607   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6608   EVT VT = N->getValueType(0);
6609
6610   // fold (fp_to_sint c1fp) -> c1
6611   if (N0CFP)
6612     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6613
6614   return SDValue();
6615 }
6616
6617 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6618   SDValue N0 = N->getOperand(0);
6619   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6620   EVT VT = N->getValueType(0);
6621
6622   // fold (fp_to_uint c1fp) -> c1
6623   if (N0CFP)
6624     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6625
6626   return SDValue();
6627 }
6628
6629 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6630   SDValue N0 = N->getOperand(0);
6631   SDValue N1 = N->getOperand(1);
6632   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6633   EVT VT = N->getValueType(0);
6634
6635   // fold (fp_round c1fp) -> c1fp
6636   if (N0CFP)
6637     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6638
6639   // fold (fp_round (fp_extend x)) -> x
6640   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6641     return N0.getOperand(0);
6642
6643   // fold (fp_round (fp_round x)) -> (fp_round x)
6644   if (N0.getOpcode() == ISD::FP_ROUND) {
6645     // This is a value preserving truncation if both round's are.
6646     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6647                    N0.getNode()->getConstantOperandVal(1) == 1;
6648     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6649                        DAG.getIntPtrConstant(IsTrunc));
6650   }
6651
6652   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6653   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6654     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6655                               N0.getOperand(0), N1);
6656     AddToWorkList(Tmp.getNode());
6657     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6658                        Tmp, N0.getOperand(1));
6659   }
6660
6661   return SDValue();
6662 }
6663
6664 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6665   SDValue N0 = N->getOperand(0);
6666   EVT VT = N->getValueType(0);
6667   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6668   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6669
6670   // fold (fp_round_inreg c1fp) -> c1fp
6671   if (N0CFP && isTypeLegal(EVT)) {
6672     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6673     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6674   }
6675
6676   return SDValue();
6677 }
6678
6679 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6680   SDValue N0 = N->getOperand(0);
6681   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6682   EVT VT = N->getValueType(0);
6683
6684   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6685   if (N->hasOneUse() &&
6686       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6687     return SDValue();
6688
6689   // fold (fp_extend c1fp) -> c1fp
6690   if (N0CFP)
6691     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6692
6693   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6694   // value of X.
6695   if (N0.getOpcode() == ISD::FP_ROUND
6696       && N0.getNode()->getConstantOperandVal(1) == 1) {
6697     SDValue In = N0.getOperand(0);
6698     if (In.getValueType() == VT) return In;
6699     if (VT.bitsLT(In.getValueType()))
6700       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6701                          In, N0.getOperand(1));
6702     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6703   }
6704
6705   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6706   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6707       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6708        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6709     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6710     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6711                                      LN0->getChain(),
6712                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6713                                      N0.getValueType(),
6714                                      LN0->isVolatile(), LN0->isNonTemporal(),
6715                                      LN0->getAlignment());
6716     CombineTo(N, ExtLoad);
6717     CombineTo(N0.getNode(),
6718               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6719                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6720               ExtLoad.getValue(1));
6721     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6722   }
6723
6724   return SDValue();
6725 }
6726
6727 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6728   SDValue N0 = N->getOperand(0);
6729   EVT VT = N->getValueType(0);
6730
6731   if (VT.isVector()) {
6732     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6733     if (FoldedVOp.getNode()) return FoldedVOp;
6734   }
6735
6736   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6737                          &DAG.getTarget().Options))
6738     return GetNegatedExpression(N0, DAG, LegalOperations);
6739
6740   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6741   // constant pool values.
6742   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6743       !VT.isVector() &&
6744       N0.getNode()->hasOneUse() &&
6745       N0.getOperand(0).getValueType().isInteger()) {
6746     SDValue Int = N0.getOperand(0);
6747     EVT IntVT = Int.getValueType();
6748     if (IntVT.isInteger() && !IntVT.isVector()) {
6749       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6750               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6751       AddToWorkList(Int.getNode());
6752       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6753                          VT, Int);
6754     }
6755   }
6756
6757   // (fneg (fmul c, x)) -> (fmul -c, x)
6758   if (N0.getOpcode() == ISD::FMUL) {
6759     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6760     if (CFP1)
6761       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6762                          N0.getOperand(0),
6763                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6764                                      N0.getOperand(1)));
6765   }
6766
6767   return SDValue();
6768 }
6769
6770 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6771   SDValue N0 = N->getOperand(0);
6772   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6773   EVT VT = N->getValueType(0);
6774
6775   // fold (fceil c1) -> fceil(c1)
6776   if (N0CFP)
6777     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6778
6779   return SDValue();
6780 }
6781
6782 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6783   SDValue N0 = N->getOperand(0);
6784   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6785   EVT VT = N->getValueType(0);
6786
6787   // fold (ftrunc c1) -> ftrunc(c1)
6788   if (N0CFP)
6789     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6790
6791   return SDValue();
6792 }
6793
6794 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6795   SDValue N0 = N->getOperand(0);
6796   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6797   EVT VT = N->getValueType(0);
6798
6799   // fold (ffloor c1) -> ffloor(c1)
6800   if (N0CFP)
6801     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6802
6803   return SDValue();
6804 }
6805
6806 SDValue DAGCombiner::visitFABS(SDNode *N) {
6807   SDValue N0 = N->getOperand(0);
6808   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6809   EVT VT = N->getValueType(0);
6810
6811   if (VT.isVector()) {
6812     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6813     if (FoldedVOp.getNode()) return FoldedVOp;
6814   }
6815
6816   // fold (fabs c1) -> fabs(c1)
6817   if (N0CFP)
6818     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6819   // fold (fabs (fabs x)) -> (fabs x)
6820   if (N0.getOpcode() == ISD::FABS)
6821     return N->getOperand(0);
6822   // fold (fabs (fneg x)) -> (fabs x)
6823   // fold (fabs (fcopysign x, y)) -> (fabs x)
6824   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6825     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6826
6827   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6828   // constant pool values.
6829   if (!TLI.isFAbsFree(VT) &&
6830       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6831       N0.getOperand(0).getValueType().isInteger() &&
6832       !N0.getOperand(0).getValueType().isVector()) {
6833     SDValue Int = N0.getOperand(0);
6834     EVT IntVT = Int.getValueType();
6835     if (IntVT.isInteger() && !IntVT.isVector()) {
6836       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6837              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6838       AddToWorkList(Int.getNode());
6839       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6840                          N->getValueType(0), Int);
6841     }
6842   }
6843
6844   return SDValue();
6845 }
6846
6847 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6848   SDValue Chain = N->getOperand(0);
6849   SDValue N1 = N->getOperand(1);
6850   SDValue N2 = N->getOperand(2);
6851
6852   // If N is a constant we could fold this into a fallthrough or unconditional
6853   // branch. However that doesn't happen very often in normal code, because
6854   // Instcombine/SimplifyCFG should have handled the available opportunities.
6855   // If we did this folding here, it would be necessary to update the
6856   // MachineBasicBlock CFG, which is awkward.
6857
6858   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6859   // on the target.
6860   if (N1.getOpcode() == ISD::SETCC &&
6861       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6862                                    N1.getOperand(0).getValueType())) {
6863     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6864                        Chain, N1.getOperand(2),
6865                        N1.getOperand(0), N1.getOperand(1), N2);
6866   }
6867
6868   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6869       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6870        (N1.getOperand(0).hasOneUse() &&
6871         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6872     SDNode *Trunc = 0;
6873     if (N1.getOpcode() == ISD::TRUNCATE) {
6874       // Look pass the truncate.
6875       Trunc = N1.getNode();
6876       N1 = N1.getOperand(0);
6877     }
6878
6879     // Match this pattern so that we can generate simpler code:
6880     //
6881     //   %a = ...
6882     //   %b = and i32 %a, 2
6883     //   %c = srl i32 %b, 1
6884     //   brcond i32 %c ...
6885     //
6886     // into
6887     //
6888     //   %a = ...
6889     //   %b = and i32 %a, 2
6890     //   %c = setcc eq %b, 0
6891     //   brcond %c ...
6892     //
6893     // This applies only when the AND constant value has one bit set and the
6894     // SRL constant is equal to the log2 of the AND constant. The back-end is
6895     // smart enough to convert the result into a TEST/JMP sequence.
6896     SDValue Op0 = N1.getOperand(0);
6897     SDValue Op1 = N1.getOperand(1);
6898
6899     if (Op0.getOpcode() == ISD::AND &&
6900         Op1.getOpcode() == ISD::Constant) {
6901       SDValue AndOp1 = Op0.getOperand(1);
6902
6903       if (AndOp1.getOpcode() == ISD::Constant) {
6904         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6905
6906         if (AndConst.isPowerOf2() &&
6907             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6908           SDValue SetCC =
6909             DAG.getSetCC(SDLoc(N),
6910                          getSetCCResultType(Op0.getValueType()),
6911                          Op0, DAG.getConstant(0, Op0.getValueType()),
6912                          ISD::SETNE);
6913
6914           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6915                                           MVT::Other, Chain, SetCC, N2);
6916           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6917           // will convert it back to (X & C1) >> C2.
6918           CombineTo(N, NewBRCond, false);
6919           // Truncate is dead.
6920           if (Trunc) {
6921             removeFromWorkList(Trunc);
6922             DAG.DeleteNode(Trunc);
6923           }
6924           // Replace the uses of SRL with SETCC
6925           WorkListRemover DeadNodes(*this);
6926           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6927           removeFromWorkList(N1.getNode());
6928           DAG.DeleteNode(N1.getNode());
6929           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6930         }
6931       }
6932     }
6933
6934     if (Trunc)
6935       // Restore N1 if the above transformation doesn't match.
6936       N1 = N->getOperand(1);
6937   }
6938
6939   // Transform br(xor(x, y)) -> br(x != y)
6940   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6941   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6942     SDNode *TheXor = N1.getNode();
6943     SDValue Op0 = TheXor->getOperand(0);
6944     SDValue Op1 = TheXor->getOperand(1);
6945     if (Op0.getOpcode() == Op1.getOpcode()) {
6946       // Avoid missing important xor optimizations.
6947       SDValue Tmp = visitXOR(TheXor);
6948       if (Tmp.getNode()) {
6949         if (Tmp.getNode() != TheXor) {
6950           DEBUG(dbgs() << "\nReplacing.8 ";
6951                 TheXor->dump(&DAG);
6952                 dbgs() << "\nWith: ";
6953                 Tmp.getNode()->dump(&DAG);
6954                 dbgs() << '\n');
6955           WorkListRemover DeadNodes(*this);
6956           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6957           removeFromWorkList(TheXor);
6958           DAG.DeleteNode(TheXor);
6959           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6960                              MVT::Other, Chain, Tmp, N2);
6961         }
6962
6963         // visitXOR has changed XOR's operands or replaced the XOR completely,
6964         // bail out.
6965         return SDValue(N, 0);
6966       }
6967     }
6968
6969     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6970       bool Equal = false;
6971       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6972         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6973             Op0.getOpcode() == ISD::XOR) {
6974           TheXor = Op0.getNode();
6975           Equal = true;
6976         }
6977
6978       EVT SetCCVT = N1.getValueType();
6979       if (LegalTypes)
6980         SetCCVT = getSetCCResultType(SetCCVT);
6981       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6982                                    SetCCVT,
6983                                    Op0, Op1,
6984                                    Equal ? ISD::SETEQ : ISD::SETNE);
6985       // Replace the uses of XOR with SETCC
6986       WorkListRemover DeadNodes(*this);
6987       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6988       removeFromWorkList(N1.getNode());
6989       DAG.DeleteNode(N1.getNode());
6990       return DAG.getNode(ISD::BRCOND, SDLoc(N),
6991                          MVT::Other, Chain, SetCC, N2);
6992     }
6993   }
6994
6995   return SDValue();
6996 }
6997
6998 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6999 //
7000 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7001   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7002   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7003
7004   // If N is a constant we could fold this into a fallthrough or unconditional
7005   // branch. However that doesn't happen very often in normal code, because
7006   // Instcombine/SimplifyCFG should have handled the available opportunities.
7007   // If we did this folding here, it would be necessary to update the
7008   // MachineBasicBlock CFG, which is awkward.
7009
7010   // Use SimplifySetCC to simplify SETCC's.
7011   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7012                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7013                                false);
7014   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7015
7016   // fold to a simpler setcc
7017   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7018     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7019                        N->getOperand(0), Simp.getOperand(2),
7020                        Simp.getOperand(0), Simp.getOperand(1),
7021                        N->getOperand(4));
7022
7023   return SDValue();
7024 }
7025
7026 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7027 /// uses N as its base pointer and that N may be folded in the load / store
7028 /// addressing mode.
7029 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7030                                     SelectionDAG &DAG,
7031                                     const TargetLowering &TLI) {
7032   EVT VT;
7033   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7034     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7035       return false;
7036     VT = Use->getValueType(0);
7037   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7038     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7039       return false;
7040     VT = ST->getValue().getValueType();
7041   } else
7042     return false;
7043
7044   TargetLowering::AddrMode AM;
7045   if (N->getOpcode() == ISD::ADD) {
7046     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7047     if (Offset)
7048       // [reg +/- imm]
7049       AM.BaseOffs = Offset->getSExtValue();
7050     else
7051       // [reg +/- reg]
7052       AM.Scale = 1;
7053   } else if (N->getOpcode() == ISD::SUB) {
7054     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7055     if (Offset)
7056       // [reg +/- imm]
7057       AM.BaseOffs = -Offset->getSExtValue();
7058     else
7059       // [reg +/- reg]
7060       AM.Scale = 1;
7061   } else
7062     return false;
7063
7064   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7065 }
7066
7067 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7068 /// pre-indexed load / store when the base pointer is an add or subtract
7069 /// and it has other uses besides the load / store. After the
7070 /// transformation, the new indexed load / store has effectively folded
7071 /// the add / subtract in and all of its other uses are redirected to the
7072 /// new load / store.
7073 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7074   if (Level < AfterLegalizeDAG)
7075     return false;
7076
7077   bool isLoad = true;
7078   SDValue Ptr;
7079   EVT VT;
7080   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7081     if (LD->isIndexed())
7082       return false;
7083     VT = LD->getMemoryVT();
7084     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7085         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7086       return false;
7087     Ptr = LD->getBasePtr();
7088   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7089     if (ST->isIndexed())
7090       return false;
7091     VT = ST->getMemoryVT();
7092     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7093         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7094       return false;
7095     Ptr = ST->getBasePtr();
7096     isLoad = false;
7097   } else {
7098     return false;
7099   }
7100
7101   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7102   // out.  There is no reason to make this a preinc/predec.
7103   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7104       Ptr.getNode()->hasOneUse())
7105     return false;
7106
7107   // Ask the target to do addressing mode selection.
7108   SDValue BasePtr;
7109   SDValue Offset;
7110   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7111   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7112     return false;
7113
7114   // Backends without true r+i pre-indexed forms may need to pass a
7115   // constant base with a variable offset so that constant coercion
7116   // will work with the patterns in canonical form.
7117   bool Swapped = false;
7118   if (isa<ConstantSDNode>(BasePtr)) {
7119     std::swap(BasePtr, Offset);
7120     Swapped = true;
7121   }
7122
7123   // Don't create a indexed load / store with zero offset.
7124   if (isa<ConstantSDNode>(Offset) &&
7125       cast<ConstantSDNode>(Offset)->isNullValue())
7126     return false;
7127
7128   // Try turning it into a pre-indexed load / store except when:
7129   // 1) The new base ptr is a frame index.
7130   // 2) If N is a store and the new base ptr is either the same as or is a
7131   //    predecessor of the value being stored.
7132   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7133   //    that would create a cycle.
7134   // 4) All uses are load / store ops that use it as old base ptr.
7135
7136   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7137   // (plus the implicit offset) to a register to preinc anyway.
7138   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7139     return false;
7140
7141   // Check #2.
7142   if (!isLoad) {
7143     SDValue Val = cast<StoreSDNode>(N)->getValue();
7144     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7145       return false;
7146   }
7147
7148   // If the offset is a constant, there may be other adds of constants that
7149   // can be folded with this one. We should do this to avoid having to keep
7150   // a copy of the original base pointer.
7151   SmallVector<SDNode *, 16> OtherUses;
7152   if (isa<ConstantSDNode>(Offset))
7153     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7154          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7155       SDNode *Use = *I;
7156       if (Use == Ptr.getNode())
7157         continue;
7158
7159       if (Use->isPredecessorOf(N))
7160         continue;
7161
7162       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7163         OtherUses.clear();
7164         break;
7165       }
7166
7167       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7168       if (Op1.getNode() == BasePtr.getNode())
7169         std::swap(Op0, Op1);
7170       assert(Op0.getNode() == BasePtr.getNode() &&
7171              "Use of ADD/SUB but not an operand");
7172
7173       if (!isa<ConstantSDNode>(Op1)) {
7174         OtherUses.clear();
7175         break;
7176       }
7177
7178       // FIXME: In some cases, we can be smarter about this.
7179       if (Op1.getValueType() != Offset.getValueType()) {
7180         OtherUses.clear();
7181         break;
7182       }
7183
7184       OtherUses.push_back(Use);
7185     }
7186
7187   if (Swapped)
7188     std::swap(BasePtr, Offset);
7189
7190   // Now check for #3 and #4.
7191   bool RealUse = false;
7192
7193   // Caches for hasPredecessorHelper
7194   SmallPtrSet<const SDNode *, 32> Visited;
7195   SmallVector<const SDNode *, 16> Worklist;
7196
7197   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7198          E = Ptr.getNode()->use_end(); I != E; ++I) {
7199     SDNode *Use = *I;
7200     if (Use == N)
7201       continue;
7202     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7203       return false;
7204
7205     // If Ptr may be folded in addressing mode of other use, then it's
7206     // not profitable to do this transformation.
7207     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7208       RealUse = true;
7209   }
7210
7211   if (!RealUse)
7212     return false;
7213
7214   SDValue Result;
7215   if (isLoad)
7216     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7217                                 BasePtr, Offset, AM);
7218   else
7219     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7220                                  BasePtr, Offset, AM);
7221   ++PreIndexedNodes;
7222   ++NodesCombined;
7223   DEBUG(dbgs() << "\nReplacing.4 ";
7224         N->dump(&DAG);
7225         dbgs() << "\nWith: ";
7226         Result.getNode()->dump(&DAG);
7227         dbgs() << '\n');
7228   WorkListRemover DeadNodes(*this);
7229   if (isLoad) {
7230     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7231     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7232   } else {
7233     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7234   }
7235
7236   // Finally, since the node is now dead, remove it from the graph.
7237   DAG.DeleteNode(N);
7238
7239   if (Swapped)
7240     std::swap(BasePtr, Offset);
7241
7242   // Replace other uses of BasePtr that can be updated to use Ptr
7243   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7244     unsigned OffsetIdx = 1;
7245     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7246       OffsetIdx = 0;
7247     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7248            BasePtr.getNode() && "Expected BasePtr operand");
7249
7250     // We need to replace ptr0 in the following expression:
7251     //   x0 * offset0 + y0 * ptr0 = t0
7252     // knowing that
7253     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7254     //
7255     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7256     // indexed load/store and the expresion that needs to be re-written.
7257     //
7258     // Therefore, we have:
7259     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7260
7261     ConstantSDNode *CN =
7262       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7263     int X0, X1, Y0, Y1;
7264     APInt Offset0 = CN->getAPIntValue();
7265     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7266
7267     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7268     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7269     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7270     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7271
7272     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7273
7274     APInt CNV = Offset0;
7275     if (X0 < 0) CNV = -CNV;
7276     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7277     else CNV = CNV - Offset1;
7278
7279     // We can now generate the new expression.
7280     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7281     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7282
7283     SDValue NewUse = DAG.getNode(Opcode,
7284                                  SDLoc(OtherUses[i]),
7285                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7286     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7287     removeFromWorkList(OtherUses[i]);
7288     DAG.DeleteNode(OtherUses[i]);
7289   }
7290
7291   // Replace the uses of Ptr with uses of the updated base value.
7292   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7293   removeFromWorkList(Ptr.getNode());
7294   DAG.DeleteNode(Ptr.getNode());
7295
7296   return true;
7297 }
7298
7299 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7300 /// add / sub of the base pointer node into a post-indexed load / store.
7301 /// The transformation folded the add / subtract into the new indexed
7302 /// load / store effectively and all of its uses are redirected to the
7303 /// new load / store.
7304 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7305   if (Level < AfterLegalizeDAG)
7306     return false;
7307
7308   bool isLoad = true;
7309   SDValue Ptr;
7310   EVT VT;
7311   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7312     if (LD->isIndexed())
7313       return false;
7314     VT = LD->getMemoryVT();
7315     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7316         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7317       return false;
7318     Ptr = LD->getBasePtr();
7319   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7320     if (ST->isIndexed())
7321       return false;
7322     VT = ST->getMemoryVT();
7323     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7324         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7325       return false;
7326     Ptr = ST->getBasePtr();
7327     isLoad = false;
7328   } else {
7329     return false;
7330   }
7331
7332   if (Ptr.getNode()->hasOneUse())
7333     return false;
7334
7335   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7336          E = Ptr.getNode()->use_end(); I != E; ++I) {
7337     SDNode *Op = *I;
7338     if (Op == N ||
7339         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7340       continue;
7341
7342     SDValue BasePtr;
7343     SDValue Offset;
7344     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7345     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7346       // Don't create a indexed load / store with zero offset.
7347       if (isa<ConstantSDNode>(Offset) &&
7348           cast<ConstantSDNode>(Offset)->isNullValue())
7349         continue;
7350
7351       // Try turning it into a post-indexed load / store except when
7352       // 1) All uses are load / store ops that use it as base ptr (and
7353       //    it may be folded as addressing mmode).
7354       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7355       //    nor a successor of N. Otherwise, if Op is folded that would
7356       //    create a cycle.
7357
7358       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7359         continue;
7360
7361       // Check for #1.
7362       bool TryNext = false;
7363       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7364              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7365         SDNode *Use = *II;
7366         if (Use == Ptr.getNode())
7367           continue;
7368
7369         // If all the uses are load / store addresses, then don't do the
7370         // transformation.
7371         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7372           bool RealUse = false;
7373           for (SDNode::use_iterator III = Use->use_begin(),
7374                  EEE = Use->use_end(); III != EEE; ++III) {
7375             SDNode *UseUse = *III;
7376             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7377               RealUse = true;
7378           }
7379
7380           if (!RealUse) {
7381             TryNext = true;
7382             break;
7383           }
7384         }
7385       }
7386
7387       if (TryNext)
7388         continue;
7389
7390       // Check for #2
7391       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7392         SDValue Result = isLoad
7393           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7394                                BasePtr, Offset, AM)
7395           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7396                                 BasePtr, Offset, AM);
7397         ++PostIndexedNodes;
7398         ++NodesCombined;
7399         DEBUG(dbgs() << "\nReplacing.5 ";
7400               N->dump(&DAG);
7401               dbgs() << "\nWith: ";
7402               Result.getNode()->dump(&DAG);
7403               dbgs() << '\n');
7404         WorkListRemover DeadNodes(*this);
7405         if (isLoad) {
7406           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7407           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7408         } else {
7409           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7410         }
7411
7412         // Finally, since the node is now dead, remove it from the graph.
7413         DAG.DeleteNode(N);
7414
7415         // Replace the uses of Use with uses of the updated base value.
7416         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7417                                       Result.getValue(isLoad ? 1 : 0));
7418         removeFromWorkList(Op);
7419         DAG.DeleteNode(Op);
7420         return true;
7421       }
7422     }
7423   }
7424
7425   return false;
7426 }
7427
7428 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7429   LoadSDNode *LD  = cast<LoadSDNode>(N);
7430   SDValue Chain = LD->getChain();
7431   SDValue Ptr   = LD->getBasePtr();
7432
7433   // If load is not volatile and there are no uses of the loaded value (and
7434   // the updated indexed value in case of indexed loads), change uses of the
7435   // chain value into uses of the chain input (i.e. delete the dead load).
7436   if (!LD->isVolatile()) {
7437     if (N->getValueType(1) == MVT::Other) {
7438       // Unindexed loads.
7439       if (!N->hasAnyUseOfValue(0)) {
7440         // It's not safe to use the two value CombineTo variant here. e.g.
7441         // v1, chain2 = load chain1, loc
7442         // v2, chain3 = load chain2, loc
7443         // v3         = add v2, c
7444         // Now we replace use of chain2 with chain1.  This makes the second load
7445         // isomorphic to the one we are deleting, and thus makes this load live.
7446         DEBUG(dbgs() << "\nReplacing.6 ";
7447               N->dump(&DAG);
7448               dbgs() << "\nWith chain: ";
7449               Chain.getNode()->dump(&DAG);
7450               dbgs() << "\n");
7451         WorkListRemover DeadNodes(*this);
7452         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7453
7454         if (N->use_empty()) {
7455           removeFromWorkList(N);
7456           DAG.DeleteNode(N);
7457         }
7458
7459         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7460       }
7461     } else {
7462       // Indexed loads.
7463       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7464       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7465         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7466         DEBUG(dbgs() << "\nReplacing.7 ";
7467               N->dump(&DAG);
7468               dbgs() << "\nWith: ";
7469               Undef.getNode()->dump(&DAG);
7470               dbgs() << " and 2 other values\n");
7471         WorkListRemover DeadNodes(*this);
7472         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7473         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7474                                       DAG.getUNDEF(N->getValueType(1)));
7475         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7476         removeFromWorkList(N);
7477         DAG.DeleteNode(N);
7478         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7479       }
7480     }
7481   }
7482
7483   // If this load is directly stored, replace the load value with the stored
7484   // value.
7485   // TODO: Handle store large -> read small portion.
7486   // TODO: Handle TRUNCSTORE/LOADEXT
7487   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7488     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7489       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7490       if (PrevST->getBasePtr() == Ptr &&
7491           PrevST->getValue().getValueType() == N->getValueType(0))
7492       return CombineTo(N, Chain.getOperand(1), Chain);
7493     }
7494   }
7495
7496   // Try to infer better alignment information than the load already has.
7497   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7498     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7499       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7500         SDValue NewLoad =
7501                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7502                               LD->getValueType(0),
7503                               Chain, Ptr, LD->getPointerInfo(),
7504                               LD->getMemoryVT(),
7505                               LD->isVolatile(), LD->isNonTemporal(), Align);
7506         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7507       }
7508     }
7509   }
7510
7511   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7512     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7513   if (UseAA) {
7514     // Walk up chain skipping non-aliasing memory nodes.
7515     SDValue BetterChain = FindBetterChain(N, Chain);
7516
7517     // If there is a better chain.
7518     if (Chain != BetterChain) {
7519       SDValue ReplLoad;
7520
7521       // Replace the chain to void dependency.
7522       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7523         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7524                                BetterChain, Ptr, LD->getPointerInfo(),
7525                                LD->isVolatile(), LD->isNonTemporal(),
7526                                LD->isInvariant(), LD->getAlignment());
7527       } else {
7528         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7529                                   LD->getValueType(0),
7530                                   BetterChain, Ptr, LD->getPointerInfo(),
7531                                   LD->getMemoryVT(),
7532                                   LD->isVolatile(),
7533                                   LD->isNonTemporal(),
7534                                   LD->getAlignment());
7535       }
7536
7537       // Create token factor to keep old chain connected.
7538       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7539                                   MVT::Other, Chain, ReplLoad.getValue(1));
7540
7541       // Make sure the new and old chains are cleaned up.
7542       AddToWorkList(Token.getNode());
7543
7544       // Replace uses with load result and token factor. Don't add users
7545       // to work list.
7546       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7547     }
7548   }
7549
7550   // Try transforming N to an indexed load.
7551   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7552     return SDValue(N, 0);
7553
7554   return SDValue();
7555 }
7556
7557 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7558 /// load is having specific bytes cleared out.  If so, return the byte size
7559 /// being masked out and the shift amount.
7560 static std::pair<unsigned, unsigned>
7561 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7562   std::pair<unsigned, unsigned> Result(0, 0);
7563
7564   // Check for the structure we're looking for.
7565   if (V->getOpcode() != ISD::AND ||
7566       !isa<ConstantSDNode>(V->getOperand(1)) ||
7567       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7568     return Result;
7569
7570   // Check the chain and pointer.
7571   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7572   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7573
7574   // The store should be chained directly to the load or be an operand of a
7575   // tokenfactor.
7576   if (LD == Chain.getNode())
7577     ; // ok.
7578   else if (Chain->getOpcode() != ISD::TokenFactor)
7579     return Result; // Fail.
7580   else {
7581     bool isOk = false;
7582     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7583       if (Chain->getOperand(i).getNode() == LD) {
7584         isOk = true;
7585         break;
7586       }
7587     if (!isOk) return Result;
7588   }
7589
7590   // This only handles simple types.
7591   if (V.getValueType() != MVT::i16 &&
7592       V.getValueType() != MVT::i32 &&
7593       V.getValueType() != MVT::i64)
7594     return Result;
7595
7596   // Check the constant mask.  Invert it so that the bits being masked out are
7597   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7598   // follow the sign bit for uniformity.
7599   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7600   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7601   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7602   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7603   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7604   if (NotMaskLZ == 64) return Result;  // All zero mask.
7605
7606   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7607   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7608     return Result;
7609
7610   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7611   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7612     NotMaskLZ -= 64-V.getValueSizeInBits();
7613
7614   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7615   switch (MaskedBytes) {
7616   case 1:
7617   case 2:
7618   case 4: break;
7619   default: return Result; // All one mask, or 5-byte mask.
7620   }
7621
7622   // Verify that the first bit starts at a multiple of mask so that the access
7623   // is aligned the same as the access width.
7624   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7625
7626   Result.first = MaskedBytes;
7627   Result.second = NotMaskTZ/8;
7628   return Result;
7629 }
7630
7631
7632 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7633 /// provides a value as specified by MaskInfo.  If so, replace the specified
7634 /// store with a narrower store of truncated IVal.
7635 static SDNode *
7636 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7637                                 SDValue IVal, StoreSDNode *St,
7638                                 DAGCombiner *DC) {
7639   unsigned NumBytes = MaskInfo.first;
7640   unsigned ByteShift = MaskInfo.second;
7641   SelectionDAG &DAG = DC->getDAG();
7642
7643   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7644   // that uses this.  If not, this is not a replacement.
7645   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7646                                   ByteShift*8, (ByteShift+NumBytes)*8);
7647   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7648
7649   // Check that it is legal on the target to do this.  It is legal if the new
7650   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7651   // legalization.
7652   MVT VT = MVT::getIntegerVT(NumBytes*8);
7653   if (!DC->isTypeLegal(VT))
7654     return 0;
7655
7656   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7657   // shifted by ByteShift and truncated down to NumBytes.
7658   if (ByteShift)
7659     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7660                        DAG.getConstant(ByteShift*8,
7661                                     DC->getShiftAmountTy(IVal.getValueType())));
7662
7663   // Figure out the offset for the store and the alignment of the access.
7664   unsigned StOffset;
7665   unsigned NewAlign = St->getAlignment();
7666
7667   if (DAG.getTargetLoweringInfo().isLittleEndian())
7668     StOffset = ByteShift;
7669   else
7670     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7671
7672   SDValue Ptr = St->getBasePtr();
7673   if (StOffset) {
7674     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7675                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7676     NewAlign = MinAlign(NewAlign, StOffset);
7677   }
7678
7679   // Truncate down to the new size.
7680   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7681
7682   ++OpsNarrowed;
7683   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7684                       St->getPointerInfo().getWithOffset(StOffset),
7685                       false, false, NewAlign).getNode();
7686 }
7687
7688
7689 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7690 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7691 /// of the loaded bits, try narrowing the load and store if it would end up
7692 /// being a win for performance or code size.
7693 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7694   StoreSDNode *ST  = cast<StoreSDNode>(N);
7695   if (ST->isVolatile())
7696     return SDValue();
7697
7698   SDValue Chain = ST->getChain();
7699   SDValue Value = ST->getValue();
7700   SDValue Ptr   = ST->getBasePtr();
7701   EVT VT = Value.getValueType();
7702
7703   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7704     return SDValue();
7705
7706   unsigned Opc = Value.getOpcode();
7707
7708   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7709   // is a byte mask indicating a consecutive number of bytes, check to see if
7710   // Y is known to provide just those bytes.  If so, we try to replace the
7711   // load + replace + store sequence with a single (narrower) store, which makes
7712   // the load dead.
7713   if (Opc == ISD::OR) {
7714     std::pair<unsigned, unsigned> MaskedLoad;
7715     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7716     if (MaskedLoad.first)
7717       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7718                                                   Value.getOperand(1), ST,this))
7719         return SDValue(NewST, 0);
7720
7721     // Or is commutative, so try swapping X and Y.
7722     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7723     if (MaskedLoad.first)
7724       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7725                                                   Value.getOperand(0), ST,this))
7726         return SDValue(NewST, 0);
7727   }
7728
7729   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7730       Value.getOperand(1).getOpcode() != ISD::Constant)
7731     return SDValue();
7732
7733   SDValue N0 = Value.getOperand(0);
7734   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7735       Chain == SDValue(N0.getNode(), 1)) {
7736     LoadSDNode *LD = cast<LoadSDNode>(N0);
7737     if (LD->getBasePtr() != Ptr ||
7738         LD->getPointerInfo().getAddrSpace() !=
7739         ST->getPointerInfo().getAddrSpace())
7740       return SDValue();
7741
7742     // Find the type to narrow it the load / op / store to.
7743     SDValue N1 = Value.getOperand(1);
7744     unsigned BitWidth = N1.getValueSizeInBits();
7745     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7746     if (Opc == ISD::AND)
7747       Imm ^= APInt::getAllOnesValue(BitWidth);
7748     if (Imm == 0 || Imm.isAllOnesValue())
7749       return SDValue();
7750     unsigned ShAmt = Imm.countTrailingZeros();
7751     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7752     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7753     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7754     while (NewBW < BitWidth &&
7755            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7756              TLI.isNarrowingProfitable(VT, NewVT))) {
7757       NewBW = NextPowerOf2(NewBW);
7758       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7759     }
7760     if (NewBW >= BitWidth)
7761       return SDValue();
7762
7763     // If the lsb changed does not start at the type bitwidth boundary,
7764     // start at the previous one.
7765     if (ShAmt % NewBW)
7766       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7767     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7768                                    std::min(BitWidth, ShAmt + NewBW));
7769     if ((Imm & Mask) == Imm) {
7770       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7771       if (Opc == ISD::AND)
7772         NewImm ^= APInt::getAllOnesValue(NewBW);
7773       uint64_t PtrOff = ShAmt / 8;
7774       // For big endian targets, we need to adjust the offset to the pointer to
7775       // load the correct bytes.
7776       if (TLI.isBigEndian())
7777         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7778
7779       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7780       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7781       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7782         return SDValue();
7783
7784       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7785                                    Ptr.getValueType(), Ptr,
7786                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7787       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7788                                   LD->getChain(), NewPtr,
7789                                   LD->getPointerInfo().getWithOffset(PtrOff),
7790                                   LD->isVolatile(), LD->isNonTemporal(),
7791                                   LD->isInvariant(), NewAlign);
7792       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7793                                    DAG.getConstant(NewImm, NewVT));
7794       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7795                                    NewVal, NewPtr,
7796                                    ST->getPointerInfo().getWithOffset(PtrOff),
7797                                    false, false, NewAlign);
7798
7799       AddToWorkList(NewPtr.getNode());
7800       AddToWorkList(NewLD.getNode());
7801       AddToWorkList(NewVal.getNode());
7802       WorkListRemover DeadNodes(*this);
7803       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7804       ++OpsNarrowed;
7805       return NewST;
7806     }
7807   }
7808
7809   return SDValue();
7810 }
7811
7812 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7813 /// if the load value isn't used by any other operations, then consider
7814 /// transforming the pair to integer load / store operations if the target
7815 /// deems the transformation profitable.
7816 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7817   StoreSDNode *ST  = cast<StoreSDNode>(N);
7818   SDValue Chain = ST->getChain();
7819   SDValue Value = ST->getValue();
7820   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7821       Value.hasOneUse() &&
7822       Chain == SDValue(Value.getNode(), 1)) {
7823     LoadSDNode *LD = cast<LoadSDNode>(Value);
7824     EVT VT = LD->getMemoryVT();
7825     if (!VT.isFloatingPoint() ||
7826         VT != ST->getMemoryVT() ||
7827         LD->isNonTemporal() ||
7828         ST->isNonTemporal() ||
7829         LD->getPointerInfo().getAddrSpace() != 0 ||
7830         ST->getPointerInfo().getAddrSpace() != 0)
7831       return SDValue();
7832
7833     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7834     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7835         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7836         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7837         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7838       return SDValue();
7839
7840     unsigned LDAlign = LD->getAlignment();
7841     unsigned STAlign = ST->getAlignment();
7842     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7843     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7844     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7845       return SDValue();
7846
7847     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7848                                 LD->getChain(), LD->getBasePtr(),
7849                                 LD->getPointerInfo(),
7850                                 false, false, false, LDAlign);
7851
7852     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7853                                  NewLD, ST->getBasePtr(),
7854                                  ST->getPointerInfo(),
7855                                  false, false, STAlign);
7856
7857     AddToWorkList(NewLD.getNode());
7858     AddToWorkList(NewST.getNode());
7859     WorkListRemover DeadNodes(*this);
7860     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7861     ++LdStFP2Int;
7862     return NewST;
7863   }
7864
7865   return SDValue();
7866 }
7867
7868 /// Helper struct to parse and store a memory address as base + index + offset.
7869 /// We ignore sign extensions when it is safe to do so.
7870 /// The following two expressions are not equivalent. To differentiate we need
7871 /// to store whether there was a sign extension involved in the index
7872 /// computation.
7873 ///  (load (i64 add (i64 copyfromreg %c)
7874 ///                 (i64 signextend (add (i8 load %index)
7875 ///                                      (i8 1))))
7876 /// vs
7877 ///
7878 /// (load (i64 add (i64 copyfromreg %c)
7879 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7880 ///                                         (i32 1)))))
7881 struct BaseIndexOffset {
7882   SDValue Base;
7883   SDValue Index;
7884   int64_t Offset;
7885   bool IsIndexSignExt;
7886
7887   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7888
7889   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7890                   bool IsIndexSignExt) :
7891     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7892
7893   bool equalBaseIndex(const BaseIndexOffset &Other) {
7894     return Other.Base == Base && Other.Index == Index &&
7895       Other.IsIndexSignExt == IsIndexSignExt;
7896   }
7897
7898   /// Parses tree in Ptr for base, index, offset addresses.
7899   static BaseIndexOffset match(SDValue Ptr) {
7900     bool IsIndexSignExt = false;
7901
7902     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7903     // instruction, then it could be just the BASE or everything else we don't
7904     // know how to handle. Just use Ptr as BASE and give up.
7905     if (Ptr->getOpcode() != ISD::ADD)
7906       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7907
7908     // We know that we have at least an ADD instruction. Try to pattern match
7909     // the simple case of BASE + OFFSET.
7910     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7911       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7912       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7913                               IsIndexSignExt);
7914     }
7915
7916     // Inside a loop the current BASE pointer is calculated using an ADD and a
7917     // MUL instruction. In this case Ptr is the actual BASE pointer.
7918     // (i64 add (i64 %array_ptr)
7919     //          (i64 mul (i64 %induction_var)
7920     //                   (i64 %element_size)))
7921     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7922       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7923
7924     // Look at Base + Index + Offset cases.
7925     SDValue Base = Ptr->getOperand(0);
7926     SDValue IndexOffset = Ptr->getOperand(1);
7927
7928     // Skip signextends.
7929     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7930       IndexOffset = IndexOffset->getOperand(0);
7931       IsIndexSignExt = true;
7932     }
7933
7934     // Either the case of Base + Index (no offset) or something else.
7935     if (IndexOffset->getOpcode() != ISD::ADD)
7936       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7937
7938     // Now we have the case of Base + Index + offset.
7939     SDValue Index = IndexOffset->getOperand(0);
7940     SDValue Offset = IndexOffset->getOperand(1);
7941
7942     if (!isa<ConstantSDNode>(Offset))
7943       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7944
7945     // Ignore signextends.
7946     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7947       Index = Index->getOperand(0);
7948       IsIndexSignExt = true;
7949     } else IsIndexSignExt = false;
7950
7951     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7952     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7953   }
7954 };
7955
7956 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7957 /// is located in a sequence of memory operations connected by a chain.
7958 struct MemOpLink {
7959   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7960     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7961   // Ptr to the mem node.
7962   LSBaseSDNode *MemNode;
7963   // Offset from the base ptr.
7964   int64_t OffsetFromBase;
7965   // What is the sequence number of this mem node.
7966   // Lowest mem operand in the DAG starts at zero.
7967   unsigned SequenceNum;
7968 };
7969
7970 /// Sorts store nodes in a link according to their offset from a shared
7971 // base ptr.
7972 struct ConsecutiveMemoryChainSorter {
7973   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7974     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7975   }
7976 };
7977
7978 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7979   EVT MemVT = St->getMemoryVT();
7980   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7981   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7982     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7983
7984   // Don't merge vectors into wider inputs.
7985   if (MemVT.isVector() || !MemVT.isSimple())
7986     return false;
7987
7988   // Perform an early exit check. Do not bother looking at stored values that
7989   // are not constants or loads.
7990   SDValue StoredVal = St->getValue();
7991   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7992   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7993       !IsLoadSrc)
7994     return false;
7995
7996   // Only look at ends of store sequences.
7997   SDValue Chain = SDValue(St, 1);
7998   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7999     return false;
8000
8001   // This holds the base pointer, index, and the offset in bytes from the base
8002   // pointer.
8003   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8004
8005   // We must have a base and an offset.
8006   if (!BasePtr.Base.getNode())
8007     return false;
8008
8009   // Do not handle stores to undef base pointers.
8010   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8011     return false;
8012
8013   // Save the LoadSDNodes that we find in the chain.
8014   // We need to make sure that these nodes do not interfere with
8015   // any of the store nodes.
8016   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8017
8018   // Save the StoreSDNodes that we find in the chain.
8019   SmallVector<MemOpLink, 8> StoreNodes;
8020
8021   // Walk up the chain and look for nodes with offsets from the same
8022   // base pointer. Stop when reaching an instruction with a different kind
8023   // or instruction which has a different base pointer.
8024   unsigned Seq = 0;
8025   StoreSDNode *Index = St;
8026   while (Index) {
8027     // If the chain has more than one use, then we can't reorder the mem ops.
8028     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8029       break;
8030
8031     // Find the base pointer and offset for this memory node.
8032     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8033
8034     // Check that the base pointer is the same as the original one.
8035     if (!Ptr.equalBaseIndex(BasePtr))
8036       break;
8037
8038     // Check that the alignment is the same.
8039     if (Index->getAlignment() != St->getAlignment())
8040       break;
8041
8042     // The memory operands must not be volatile.
8043     if (Index->isVolatile() || Index->isIndexed())
8044       break;
8045
8046     // No truncation.
8047     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8048       if (St->isTruncatingStore())
8049         break;
8050
8051     // The stored memory type must be the same.
8052     if (Index->getMemoryVT() != MemVT)
8053       break;
8054
8055     // We do not allow unaligned stores because we want to prevent overriding
8056     // stores.
8057     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8058       break;
8059
8060     // We found a potential memory operand to merge.
8061     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8062
8063     // Find the next memory operand in the chain. If the next operand in the
8064     // chain is a store then move up and continue the scan with the next
8065     // memory operand. If the next operand is a load save it and use alias
8066     // information to check if it interferes with anything.
8067     SDNode *NextInChain = Index->getChain().getNode();
8068     while (1) {
8069       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8070         // We found a store node. Use it for the next iteration.
8071         Index = STn;
8072         break;
8073       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8074         // Save the load node for later. Continue the scan.
8075         AliasLoadNodes.push_back(Ldn);
8076         NextInChain = Ldn->getChain().getNode();
8077         continue;
8078       } else {
8079         Index = NULL;
8080         break;
8081       }
8082     }
8083   }
8084
8085   // Check if there is anything to merge.
8086   if (StoreNodes.size() < 2)
8087     return false;
8088
8089   // Sort the memory operands according to their distance from the base pointer.
8090   std::sort(StoreNodes.begin(), StoreNodes.end(),
8091             ConsecutiveMemoryChainSorter());
8092
8093   // Scan the memory operations on the chain and find the first non-consecutive
8094   // store memory address.
8095   unsigned LastConsecutiveStore = 0;
8096   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8097   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8098
8099     // Check that the addresses are consecutive starting from the second
8100     // element in the list of stores.
8101     if (i > 0) {
8102       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8103       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8104         break;
8105     }
8106
8107     bool Alias = false;
8108     // Check if this store interferes with any of the loads that we found.
8109     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8110       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8111         Alias = true;
8112         break;
8113       }
8114     // We found a load that alias with this store. Stop the sequence.
8115     if (Alias)
8116       break;
8117
8118     // Mark this node as useful.
8119     LastConsecutiveStore = i;
8120   }
8121
8122   // The node with the lowest store address.
8123   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8124
8125   // Store the constants into memory as one consecutive store.
8126   if (!IsLoadSrc) {
8127     unsigned LastLegalType = 0;
8128     unsigned LastLegalVectorType = 0;
8129     bool NonZero = false;
8130     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8131       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8132       SDValue StoredVal = St->getValue();
8133
8134       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8135         NonZero |= !C->isNullValue();
8136       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8137         NonZero |= !C->getConstantFPValue()->isNullValue();
8138       } else {
8139         // Non constant.
8140         break;
8141       }
8142
8143       // Find a legal type for the constant store.
8144       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8145       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8146       if (TLI.isTypeLegal(StoreTy))
8147         LastLegalType = i+1;
8148       // Or check whether a truncstore is legal.
8149       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8150                TargetLowering::TypePromoteInteger) {
8151         EVT LegalizedStoredValueTy =
8152           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8153         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8154           LastLegalType = i+1;
8155       }
8156
8157       // Find a legal type for the vector store.
8158       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8159       if (TLI.isTypeLegal(Ty))
8160         LastLegalVectorType = i + 1;
8161     }
8162
8163     // We only use vectors if the constant is known to be zero and the
8164     // function is not marked with the noimplicitfloat attribute.
8165     if (NonZero || NoVectors)
8166       LastLegalVectorType = 0;
8167
8168     // Check if we found a legal integer type to store.
8169     if (LastLegalType == 0 && LastLegalVectorType == 0)
8170       return false;
8171
8172     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8173     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8174
8175     // Make sure we have something to merge.
8176     if (NumElem < 2)
8177       return false;
8178
8179     unsigned EarliestNodeUsed = 0;
8180     for (unsigned i=0; i < NumElem; ++i) {
8181       // Find a chain for the new wide-store operand. Notice that some
8182       // of the store nodes that we found may not be selected for inclusion
8183       // in the wide store. The chain we use needs to be the chain of the
8184       // earliest store node which is *used* and replaced by the wide store.
8185       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8186         EarliestNodeUsed = i;
8187     }
8188
8189     // The earliest Node in the DAG.
8190     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8191     SDLoc DL(StoreNodes[0].MemNode);
8192
8193     SDValue StoredVal;
8194     if (UseVector) {
8195       // Find a legal type for the vector store.
8196       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8197       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8198       StoredVal = DAG.getConstant(0, Ty);
8199     } else {
8200       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8201       APInt StoreInt(StoreBW, 0);
8202
8203       // Construct a single integer constant which is made of the smaller
8204       // constant inputs.
8205       bool IsLE = TLI.isLittleEndian();
8206       for (unsigned i = 0; i < NumElem ; ++i) {
8207         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8208         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8209         SDValue Val = St->getValue();
8210         StoreInt<<=ElementSizeBytes*8;
8211         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8212           StoreInt|=C->getAPIntValue().zext(StoreBW);
8213         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8214           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8215         } else {
8216           assert(false && "Invalid constant element type");
8217         }
8218       }
8219
8220       // Create the new Load and Store operations.
8221       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8222       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8223     }
8224
8225     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8226                                     FirstInChain->getBasePtr(),
8227                                     FirstInChain->getPointerInfo(),
8228                                     false, false,
8229                                     FirstInChain->getAlignment());
8230
8231     // Replace the first store with the new store
8232     CombineTo(EarliestOp, NewStore);
8233     // Erase all other stores.
8234     for (unsigned i = 0; i < NumElem ; ++i) {
8235       if (StoreNodes[i].MemNode == EarliestOp)
8236         continue;
8237       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8238       // ReplaceAllUsesWith will replace all uses that existed when it was
8239       // called, but graph optimizations may cause new ones to appear. For
8240       // example, the case in pr14333 looks like
8241       //
8242       //  St's chain -> St -> another store -> X
8243       //
8244       // And the only difference from St to the other store is the chain.
8245       // When we change it's chain to be St's chain they become identical,
8246       // get CSEed and the net result is that X is now a use of St.
8247       // Since we know that St is redundant, just iterate.
8248       while (!St->use_empty())
8249         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8250       removeFromWorkList(St);
8251       DAG.DeleteNode(St);
8252     }
8253
8254     return true;
8255   }
8256
8257   // Below we handle the case of multiple consecutive stores that
8258   // come from multiple consecutive loads. We merge them into a single
8259   // wide load and a single wide store.
8260
8261   // Look for load nodes which are used by the stored values.
8262   SmallVector<MemOpLink, 8> LoadNodes;
8263
8264   // Find acceptable loads. Loads need to have the same chain (token factor),
8265   // must not be zext, volatile, indexed, and they must be consecutive.
8266   BaseIndexOffset LdBasePtr;
8267   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8268     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8269     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8270     if (!Ld) break;
8271
8272     // Loads must only have one use.
8273     if (!Ld->hasNUsesOfValue(1, 0))
8274       break;
8275
8276     // Check that the alignment is the same as the stores.
8277     if (Ld->getAlignment() != St->getAlignment())
8278       break;
8279
8280     // The memory operands must not be volatile.
8281     if (Ld->isVolatile() || Ld->isIndexed())
8282       break;
8283
8284     // We do not accept ext loads.
8285     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8286       break;
8287
8288     // The stored memory type must be the same.
8289     if (Ld->getMemoryVT() != MemVT)
8290       break;
8291
8292     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8293     // If this is not the first ptr that we check.
8294     if (LdBasePtr.Base.getNode()) {
8295       // The base ptr must be the same.
8296       if (!LdPtr.equalBaseIndex(LdBasePtr))
8297         break;
8298     } else {
8299       // Check that all other base pointers are the same as this one.
8300       LdBasePtr = LdPtr;
8301     }
8302
8303     // We found a potential memory operand to merge.
8304     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8305   }
8306
8307   if (LoadNodes.size() < 2)
8308     return false;
8309
8310   // Scan the memory operations on the chain and find the first non-consecutive
8311   // load memory address. These variables hold the index in the store node
8312   // array.
8313   unsigned LastConsecutiveLoad = 0;
8314   // This variable refers to the size and not index in the array.
8315   unsigned LastLegalVectorType = 0;
8316   unsigned LastLegalIntegerType = 0;
8317   StartAddress = LoadNodes[0].OffsetFromBase;
8318   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8319   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8320     // All loads much share the same chain.
8321     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8322       break;
8323
8324     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8325     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8326       break;
8327     LastConsecutiveLoad = i;
8328
8329     // Find a legal type for the vector store.
8330     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8331     if (TLI.isTypeLegal(StoreTy))
8332       LastLegalVectorType = i + 1;
8333
8334     // Find a legal type for the integer store.
8335     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8336     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8337     if (TLI.isTypeLegal(StoreTy))
8338       LastLegalIntegerType = i + 1;
8339     // Or check whether a truncstore and extload is legal.
8340     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8341              TargetLowering::TypePromoteInteger) {
8342       EVT LegalizedStoredValueTy =
8343         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8344       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8345           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8346           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8347           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8348         LastLegalIntegerType = i+1;
8349     }
8350   }
8351
8352   // Only use vector types if the vector type is larger than the integer type.
8353   // If they are the same, use integers.
8354   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8355   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8356
8357   // We add +1 here because the LastXXX variables refer to location while
8358   // the NumElem refers to array/index size.
8359   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8360   NumElem = std::min(LastLegalType, NumElem);
8361
8362   if (NumElem < 2)
8363     return false;
8364
8365   // The earliest Node in the DAG.
8366   unsigned EarliestNodeUsed = 0;
8367   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8368   for (unsigned i=1; i<NumElem; ++i) {
8369     // Find a chain for the new wide-store operand. Notice that some
8370     // of the store nodes that we found may not be selected for inclusion
8371     // in the wide store. The chain we use needs to be the chain of the
8372     // earliest store node which is *used* and replaced by the wide store.
8373     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8374       EarliestNodeUsed = i;
8375   }
8376
8377   // Find if it is better to use vectors or integers to load and store
8378   // to memory.
8379   EVT JointMemOpVT;
8380   if (UseVectorTy) {
8381     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8382   } else {
8383     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8384     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8385   }
8386
8387   SDLoc LoadDL(LoadNodes[0].MemNode);
8388   SDLoc StoreDL(StoreNodes[0].MemNode);
8389
8390   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8391   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8392                                 FirstLoad->getChain(),
8393                                 FirstLoad->getBasePtr(),
8394                                 FirstLoad->getPointerInfo(),
8395                                 false, false, false,
8396                                 FirstLoad->getAlignment());
8397
8398   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8399                                   FirstInChain->getBasePtr(),
8400                                   FirstInChain->getPointerInfo(), false, false,
8401                                   FirstInChain->getAlignment());
8402
8403   // Replace one of the loads with the new load.
8404   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8405   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8406                                 SDValue(NewLoad.getNode(), 1));
8407
8408   // Remove the rest of the load chains.
8409   for (unsigned i = 1; i < NumElem ; ++i) {
8410     // Replace all chain users of the old load nodes with the chain of the new
8411     // load node.
8412     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8413     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8414   }
8415
8416   // Replace the first store with the new store.
8417   CombineTo(EarliestOp, NewStore);
8418   // Erase all other stores.
8419   for (unsigned i = 0; i < NumElem ; ++i) {
8420     // Remove all Store nodes.
8421     if (StoreNodes[i].MemNode == EarliestOp)
8422       continue;
8423     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8424     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8425     removeFromWorkList(St);
8426     DAG.DeleteNode(St);
8427   }
8428
8429   return true;
8430 }
8431
8432 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8433   StoreSDNode *ST  = cast<StoreSDNode>(N);
8434   SDValue Chain = ST->getChain();
8435   SDValue Value = ST->getValue();
8436   SDValue Ptr   = ST->getBasePtr();
8437
8438   // If this is a store of a bit convert, store the input value if the
8439   // resultant store does not need a higher alignment than the original.
8440   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8441       ST->isUnindexed()) {
8442     unsigned OrigAlign = ST->getAlignment();
8443     EVT SVT = Value.getOperand(0).getValueType();
8444     unsigned Align = TLI.getDataLayout()->
8445       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8446     if (Align <= OrigAlign &&
8447         ((!LegalOperations && !ST->isVolatile()) ||
8448          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8449       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8450                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8451                           ST->isNonTemporal(), OrigAlign);
8452   }
8453
8454   // Turn 'store undef, Ptr' -> nothing.
8455   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8456     return Chain;
8457
8458   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8459   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8460     // NOTE: If the original store is volatile, this transform must not increase
8461     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8462     // processor operation but an i64 (which is not legal) requires two.  So the
8463     // transform should not be done in this case.
8464     if (Value.getOpcode() != ISD::TargetConstantFP) {
8465       SDValue Tmp;
8466       switch (CFP->getSimpleValueType(0).SimpleTy) {
8467       default: llvm_unreachable("Unknown FP type");
8468       case MVT::f16:    // We don't do this for these yet.
8469       case MVT::f80:
8470       case MVT::f128:
8471       case MVT::ppcf128:
8472         break;
8473       case MVT::f32:
8474         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8475             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8476           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8477                               bitcastToAPInt().getZExtValue(), MVT::i32);
8478           return DAG.getStore(Chain, SDLoc(N), Tmp,
8479                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8480                               ST->isNonTemporal(), ST->getAlignment());
8481         }
8482         break;
8483       case MVT::f64:
8484         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8485              !ST->isVolatile()) ||
8486             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8487           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8488                                 getZExtValue(), MVT::i64);
8489           return DAG.getStore(Chain, SDLoc(N), Tmp,
8490                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8491                               ST->isNonTemporal(), ST->getAlignment());
8492         }
8493
8494         if (!ST->isVolatile() &&
8495             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8496           // Many FP stores are not made apparent until after legalize, e.g. for
8497           // argument passing.  Since this is so common, custom legalize the
8498           // 64-bit integer store into two 32-bit stores.
8499           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8500           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8501           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8502           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8503
8504           unsigned Alignment = ST->getAlignment();
8505           bool isVolatile = ST->isVolatile();
8506           bool isNonTemporal = ST->isNonTemporal();
8507
8508           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8509                                      Ptr, ST->getPointerInfo(),
8510                                      isVolatile, isNonTemporal,
8511                                      ST->getAlignment());
8512           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8513                             DAG.getConstant(4, Ptr.getValueType()));
8514           Alignment = MinAlign(Alignment, 4U);
8515           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8516                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8517                                      isVolatile, isNonTemporal,
8518                                      Alignment);
8519           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8520                              St0, St1);
8521         }
8522
8523         break;
8524       }
8525     }
8526   }
8527
8528   // Try to infer better alignment information than the store already has.
8529   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8530     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8531       if (Align > ST->getAlignment())
8532         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8533                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8534                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8535     }
8536   }
8537
8538   // Try transforming a pair floating point load / store ops to integer
8539   // load / store ops.
8540   SDValue NewST = TransformFPLoadStorePair(N);
8541   if (NewST.getNode())
8542     return NewST;
8543
8544   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8545     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8546   if (UseAA) {
8547     // Walk up chain skipping non-aliasing memory nodes.
8548     SDValue BetterChain = FindBetterChain(N, Chain);
8549
8550     // If there is a better chain.
8551     if (Chain != BetterChain) {
8552       SDValue ReplStore;
8553
8554       // Replace the chain to avoid dependency.
8555       if (ST->isTruncatingStore()) {
8556         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8557                                       ST->getPointerInfo(),
8558                                       ST->getMemoryVT(), ST->isVolatile(),
8559                                       ST->isNonTemporal(), ST->getAlignment());
8560       } else {
8561         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8562                                  ST->getPointerInfo(),
8563                                  ST->isVolatile(), ST->isNonTemporal(),
8564                                  ST->getAlignment());
8565       }
8566
8567       // Create token to keep both nodes around.
8568       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8569                                   MVT::Other, Chain, ReplStore);
8570
8571       // Make sure the new and old chains are cleaned up.
8572       AddToWorkList(Token.getNode());
8573
8574       // Don't add users to work list.
8575       return CombineTo(N, Token, false);
8576     }
8577   }
8578
8579   // Try transforming N to an indexed store.
8580   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8581     return SDValue(N, 0);
8582
8583   // FIXME: is there such a thing as a truncating indexed store?
8584   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8585       Value.getValueType().isInteger()) {
8586     // See if we can simplify the input to this truncstore with knowledge that
8587     // only the low bits are being used.  For example:
8588     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8589     SDValue Shorter =
8590       GetDemandedBits(Value,
8591                       APInt::getLowBitsSet(
8592                         Value.getValueType().getScalarType().getSizeInBits(),
8593                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8594     AddToWorkList(Value.getNode());
8595     if (Shorter.getNode())
8596       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8597                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8598                                ST->isVolatile(), ST->isNonTemporal(),
8599                                ST->getAlignment());
8600
8601     // Otherwise, see if we can simplify the operation with
8602     // SimplifyDemandedBits, which only works if the value has a single use.
8603     if (SimplifyDemandedBits(Value,
8604                         APInt::getLowBitsSet(
8605                           Value.getValueType().getScalarType().getSizeInBits(),
8606                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8607       return SDValue(N, 0);
8608   }
8609
8610   // If this is a load followed by a store to the same location, then the store
8611   // is dead/noop.
8612   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8613     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8614         ST->isUnindexed() && !ST->isVolatile() &&
8615         // There can't be any side effects between the load and store, such as
8616         // a call or store.
8617         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8618       // The store is dead, remove it.
8619       return Chain;
8620     }
8621   }
8622
8623   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8624   // truncating store.  We can do this even if this is already a truncstore.
8625   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8626       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8627       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8628                             ST->getMemoryVT())) {
8629     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8630                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8631                              ST->isVolatile(), ST->isNonTemporal(),
8632                              ST->getAlignment());
8633   }
8634
8635   // Only perform this optimization before the types are legal, because we
8636   // don't want to perform this optimization on every DAGCombine invocation.
8637   if (!LegalTypes) {
8638     bool EverChanged = false;
8639
8640     do {
8641       // There can be multiple store sequences on the same chain.
8642       // Keep trying to merge store sequences until we are unable to do so
8643       // or until we merge the last store on the chain.
8644       bool Changed = MergeConsecutiveStores(ST);
8645       EverChanged |= Changed;
8646       if (!Changed) break;
8647     } while (ST->getOpcode() != ISD::DELETED_NODE);
8648
8649     if (EverChanged)
8650       return SDValue(N, 0);
8651   }
8652
8653   return ReduceLoadOpStoreWidth(N);
8654 }
8655
8656 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8657   SDValue InVec = N->getOperand(0);
8658   SDValue InVal = N->getOperand(1);
8659   SDValue EltNo = N->getOperand(2);
8660   SDLoc dl(N);
8661
8662   // If the inserted element is an UNDEF, just use the input vector.
8663   if (InVal.getOpcode() == ISD::UNDEF)
8664     return InVec;
8665
8666   EVT VT = InVec.getValueType();
8667
8668   // If we can't generate a legal BUILD_VECTOR, exit
8669   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8670     return SDValue();
8671
8672   // Check that we know which element is being inserted
8673   if (!isa<ConstantSDNode>(EltNo))
8674     return SDValue();
8675   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8676
8677   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8678   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8679   // vector elements.
8680   SmallVector<SDValue, 8> Ops;
8681   // Do not combine these two vectors if the output vector will not replace
8682   // the input vector.
8683   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8684     Ops.append(InVec.getNode()->op_begin(),
8685                InVec.getNode()->op_end());
8686   } else if (InVec.getOpcode() == ISD::UNDEF) {
8687     unsigned NElts = VT.getVectorNumElements();
8688     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8689   } else {
8690     return SDValue();
8691   }
8692
8693   // Insert the element
8694   if (Elt < Ops.size()) {
8695     // All the operands of BUILD_VECTOR must have the same type;
8696     // we enforce that here.
8697     EVT OpVT = Ops[0].getValueType();
8698     if (InVal.getValueType() != OpVT)
8699       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8700                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8701                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8702     Ops[Elt] = InVal;
8703   }
8704
8705   // Return the new vector
8706   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8707                      VT, &Ops[0], Ops.size());
8708 }
8709
8710 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8711   // (vextract (scalar_to_vector val, 0) -> val
8712   SDValue InVec = N->getOperand(0);
8713   EVT VT = InVec.getValueType();
8714   EVT NVT = N->getValueType(0);
8715
8716   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8717     // Check if the result type doesn't match the inserted element type. A
8718     // SCALAR_TO_VECTOR may truncate the inserted element and the
8719     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8720     SDValue InOp = InVec.getOperand(0);
8721     if (InOp.getValueType() != NVT) {
8722       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8723       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8724     }
8725     return InOp;
8726   }
8727
8728   SDValue EltNo = N->getOperand(1);
8729   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8730
8731   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8732   // We only perform this optimization before the op legalization phase because
8733   // we may introduce new vector instructions which are not backed by TD
8734   // patterns. For example on AVX, extracting elements from a wide vector
8735   // without using extract_subvector.
8736   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8737       && ConstEltNo && !LegalOperations) {
8738     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8739     int NumElem = VT.getVectorNumElements();
8740     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8741     // Find the new index to extract from.
8742     int OrigElt = SVOp->getMaskElt(Elt);
8743
8744     // Extracting an undef index is undef.
8745     if (OrigElt == -1)
8746       return DAG.getUNDEF(NVT);
8747
8748     // Select the right vector half to extract from.
8749     if (OrigElt < NumElem) {
8750       InVec = InVec->getOperand(0);
8751     } else {
8752       InVec = InVec->getOperand(1);
8753       OrigElt -= NumElem;
8754     }
8755
8756     EVT IndexTy = TLI.getVectorIdxTy();
8757     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8758                        InVec, DAG.getConstant(OrigElt, IndexTy));
8759   }
8760
8761   // Perform only after legalization to ensure build_vector / vector_shuffle
8762   // optimizations have already been done.
8763   if (!LegalOperations) return SDValue();
8764
8765   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8766   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8767   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8768
8769   if (ConstEltNo) {
8770     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8771     bool NewLoad = false;
8772     bool BCNumEltsChanged = false;
8773     EVT ExtVT = VT.getVectorElementType();
8774     EVT LVT = ExtVT;
8775
8776     // If the result of load has to be truncated, then it's not necessarily
8777     // profitable.
8778     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8779       return SDValue();
8780
8781     if (InVec.getOpcode() == ISD::BITCAST) {
8782       // Don't duplicate a load with other uses.
8783       if (!InVec.hasOneUse())
8784         return SDValue();
8785
8786       EVT BCVT = InVec.getOperand(0).getValueType();
8787       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8788         return SDValue();
8789       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8790         BCNumEltsChanged = true;
8791       InVec = InVec.getOperand(0);
8792       ExtVT = BCVT.getVectorElementType();
8793       NewLoad = true;
8794     }
8795
8796     LoadSDNode *LN0 = NULL;
8797     const ShuffleVectorSDNode *SVN = NULL;
8798     if (ISD::isNormalLoad(InVec.getNode())) {
8799       LN0 = cast<LoadSDNode>(InVec);
8800     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8801                InVec.getOperand(0).getValueType() == ExtVT &&
8802                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8803       // Don't duplicate a load with other uses.
8804       if (!InVec.hasOneUse())
8805         return SDValue();
8806
8807       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8808     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8809       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8810       // =>
8811       // (load $addr+1*size)
8812
8813       // Don't duplicate a load with other uses.
8814       if (!InVec.hasOneUse())
8815         return SDValue();
8816
8817       // If the bit convert changed the number of elements, it is unsafe
8818       // to examine the mask.
8819       if (BCNumEltsChanged)
8820         return SDValue();
8821
8822       // Select the input vector, guarding against out of range extract vector.
8823       unsigned NumElems = VT.getVectorNumElements();
8824       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8825       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8826
8827       if (InVec.getOpcode() == ISD::BITCAST) {
8828         // Don't duplicate a load with other uses.
8829         if (!InVec.hasOneUse())
8830           return SDValue();
8831
8832         InVec = InVec.getOperand(0);
8833       }
8834       if (ISD::isNormalLoad(InVec.getNode())) {
8835         LN0 = cast<LoadSDNode>(InVec);
8836         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8837       }
8838     }
8839
8840     // Make sure we found a non-volatile load and the extractelement is
8841     // the only use.
8842     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8843       return SDValue();
8844
8845     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8846     if (Elt == -1)
8847       return DAG.getUNDEF(LVT);
8848
8849     unsigned Align = LN0->getAlignment();
8850     if (NewLoad) {
8851       // Check the resultant load doesn't need a higher alignment than the
8852       // original load.
8853       unsigned NewAlign =
8854         TLI.getDataLayout()
8855             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8856
8857       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8858         return SDValue();
8859
8860       Align = NewAlign;
8861     }
8862
8863     SDValue NewPtr = LN0->getBasePtr();
8864     unsigned PtrOff = 0;
8865
8866     if (Elt) {
8867       PtrOff = LVT.getSizeInBits() * Elt / 8;
8868       EVT PtrType = NewPtr.getValueType();
8869       if (TLI.isBigEndian())
8870         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8871       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8872                            DAG.getConstant(PtrOff, PtrType));
8873     }
8874
8875     // The replacement we need to do here is a little tricky: we need to
8876     // replace an extractelement of a load with a load.
8877     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8878     // Note that this replacement assumes that the extractvalue is the only
8879     // use of the load; that's okay because we don't want to perform this
8880     // transformation in other cases anyway.
8881     SDValue Load;
8882     SDValue Chain;
8883     if (NVT.bitsGT(LVT)) {
8884       // If the result type of vextract is wider than the load, then issue an
8885       // extending load instead.
8886       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8887         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8888       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8889                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8890                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8891       Chain = Load.getValue(1);
8892     } else {
8893       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8894                          LN0->getPointerInfo().getWithOffset(PtrOff),
8895                          LN0->isVolatile(), LN0->isNonTemporal(),
8896                          LN0->isInvariant(), Align);
8897       Chain = Load.getValue(1);
8898       if (NVT.bitsLT(LVT))
8899         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8900       else
8901         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8902     }
8903     WorkListRemover DeadNodes(*this);
8904     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8905     SDValue To[] = { Load, Chain };
8906     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8907     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8908     // worklist explicitly as well.
8909     AddToWorkList(Load.getNode());
8910     AddUsersToWorkList(Load.getNode()); // Add users too
8911     // Make sure to revisit this node to clean it up; it will usually be dead.
8912     AddToWorkList(N);
8913     return SDValue(N, 0);
8914   }
8915
8916   return SDValue();
8917 }
8918
8919 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8920 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8921   // We perform this optimization post type-legalization because
8922   // the type-legalizer often scalarizes integer-promoted vectors.
8923   // Performing this optimization before may create bit-casts which
8924   // will be type-legalized to complex code sequences.
8925   // We perform this optimization only before the operation legalizer because we
8926   // may introduce illegal operations.
8927   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8928     return SDValue();
8929
8930   unsigned NumInScalars = N->getNumOperands();
8931   SDLoc dl(N);
8932   EVT VT = N->getValueType(0);
8933
8934   // Check to see if this is a BUILD_VECTOR of a bunch of values
8935   // which come from any_extend or zero_extend nodes. If so, we can create
8936   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8937   // optimizations. We do not handle sign-extend because we can't fill the sign
8938   // using shuffles.
8939   EVT SourceType = MVT::Other;
8940   bool AllAnyExt = true;
8941
8942   for (unsigned i = 0; i != NumInScalars; ++i) {
8943     SDValue In = N->getOperand(i);
8944     // Ignore undef inputs.
8945     if (In.getOpcode() == ISD::UNDEF) continue;
8946
8947     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8948     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8949
8950     // Abort if the element is not an extension.
8951     if (!ZeroExt && !AnyExt) {
8952       SourceType = MVT::Other;
8953       break;
8954     }
8955
8956     // The input is a ZeroExt or AnyExt. Check the original type.
8957     EVT InTy = In.getOperand(0).getValueType();
8958
8959     // Check that all of the widened source types are the same.
8960     if (SourceType == MVT::Other)
8961       // First time.
8962       SourceType = InTy;
8963     else if (InTy != SourceType) {
8964       // Multiple income types. Abort.
8965       SourceType = MVT::Other;
8966       break;
8967     }
8968
8969     // Check if all of the extends are ANY_EXTENDs.
8970     AllAnyExt &= AnyExt;
8971   }
8972
8973   // In order to have valid types, all of the inputs must be extended from the
8974   // same source type and all of the inputs must be any or zero extend.
8975   // Scalar sizes must be a power of two.
8976   EVT OutScalarTy = VT.getScalarType();
8977   bool ValidTypes = SourceType != MVT::Other &&
8978                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8979                  isPowerOf2_32(SourceType.getSizeInBits());
8980
8981   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8982   // turn into a single shuffle instruction.
8983   if (!ValidTypes)
8984     return SDValue();
8985
8986   bool isLE = TLI.isLittleEndian();
8987   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8988   assert(ElemRatio > 1 && "Invalid element size ratio");
8989   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8990                                DAG.getConstant(0, SourceType);
8991
8992   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8993   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8994
8995   // Populate the new build_vector
8996   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8997     SDValue Cast = N->getOperand(i);
8998     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8999             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9000             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9001     SDValue In;
9002     if (Cast.getOpcode() == ISD::UNDEF)
9003       In = DAG.getUNDEF(SourceType);
9004     else
9005       In = Cast->getOperand(0);
9006     unsigned Index = isLE ? (i * ElemRatio) :
9007                             (i * ElemRatio + (ElemRatio - 1));
9008
9009     assert(Index < Ops.size() && "Invalid index");
9010     Ops[Index] = In;
9011   }
9012
9013   // The type of the new BUILD_VECTOR node.
9014   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9015   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9016          "Invalid vector size");
9017   // Check if the new vector type is legal.
9018   if (!isTypeLegal(VecVT)) return SDValue();
9019
9020   // Make the new BUILD_VECTOR.
9021   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9022
9023   // The new BUILD_VECTOR node has the potential to be further optimized.
9024   AddToWorkList(BV.getNode());
9025   // Bitcast to the desired type.
9026   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9027 }
9028
9029 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9030   EVT VT = N->getValueType(0);
9031
9032   unsigned NumInScalars = N->getNumOperands();
9033   SDLoc dl(N);
9034
9035   EVT SrcVT = MVT::Other;
9036   unsigned Opcode = ISD::DELETED_NODE;
9037   unsigned NumDefs = 0;
9038
9039   for (unsigned i = 0; i != NumInScalars; ++i) {
9040     SDValue In = N->getOperand(i);
9041     unsigned Opc = In.getOpcode();
9042
9043     if (Opc == ISD::UNDEF)
9044       continue;
9045
9046     // If all scalar values are floats and converted from integers.
9047     if (Opcode == ISD::DELETED_NODE &&
9048         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9049       Opcode = Opc;
9050     }
9051
9052     if (Opc != Opcode)
9053       return SDValue();
9054
9055     EVT InVT = In.getOperand(0).getValueType();
9056
9057     // If all scalar values are typed differently, bail out. It's chosen to
9058     // simplify BUILD_VECTOR of integer types.
9059     if (SrcVT == MVT::Other)
9060       SrcVT = InVT;
9061     if (SrcVT != InVT)
9062       return SDValue();
9063     NumDefs++;
9064   }
9065
9066   // If the vector has just one element defined, it's not worth to fold it into
9067   // a vectorized one.
9068   if (NumDefs < 2)
9069     return SDValue();
9070
9071   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9072          && "Should only handle conversion from integer to float.");
9073   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9074
9075   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9076
9077   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9078     return SDValue();
9079
9080   SmallVector<SDValue, 8> Opnds;
9081   for (unsigned i = 0; i != NumInScalars; ++i) {
9082     SDValue In = N->getOperand(i);
9083
9084     if (In.getOpcode() == ISD::UNDEF)
9085       Opnds.push_back(DAG.getUNDEF(SrcVT));
9086     else
9087       Opnds.push_back(In.getOperand(0));
9088   }
9089   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9090                            &Opnds[0], Opnds.size());
9091   AddToWorkList(BV.getNode());
9092
9093   return DAG.getNode(Opcode, dl, VT, BV);
9094 }
9095
9096 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9097   unsigned NumInScalars = N->getNumOperands();
9098   SDLoc dl(N);
9099   EVT VT = N->getValueType(0);
9100
9101   // A vector built entirely of undefs is undef.
9102   if (ISD::allOperandsUndef(N))
9103     return DAG.getUNDEF(VT);
9104
9105   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9106   if (V.getNode())
9107     return V;
9108
9109   V = reduceBuildVecConvertToConvertBuildVec(N);
9110   if (V.getNode())
9111     return V;
9112
9113   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9114   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9115   // at most two distinct vectors, turn this into a shuffle node.
9116
9117   // May only combine to shuffle after legalize if shuffle is legal.
9118   if (LegalOperations &&
9119       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9120     return SDValue();
9121
9122   SDValue VecIn1, VecIn2;
9123   for (unsigned i = 0; i != NumInScalars; ++i) {
9124     // Ignore undef inputs.
9125     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9126
9127     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9128     // constant index, bail out.
9129     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9130         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9131       VecIn1 = VecIn2 = SDValue(0, 0);
9132       break;
9133     }
9134
9135     // We allow up to two distinct input vectors.
9136     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9137     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9138       continue;
9139
9140     if (VecIn1.getNode() == 0) {
9141       VecIn1 = ExtractedFromVec;
9142     } else if (VecIn2.getNode() == 0) {
9143       VecIn2 = ExtractedFromVec;
9144     } else {
9145       // Too many inputs.
9146       VecIn1 = VecIn2 = SDValue(0, 0);
9147       break;
9148     }
9149   }
9150
9151     // If everything is good, we can make a shuffle operation.
9152   if (VecIn1.getNode()) {
9153     SmallVector<int, 8> Mask;
9154     for (unsigned i = 0; i != NumInScalars; ++i) {
9155       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9156         Mask.push_back(-1);
9157         continue;
9158       }
9159
9160       // If extracting from the first vector, just use the index directly.
9161       SDValue Extract = N->getOperand(i);
9162       SDValue ExtVal = Extract.getOperand(1);
9163       if (Extract.getOperand(0) == VecIn1) {
9164         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9165         if (ExtIndex > VT.getVectorNumElements())
9166           return SDValue();
9167
9168         Mask.push_back(ExtIndex);
9169         continue;
9170       }
9171
9172       // Otherwise, use InIdx + VecSize
9173       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9174       Mask.push_back(Idx+NumInScalars);
9175     }
9176
9177     // We can't generate a shuffle node with mismatched input and output types.
9178     // Attempt to transform a single input vector to the correct type.
9179     if ((VT != VecIn1.getValueType())) {
9180       // We don't support shuffeling between TWO values of different types.
9181       if (VecIn2.getNode() != 0)
9182         return SDValue();
9183
9184       // We only support widening of vectors which are half the size of the
9185       // output registers. For example XMM->YMM widening on X86 with AVX.
9186       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9187         return SDValue();
9188
9189       // If the input vector type has a different base type to the output
9190       // vector type, bail out.
9191       if (VecIn1.getValueType().getVectorElementType() !=
9192           VT.getVectorElementType())
9193         return SDValue();
9194
9195       // Widen the input vector by adding undef values.
9196       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9197                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9198     }
9199
9200     // If VecIn2 is unused then change it to undef.
9201     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9202
9203     // Check that we were able to transform all incoming values to the same
9204     // type.
9205     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9206         VecIn1.getValueType() != VT)
9207           return SDValue();
9208
9209     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9210     if (!isTypeLegal(VT))
9211       return SDValue();
9212
9213     // Return the new VECTOR_SHUFFLE node.
9214     SDValue Ops[2];
9215     Ops[0] = VecIn1;
9216     Ops[1] = VecIn2;
9217     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9218   }
9219
9220   return SDValue();
9221 }
9222
9223 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9224   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9225   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9226   // inputs come from at most two distinct vectors, turn this into a shuffle
9227   // node.
9228
9229   // If we only have one input vector, we don't need to do any concatenation.
9230   if (N->getNumOperands() == 1)
9231     return N->getOperand(0);
9232
9233   // Check if all of the operands are undefs.
9234   if (ISD::allOperandsUndef(N))
9235     return DAG.getUNDEF(N->getValueType(0));
9236
9237   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9238   // nodes often generate nop CONCAT_VECTOR nodes.
9239   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9240   // place the incoming vectors at the exact same location.
9241   SDValue SingleSource = SDValue();
9242   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9243
9244   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9245     SDValue Op = N->getOperand(i);
9246
9247     if (Op.getOpcode() == ISD::UNDEF)
9248       continue;
9249
9250     // Check if this is the identity extract:
9251     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9252       return SDValue();
9253
9254     // Find the single incoming vector for the extract_subvector.
9255     if (SingleSource.getNode()) {
9256       if (Op.getOperand(0) != SingleSource)
9257         return SDValue();
9258     } else {
9259       SingleSource = Op.getOperand(0);
9260
9261       // Check the source type is the same as the type of the result.
9262       // If not, this concat may extend the vector, so we can not
9263       // optimize it away.
9264       if (SingleSource.getValueType() != N->getValueType(0))
9265         return SDValue();
9266     }
9267
9268     unsigned IdentityIndex = i * PartNumElem;
9269     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9270     // The extract index must be constant.
9271     if (!CS)
9272       return SDValue();
9273
9274     // Check that we are reading from the identity index.
9275     if (CS->getZExtValue() != IdentityIndex)
9276       return SDValue();
9277   }
9278
9279   if (SingleSource.getNode())
9280     return SingleSource;
9281
9282   return SDValue();
9283 }
9284
9285 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9286   EVT NVT = N->getValueType(0);
9287   SDValue V = N->getOperand(0);
9288
9289   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9290     // Combine:
9291     //    (extract_subvec (concat V1, V2, ...), i)
9292     // Into:
9293     //    Vi if possible
9294     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9295     if (V->getOperand(0).getValueType() != NVT)
9296       return SDValue();
9297     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9298     unsigned NumElems = NVT.getVectorNumElements();
9299     assert((Idx % NumElems) == 0 &&
9300            "IDX in concat is not a multiple of the result vector length.");
9301     return V->getOperand(Idx / NumElems);
9302   }
9303
9304   // Skip bitcasting
9305   if (V->getOpcode() == ISD::BITCAST)
9306     V = V.getOperand(0);
9307
9308   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9309     SDLoc dl(N);
9310     // Handle only simple case where vector being inserted and vector
9311     // being extracted are of same type, and are half size of larger vectors.
9312     EVT BigVT = V->getOperand(0).getValueType();
9313     EVT SmallVT = V->getOperand(1).getValueType();
9314     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9315       return SDValue();
9316
9317     // Only handle cases where both indexes are constants with the same type.
9318     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9319     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9320
9321     if (InsIdx && ExtIdx &&
9322         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9323         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9324       // Combine:
9325       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9326       // Into:
9327       //    indices are equal or bit offsets are equal => V1
9328       //    otherwise => (extract_subvec V1, ExtIdx)
9329       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9330           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9331         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9332       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9333                          DAG.getNode(ISD::BITCAST, dl,
9334                                      N->getOperand(0).getValueType(),
9335                                      V->getOperand(0)), N->getOperand(1));
9336     }
9337   }
9338
9339   return SDValue();
9340 }
9341
9342 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9343 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9344   EVT VT = N->getValueType(0);
9345   unsigned NumElts = VT.getVectorNumElements();
9346
9347   SDValue N0 = N->getOperand(0);
9348   SDValue N1 = N->getOperand(1);
9349   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9350
9351   SmallVector<SDValue, 4> Ops;
9352   EVT ConcatVT = N0.getOperand(0).getValueType();
9353   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9354   unsigned NumConcats = NumElts / NumElemsPerConcat;
9355
9356   // Look at every vector that's inserted. We're looking for exact
9357   // subvector-sized copies from a concatenated vector
9358   for (unsigned I = 0; I != NumConcats; ++I) {
9359     // Make sure we're dealing with a copy.
9360     unsigned Begin = I * NumElemsPerConcat;
9361     bool AllUndef = true, NoUndef = true;
9362     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9363       if (SVN->getMaskElt(J) >= 0)
9364         AllUndef = false;
9365       else
9366         NoUndef = false;
9367     }
9368
9369     if (NoUndef) {
9370       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9371         return SDValue();
9372
9373       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9374         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9375           return SDValue();
9376
9377       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9378       if (FirstElt < N0.getNumOperands())
9379         Ops.push_back(N0.getOperand(FirstElt));
9380       else
9381         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9382
9383     } else if (AllUndef) {
9384       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9385     } else { // Mixed with general masks and undefs, can't do optimization.
9386       return SDValue();
9387     }
9388   }
9389
9390   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9391                      Ops.size());
9392 }
9393
9394 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9395   EVT VT = N->getValueType(0);
9396   unsigned NumElts = VT.getVectorNumElements();
9397
9398   SDValue N0 = N->getOperand(0);
9399   SDValue N1 = N->getOperand(1);
9400
9401   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9402
9403   // Canonicalize shuffle undef, undef -> undef
9404   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9405     return DAG.getUNDEF(VT);
9406
9407   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9408
9409   // Canonicalize shuffle v, v -> v, undef
9410   if (N0 == N1) {
9411     SmallVector<int, 8> NewMask;
9412     for (unsigned i = 0; i != NumElts; ++i) {
9413       int Idx = SVN->getMaskElt(i);
9414       if (Idx >= (int)NumElts) Idx -= NumElts;
9415       NewMask.push_back(Idx);
9416     }
9417     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9418                                 &NewMask[0]);
9419   }
9420
9421   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9422   if (N0.getOpcode() == ISD::UNDEF) {
9423     SmallVector<int, 8> NewMask;
9424     for (unsigned i = 0; i != NumElts; ++i) {
9425       int Idx = SVN->getMaskElt(i);
9426       if (Idx >= 0) {
9427         if (Idx >= (int)NumElts)
9428           Idx -= NumElts;
9429         else
9430           Idx = -1; // remove reference to lhs
9431       }
9432       NewMask.push_back(Idx);
9433     }
9434     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9435                                 &NewMask[0]);
9436   }
9437
9438   // Remove references to rhs if it is undef
9439   if (N1.getOpcode() == ISD::UNDEF) {
9440     bool Changed = false;
9441     SmallVector<int, 8> NewMask;
9442     for (unsigned i = 0; i != NumElts; ++i) {
9443       int Idx = SVN->getMaskElt(i);
9444       if (Idx >= (int)NumElts) {
9445         Idx = -1;
9446         Changed = true;
9447       }
9448       NewMask.push_back(Idx);
9449     }
9450     if (Changed)
9451       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9452   }
9453
9454   // If it is a splat, check if the argument vector is another splat or a
9455   // build_vector with all scalar elements the same.
9456   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9457     SDNode *V = N0.getNode();
9458
9459     // If this is a bit convert that changes the element type of the vector but
9460     // not the number of vector elements, look through it.  Be careful not to
9461     // look though conversions that change things like v4f32 to v2f64.
9462     if (V->getOpcode() == ISD::BITCAST) {
9463       SDValue ConvInput = V->getOperand(0);
9464       if (ConvInput.getValueType().isVector() &&
9465           ConvInput.getValueType().getVectorNumElements() == NumElts)
9466         V = ConvInput.getNode();
9467     }
9468
9469     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9470       assert(V->getNumOperands() == NumElts &&
9471              "BUILD_VECTOR has wrong number of operands");
9472       SDValue Base;
9473       bool AllSame = true;
9474       for (unsigned i = 0; i != NumElts; ++i) {
9475         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9476           Base = V->getOperand(i);
9477           break;
9478         }
9479       }
9480       // Splat of <u, u, u, u>, return <u, u, u, u>
9481       if (!Base.getNode())
9482         return N0;
9483       for (unsigned i = 0; i != NumElts; ++i) {
9484         if (V->getOperand(i) != Base) {
9485           AllSame = false;
9486           break;
9487         }
9488       }
9489       // Splat of <x, x, x, x>, return <x, x, x, x>
9490       if (AllSame)
9491         return N0;
9492     }
9493   }
9494
9495   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9496       Level < AfterLegalizeVectorOps &&
9497       (N1.getOpcode() == ISD::UNDEF ||
9498       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9499        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9500     SDValue V = partitionShuffleOfConcats(N, DAG);
9501
9502     if (V.getNode())
9503       return V;
9504   }
9505
9506   // If this shuffle node is simply a swizzle of another shuffle node,
9507   // and it reverses the swizzle of the previous shuffle then we can
9508   // optimize shuffle(shuffle(x, undef), undef) -> x.
9509   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9510       N1.getOpcode() == ISD::UNDEF) {
9511
9512     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9513
9514     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9515     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9516       return SDValue();
9517
9518     // The incoming shuffle must be of the same type as the result of the
9519     // current shuffle.
9520     assert(OtherSV->getOperand(0).getValueType() == VT &&
9521            "Shuffle types don't match");
9522
9523     for (unsigned i = 0; i != NumElts; ++i) {
9524       int Idx = SVN->getMaskElt(i);
9525       assert(Idx < (int)NumElts && "Index references undef operand");
9526       // Next, this index comes from the first value, which is the incoming
9527       // shuffle. Adopt the incoming index.
9528       if (Idx >= 0)
9529         Idx = OtherSV->getMaskElt(Idx);
9530
9531       // The combined shuffle must map each index to itself.
9532       if (Idx >= 0 && (unsigned)Idx != i)
9533         return SDValue();
9534     }
9535
9536     return OtherSV->getOperand(0);
9537   }
9538
9539   return SDValue();
9540 }
9541
9542 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9543 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9544 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9545 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9546 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9547   EVT VT = N->getValueType(0);
9548   SDLoc dl(N);
9549   SDValue LHS = N->getOperand(0);
9550   SDValue RHS = N->getOperand(1);
9551   if (N->getOpcode() == ISD::AND) {
9552     if (RHS.getOpcode() == ISD::BITCAST)
9553       RHS = RHS.getOperand(0);
9554     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9555       SmallVector<int, 8> Indices;
9556       unsigned NumElts = RHS.getNumOperands();
9557       for (unsigned i = 0; i != NumElts; ++i) {
9558         SDValue Elt = RHS.getOperand(i);
9559         if (!isa<ConstantSDNode>(Elt))
9560           return SDValue();
9561
9562         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9563           Indices.push_back(i);
9564         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9565           Indices.push_back(NumElts);
9566         else
9567           return SDValue();
9568       }
9569
9570       // Let's see if the target supports this vector_shuffle.
9571       EVT RVT = RHS.getValueType();
9572       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9573         return SDValue();
9574
9575       // Return the new VECTOR_SHUFFLE node.
9576       EVT EltVT = RVT.getVectorElementType();
9577       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9578                                      DAG.getConstant(0, EltVT));
9579       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9580                                  RVT, &ZeroOps[0], ZeroOps.size());
9581       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9582       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9583       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9584     }
9585   }
9586
9587   return SDValue();
9588 }
9589
9590 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9591 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9592   assert(N->getValueType(0).isVector() &&
9593          "SimplifyVBinOp only works on vectors!");
9594
9595   SDValue LHS = N->getOperand(0);
9596   SDValue RHS = N->getOperand(1);
9597   SDValue Shuffle = XformToShuffleWithZero(N);
9598   if (Shuffle.getNode()) return Shuffle;
9599
9600   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9601   // this operation.
9602   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9603       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9604     SmallVector<SDValue, 8> Ops;
9605     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9606       SDValue LHSOp = LHS.getOperand(i);
9607       SDValue RHSOp = RHS.getOperand(i);
9608       // If these two elements can't be folded, bail out.
9609       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9610            LHSOp.getOpcode() != ISD::Constant &&
9611            LHSOp.getOpcode() != ISD::ConstantFP) ||
9612           (RHSOp.getOpcode() != ISD::UNDEF &&
9613            RHSOp.getOpcode() != ISD::Constant &&
9614            RHSOp.getOpcode() != ISD::ConstantFP))
9615         break;
9616
9617       // Can't fold divide by zero.
9618       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9619           N->getOpcode() == ISD::FDIV) {
9620         if ((RHSOp.getOpcode() == ISD::Constant &&
9621              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9622             (RHSOp.getOpcode() == ISD::ConstantFP &&
9623              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9624           break;
9625       }
9626
9627       EVT VT = LHSOp.getValueType();
9628       EVT RVT = RHSOp.getValueType();
9629       if (RVT != VT) {
9630         // Integer BUILD_VECTOR operands may have types larger than the element
9631         // size (e.g., when the element type is not legal).  Prior to type
9632         // legalization, the types may not match between the two BUILD_VECTORS.
9633         // Truncate one of the operands to make them match.
9634         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9635           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9636         } else {
9637           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9638           VT = RVT;
9639         }
9640       }
9641       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9642                                    LHSOp, RHSOp);
9643       if (FoldOp.getOpcode() != ISD::UNDEF &&
9644           FoldOp.getOpcode() != ISD::Constant &&
9645           FoldOp.getOpcode() != ISD::ConstantFP)
9646         break;
9647       Ops.push_back(FoldOp);
9648       AddToWorkList(FoldOp.getNode());
9649     }
9650
9651     if (Ops.size() == LHS.getNumOperands())
9652       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9653                          LHS.getValueType(), &Ops[0], Ops.size());
9654   }
9655
9656   return SDValue();
9657 }
9658
9659 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9660 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9661   assert(N->getValueType(0).isVector() &&
9662          "SimplifyVUnaryOp only works on vectors!");
9663
9664   SDValue N0 = N->getOperand(0);
9665
9666   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9667     return SDValue();
9668
9669   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9670   SmallVector<SDValue, 8> Ops;
9671   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9672     SDValue Op = N0.getOperand(i);
9673     if (Op.getOpcode() != ISD::UNDEF &&
9674         Op.getOpcode() != ISD::ConstantFP)
9675       break;
9676     EVT EltVT = Op.getValueType();
9677     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9678     if (FoldOp.getOpcode() != ISD::UNDEF &&
9679         FoldOp.getOpcode() != ISD::ConstantFP)
9680       break;
9681     Ops.push_back(FoldOp);
9682     AddToWorkList(FoldOp.getNode());
9683   }
9684
9685   if (Ops.size() != N0.getNumOperands())
9686     return SDValue();
9687
9688   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9689                      N0.getValueType(), &Ops[0], Ops.size());
9690 }
9691
9692 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9693                                     SDValue N1, SDValue N2){
9694   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9695
9696   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9697                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9698
9699   // If we got a simplified select_cc node back from SimplifySelectCC, then
9700   // break it down into a new SETCC node, and a new SELECT node, and then return
9701   // the SELECT node, since we were called with a SELECT node.
9702   if (SCC.getNode()) {
9703     // Check to see if we got a select_cc back (to turn into setcc/select).
9704     // Otherwise, just return whatever node we got back, like fabs.
9705     if (SCC.getOpcode() == ISD::SELECT_CC) {
9706       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9707                                   N0.getValueType(),
9708                                   SCC.getOperand(0), SCC.getOperand(1),
9709                                   SCC.getOperand(4));
9710       AddToWorkList(SETCC.getNode());
9711       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9712                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9713     }
9714
9715     return SCC;
9716   }
9717   return SDValue();
9718 }
9719
9720 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9721 /// are the two values being selected between, see if we can simplify the
9722 /// select.  Callers of this should assume that TheSelect is deleted if this
9723 /// returns true.  As such, they should return the appropriate thing (e.g. the
9724 /// node) back to the top-level of the DAG combiner loop to avoid it being
9725 /// looked at.
9726 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9727                                     SDValue RHS) {
9728
9729   // Cannot simplify select with vector condition
9730   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9731
9732   // If this is a select from two identical things, try to pull the operation
9733   // through the select.
9734   if (LHS.getOpcode() != RHS.getOpcode() ||
9735       !LHS.hasOneUse() || !RHS.hasOneUse())
9736     return false;
9737
9738   // If this is a load and the token chain is identical, replace the select
9739   // of two loads with a load through a select of the address to load from.
9740   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9741   // constants have been dropped into the constant pool.
9742   if (LHS.getOpcode() == ISD::LOAD) {
9743     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9744     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9745
9746     // Token chains must be identical.
9747     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9748         // Do not let this transformation reduce the number of volatile loads.
9749         LLD->isVolatile() || RLD->isVolatile() ||
9750         // If this is an EXTLOAD, the VT's must match.
9751         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9752         // If this is an EXTLOAD, the kind of extension must match.
9753         (LLD->getExtensionType() != RLD->getExtensionType() &&
9754          // The only exception is if one of the extensions is anyext.
9755          LLD->getExtensionType() != ISD::EXTLOAD &&
9756          RLD->getExtensionType() != ISD::EXTLOAD) ||
9757         // FIXME: this discards src value information.  This is
9758         // over-conservative. It would be beneficial to be able to remember
9759         // both potential memory locations.  Since we are discarding
9760         // src value info, don't do the transformation if the memory
9761         // locations are not in the default address space.
9762         LLD->getPointerInfo().getAddrSpace() != 0 ||
9763         RLD->getPointerInfo().getAddrSpace() != 0 ||
9764         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9765                                       LLD->getBasePtr().getValueType()))
9766       return false;
9767
9768     // Check that the select condition doesn't reach either load.  If so,
9769     // folding this will induce a cycle into the DAG.  If not, this is safe to
9770     // xform, so create a select of the addresses.
9771     SDValue Addr;
9772     if (TheSelect->getOpcode() == ISD::SELECT) {
9773       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9774       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9775           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9776         return false;
9777       // The loads must not depend on one another.
9778       if (LLD->isPredecessorOf(RLD) ||
9779           RLD->isPredecessorOf(LLD))
9780         return false;
9781       Addr = DAG.getSelect(SDLoc(TheSelect),
9782                            LLD->getBasePtr().getValueType(),
9783                            TheSelect->getOperand(0), LLD->getBasePtr(),
9784                            RLD->getBasePtr());
9785     } else {  // Otherwise SELECT_CC
9786       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9787       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9788
9789       if ((LLD->hasAnyUseOfValue(1) &&
9790            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9791           (RLD->hasAnyUseOfValue(1) &&
9792            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9793         return false;
9794
9795       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9796                          LLD->getBasePtr().getValueType(),
9797                          TheSelect->getOperand(0),
9798                          TheSelect->getOperand(1),
9799                          LLD->getBasePtr(), RLD->getBasePtr(),
9800                          TheSelect->getOperand(4));
9801     }
9802
9803     SDValue Load;
9804     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9805       Load = DAG.getLoad(TheSelect->getValueType(0),
9806                          SDLoc(TheSelect),
9807                          // FIXME: Discards pointer info.
9808                          LLD->getChain(), Addr, MachinePointerInfo(),
9809                          LLD->isVolatile(), LLD->isNonTemporal(),
9810                          LLD->isInvariant(), LLD->getAlignment());
9811     } else {
9812       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9813                             RLD->getExtensionType() : LLD->getExtensionType(),
9814                             SDLoc(TheSelect),
9815                             TheSelect->getValueType(0),
9816                             // FIXME: Discards pointer info.
9817                             LLD->getChain(), Addr, MachinePointerInfo(),
9818                             LLD->getMemoryVT(), LLD->isVolatile(),
9819                             LLD->isNonTemporal(), LLD->getAlignment());
9820     }
9821
9822     // Users of the select now use the result of the load.
9823     CombineTo(TheSelect, Load);
9824
9825     // Users of the old loads now use the new load's chain.  We know the
9826     // old-load value is dead now.
9827     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9828     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9829     return true;
9830   }
9831
9832   return false;
9833 }
9834
9835 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9836 /// where 'cond' is the comparison specified by CC.
9837 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9838                                       SDValue N2, SDValue N3,
9839                                       ISD::CondCode CC, bool NotExtCompare) {
9840   // (x ? y : y) -> y.
9841   if (N2 == N3) return N2;
9842
9843   EVT VT = N2.getValueType();
9844   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9845   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9846   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9847
9848   // Determine if the condition we're dealing with is constant
9849   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9850                               N0, N1, CC, DL, false);
9851   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9852   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9853
9854   // fold select_cc true, x, y -> x
9855   if (SCCC && !SCCC->isNullValue())
9856     return N2;
9857   // fold select_cc false, x, y -> y
9858   if (SCCC && SCCC->isNullValue())
9859     return N3;
9860
9861   // Check to see if we can simplify the select into an fabs node
9862   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9863     // Allow either -0.0 or 0.0
9864     if (CFP->getValueAPF().isZero()) {
9865       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9866       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9867           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9868           N2 == N3.getOperand(0))
9869         return DAG.getNode(ISD::FABS, DL, VT, N0);
9870
9871       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9872       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9873           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9874           N2.getOperand(0) == N3)
9875         return DAG.getNode(ISD::FABS, DL, VT, N3);
9876     }
9877   }
9878
9879   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9880   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9881   // in it.  This is a win when the constant is not otherwise available because
9882   // it replaces two constant pool loads with one.  We only do this if the FP
9883   // type is known to be legal, because if it isn't, then we are before legalize
9884   // types an we want the other legalization to happen first (e.g. to avoid
9885   // messing with soft float) and if the ConstantFP is not legal, because if
9886   // it is legal, we may not need to store the FP constant in a constant pool.
9887   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9888     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9889       if (TLI.isTypeLegal(N2.getValueType()) &&
9890           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9891            TargetLowering::Legal) &&
9892           // If both constants have multiple uses, then we won't need to do an
9893           // extra load, they are likely around in registers for other users.
9894           (TV->hasOneUse() || FV->hasOneUse())) {
9895         Constant *Elts[] = {
9896           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9897           const_cast<ConstantFP*>(TV->getConstantFPValue())
9898         };
9899         Type *FPTy = Elts[0]->getType();
9900         const DataLayout &TD = *TLI.getDataLayout();
9901
9902         // Create a ConstantArray of the two constants.
9903         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9904         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9905                                             TD.getPrefTypeAlignment(FPTy));
9906         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9907
9908         // Get the offsets to the 0 and 1 element of the array so that we can
9909         // select between them.
9910         SDValue Zero = DAG.getIntPtrConstant(0);
9911         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9912         SDValue One = DAG.getIntPtrConstant(EltSize);
9913
9914         SDValue Cond = DAG.getSetCC(DL,
9915                                     getSetCCResultType(N0.getValueType()),
9916                                     N0, N1, CC);
9917         AddToWorkList(Cond.getNode());
9918         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9919                                           Cond, One, Zero);
9920         AddToWorkList(CstOffset.getNode());
9921         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9922                             CstOffset);
9923         AddToWorkList(CPIdx.getNode());
9924         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9925                            MachinePointerInfo::getConstantPool(), false,
9926                            false, false, Alignment);
9927
9928       }
9929     }
9930
9931   // Check to see if we can perform the "gzip trick", transforming
9932   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9933   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9934       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9935        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9936     EVT XType = N0.getValueType();
9937     EVT AType = N2.getValueType();
9938     if (XType.bitsGE(AType)) {
9939       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9940       // single-bit constant.
9941       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9942         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9943         ShCtV = XType.getSizeInBits()-ShCtV-1;
9944         SDValue ShCt = DAG.getConstant(ShCtV,
9945                                        getShiftAmountTy(N0.getValueType()));
9946         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9947                                     XType, N0, ShCt);
9948         AddToWorkList(Shift.getNode());
9949
9950         if (XType.bitsGT(AType)) {
9951           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9952           AddToWorkList(Shift.getNode());
9953         }
9954
9955         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9956       }
9957
9958       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9959                                   XType, N0,
9960                                   DAG.getConstant(XType.getSizeInBits()-1,
9961                                          getShiftAmountTy(N0.getValueType())));
9962       AddToWorkList(Shift.getNode());
9963
9964       if (XType.bitsGT(AType)) {
9965         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9966         AddToWorkList(Shift.getNode());
9967       }
9968
9969       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9970     }
9971   }
9972
9973   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9974   // where y is has a single bit set.
9975   // A plaintext description would be, we can turn the SELECT_CC into an AND
9976   // when the condition can be materialized as an all-ones register.  Any
9977   // single bit-test can be materialized as an all-ones register with
9978   // shift-left and shift-right-arith.
9979   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9980       N0->getValueType(0) == VT &&
9981       N1C && N1C->isNullValue() &&
9982       N2C && N2C->isNullValue()) {
9983     SDValue AndLHS = N0->getOperand(0);
9984     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9985     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9986       // Shift the tested bit over the sign bit.
9987       APInt AndMask = ConstAndRHS->getAPIntValue();
9988       SDValue ShlAmt =
9989         DAG.getConstant(AndMask.countLeadingZeros(),
9990                         getShiftAmountTy(AndLHS.getValueType()));
9991       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9992
9993       // Now arithmetic right shift it all the way over, so the result is either
9994       // all-ones, or zero.
9995       SDValue ShrAmt =
9996         DAG.getConstant(AndMask.getBitWidth()-1,
9997                         getShiftAmountTy(Shl.getValueType()));
9998       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9999
10000       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10001     }
10002   }
10003
10004   // fold select C, 16, 0 -> shl C, 4
10005   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10006     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10007       TargetLowering::ZeroOrOneBooleanContent) {
10008
10009     // If the caller doesn't want us to simplify this into a zext of a compare,
10010     // don't do it.
10011     if (NotExtCompare && N2C->getAPIntValue() == 1)
10012       return SDValue();
10013
10014     // Get a SetCC of the condition
10015     // NOTE: Don't create a SETCC if it's not legal on this target.
10016     if (!LegalOperations ||
10017         TLI.isOperationLegal(ISD::SETCC,
10018           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10019       SDValue Temp, SCC;
10020       // cast from setcc result type to select result type
10021       if (LegalTypes) {
10022         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10023                             N0, N1, CC);
10024         if (N2.getValueType().bitsLT(SCC.getValueType()))
10025           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10026                                         N2.getValueType());
10027         else
10028           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10029                              N2.getValueType(), SCC);
10030       } else {
10031         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10032         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10033                            N2.getValueType(), SCC);
10034       }
10035
10036       AddToWorkList(SCC.getNode());
10037       AddToWorkList(Temp.getNode());
10038
10039       if (N2C->getAPIntValue() == 1)
10040         return Temp;
10041
10042       // shl setcc result by log2 n2c
10043       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10044                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10045                                          getShiftAmountTy(Temp.getValueType())));
10046     }
10047   }
10048
10049   // Check to see if this is the equivalent of setcc
10050   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10051   // otherwise, go ahead with the folds.
10052   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10053     EVT XType = N0.getValueType();
10054     if (!LegalOperations ||
10055         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10056       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10057       if (Res.getValueType() != VT)
10058         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10059       return Res;
10060     }
10061
10062     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10063     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10064         (!LegalOperations ||
10065          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10066       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10067       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10068                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10069                                        getShiftAmountTy(Ctlz.getValueType())));
10070     }
10071     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10072     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10073       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10074                                   XType, DAG.getConstant(0, XType), N0);
10075       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10076       return DAG.getNode(ISD::SRL, DL, XType,
10077                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10078                          DAG.getConstant(XType.getSizeInBits()-1,
10079                                          getShiftAmountTy(XType)));
10080     }
10081     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10082     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10083       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10084                                  DAG.getConstant(XType.getSizeInBits()-1,
10085                                          getShiftAmountTy(N0.getValueType())));
10086       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10087     }
10088   }
10089
10090   // Check to see if this is an integer abs.
10091   // select_cc setg[te] X,  0,  X, -X ->
10092   // select_cc setgt    X, -1,  X, -X ->
10093   // select_cc setl[te] X,  0, -X,  X ->
10094   // select_cc setlt    X,  1, -X,  X ->
10095   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10096   if (N1C) {
10097     ConstantSDNode *SubC = NULL;
10098     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10099          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10100         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10101       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10102     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10103               (N1C->isOne() && CC == ISD::SETLT)) &&
10104              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10105       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10106
10107     EVT XType = N0.getValueType();
10108     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10109       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10110                                   N0,
10111                                   DAG.getConstant(XType.getSizeInBits()-1,
10112                                          getShiftAmountTy(N0.getValueType())));
10113       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10114                                 XType, N0, Shift);
10115       AddToWorkList(Shift.getNode());
10116       AddToWorkList(Add.getNode());
10117       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10118     }
10119   }
10120
10121   return SDValue();
10122 }
10123
10124 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10125 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10126                                    SDValue N1, ISD::CondCode Cond,
10127                                    SDLoc DL, bool foldBooleans) {
10128   TargetLowering::DAGCombinerInfo
10129     DagCombineInfo(DAG, Level, false, this);
10130   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10131 }
10132
10133 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10134 /// return a DAG expression to select that will generate the same value by
10135 /// multiplying by a magic number.  See:
10136 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10137 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10138   std::vector<SDNode*> Built;
10139   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10140
10141   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10142        ii != ee; ++ii)
10143     AddToWorkList(*ii);
10144   return S;
10145 }
10146
10147 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10148 /// return a DAG expression to select that will generate the same value by
10149 /// multiplying by a magic number.  See:
10150 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10151 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10152   std::vector<SDNode*> Built;
10153   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10154
10155   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10156        ii != ee; ++ii)
10157     AddToWorkList(*ii);
10158   return S;
10159 }
10160
10161 /// FindBaseOffset - Return true if base is a frame index, which is known not
10162 // to alias with anything but itself.  Provides base object and offset as
10163 // results.
10164 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10165                            const GlobalValue *&GV, const void *&CV) {
10166   // Assume it is a primitive operation.
10167   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10168
10169   // If it's an adding a simple constant then integrate the offset.
10170   if (Base.getOpcode() == ISD::ADD) {
10171     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10172       Base = Base.getOperand(0);
10173       Offset += C->getZExtValue();
10174     }
10175   }
10176
10177   // Return the underlying GlobalValue, and update the Offset.  Return false
10178   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10179   // by multiple nodes with different offsets.
10180   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10181     GV = G->getGlobal();
10182     Offset += G->getOffset();
10183     return false;
10184   }
10185
10186   // Return the underlying Constant value, and update the Offset.  Return false
10187   // for ConstantSDNodes since the same constant pool entry may be represented
10188   // by multiple nodes with different offsets.
10189   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10190     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10191                                          : (const void *)C->getConstVal();
10192     Offset += C->getOffset();
10193     return false;
10194   }
10195   // If it's any of the following then it can't alias with anything but itself.
10196   return isa<FrameIndexSDNode>(Base);
10197 }
10198
10199 /// isAlias - Return true if there is any possibility that the two addresses
10200 /// overlap.
10201 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10202                           const Value *SrcValue1, int SrcValueOffset1,
10203                           unsigned SrcValueAlign1,
10204                           const MDNode *TBAAInfo1,
10205                           SDValue Ptr2, int64_t Size2,
10206                           const Value *SrcValue2, int SrcValueOffset2,
10207                           unsigned SrcValueAlign2,
10208                           const MDNode *TBAAInfo2) const {
10209   // If they are the same then they must be aliases.
10210   if (Ptr1 == Ptr2) return true;
10211
10212   // Gather base node and offset information.
10213   SDValue Base1, Base2;
10214   int64_t Offset1, Offset2;
10215   const GlobalValue *GV1, *GV2;
10216   const void *CV1, *CV2;
10217   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10218   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10219
10220   // If they have a same base address then check to see if they overlap.
10221   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10222     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10223
10224   // It is possible for different frame indices to alias each other, mostly
10225   // when tail call optimization reuses return address slots for arguments.
10226   // To catch this case, look up the actual index of frame indices to compute
10227   // the real alias relationship.
10228   if (isFrameIndex1 && isFrameIndex2) {
10229     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10230     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10231     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10232     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10233   }
10234
10235   // Otherwise, if we know what the bases are, and they aren't identical, then
10236   // we know they cannot alias.
10237   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10238     return false;
10239
10240   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10241   // compared to the size and offset of the access, we may be able to prove they
10242   // do not alias.  This check is conservative for now to catch cases created by
10243   // splitting vector types.
10244   if ((SrcValueAlign1 == SrcValueAlign2) &&
10245       (SrcValueOffset1 != SrcValueOffset2) &&
10246       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10247     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10248     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10249
10250     // There is no overlap between these relatively aligned accesses of similar
10251     // size, return no alias.
10252     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10253       return false;
10254   }
10255
10256   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10257     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10258   if (UseAA && SrcValue1 && SrcValue2) {
10259     // Use alias analysis information.
10260     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10261     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10262     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10263     AliasAnalysis::AliasResult AAResult =
10264       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10265                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10266     if (AAResult == AliasAnalysis::NoAlias)
10267       return false;
10268   }
10269
10270   // Otherwise we have to assume they alias.
10271   return true;
10272 }
10273
10274 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10275   SDValue Ptr0, Ptr1;
10276   int64_t Size0, Size1;
10277   const Value *SrcValue0, *SrcValue1;
10278   int SrcValueOffset0, SrcValueOffset1;
10279   unsigned SrcValueAlign0, SrcValueAlign1;
10280   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10281   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10282                 SrcValueAlign0, SrcTBAAInfo0);
10283   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10284                 SrcValueAlign1, SrcTBAAInfo1);
10285   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10286                  SrcValueAlign0, SrcTBAAInfo0,
10287                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10288                  SrcValueAlign1, SrcTBAAInfo1);
10289 }
10290
10291 /// FindAliasInfo - Extracts the relevant alias information from the memory
10292 /// node.  Returns true if the operand was a load.
10293 bool DAGCombiner::FindAliasInfo(SDNode *N,
10294                                 SDValue &Ptr, int64_t &Size,
10295                                 const Value *&SrcValue,
10296                                 int &SrcValueOffset,
10297                                 unsigned &SrcValueAlign,
10298                                 const MDNode *&TBAAInfo) const {
10299   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10300
10301   Ptr = LS->getBasePtr();
10302   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10303   SrcValue = LS->getSrcValue();
10304   SrcValueOffset = LS->getSrcValueOffset();
10305   SrcValueAlign = LS->getOriginalAlignment();
10306   TBAAInfo = LS->getTBAAInfo();
10307   return isa<LoadSDNode>(LS);
10308 }
10309
10310 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10311 /// looking for aliasing nodes and adding them to the Aliases vector.
10312 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10313                                    SmallVectorImpl<SDValue> &Aliases) {
10314   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10315   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10316
10317   // Get alias information for node.
10318   SDValue Ptr;
10319   int64_t Size;
10320   const Value *SrcValue;
10321   int SrcValueOffset;
10322   unsigned SrcValueAlign;
10323   const MDNode *SrcTBAAInfo;
10324   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10325                               SrcValueAlign, SrcTBAAInfo);
10326
10327   // Starting off.
10328   Chains.push_back(OriginalChain);
10329   unsigned Depth = 0;
10330
10331   // Look at each chain and determine if it is an alias.  If so, add it to the
10332   // aliases list.  If not, then continue up the chain looking for the next
10333   // candidate.
10334   while (!Chains.empty()) {
10335     SDValue Chain = Chains.back();
10336     Chains.pop_back();
10337
10338     // For TokenFactor nodes, look at each operand and only continue up the
10339     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10340     // find more and revert to original chain since the xform is unlikely to be
10341     // profitable.
10342     //
10343     // FIXME: The depth check could be made to return the last non-aliasing
10344     // chain we found before we hit a tokenfactor rather than the original
10345     // chain.
10346     if (Depth > 6 || Aliases.size() == 2) {
10347       Aliases.clear();
10348       Aliases.push_back(OriginalChain);
10349       break;
10350     }
10351
10352     // Don't bother if we've been before.
10353     if (!Visited.insert(Chain.getNode()))
10354       continue;
10355
10356     switch (Chain.getOpcode()) {
10357     case ISD::EntryToken:
10358       // Entry token is ideal chain operand, but handled in FindBetterChain.
10359       break;
10360
10361     case ISD::LOAD:
10362     case ISD::STORE: {
10363       // Get alias information for Chain.
10364       SDValue OpPtr;
10365       int64_t OpSize;
10366       const Value *OpSrcValue;
10367       int OpSrcValueOffset;
10368       unsigned OpSrcValueAlign;
10369       const MDNode *OpSrcTBAAInfo;
10370       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10371                                     OpSrcValue, OpSrcValueOffset,
10372                                     OpSrcValueAlign,
10373                                     OpSrcTBAAInfo);
10374
10375       // If chain is alias then stop here.
10376       if (!(IsLoad && IsOpLoad) &&
10377           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10378                   SrcTBAAInfo,
10379                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10380                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10381         Aliases.push_back(Chain);
10382       } else {
10383         // Look further up the chain.
10384         Chains.push_back(Chain.getOperand(0));
10385         ++Depth;
10386       }
10387       break;
10388     }
10389
10390     case ISD::TokenFactor:
10391       // We have to check each of the operands of the token factor for "small"
10392       // token factors, so we queue them up.  Adding the operands to the queue
10393       // (stack) in reverse order maintains the original order and increases the
10394       // likelihood that getNode will find a matching token factor (CSE.)
10395       if (Chain.getNumOperands() > 16) {
10396         Aliases.push_back(Chain);
10397         break;
10398       }
10399       for (unsigned n = Chain.getNumOperands(); n;)
10400         Chains.push_back(Chain.getOperand(--n));
10401       ++Depth;
10402       break;
10403
10404     default:
10405       // For all other instructions we will just have to take what we can get.
10406       Aliases.push_back(Chain);
10407       break;
10408     }
10409   }
10410 }
10411
10412 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10413 /// for a better chain (aliasing node.)
10414 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10415   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10416
10417   // Accumulate all the aliases to this node.
10418   GatherAllAliases(N, OldChain, Aliases);
10419
10420   // If no operands then chain to entry token.
10421   if (Aliases.size() == 0)
10422     return DAG.getEntryNode();
10423
10424   // If a single operand then chain to it.  We don't need to revisit it.
10425   if (Aliases.size() == 1)
10426     return Aliases[0];
10427
10428   // Construct a custom tailored token factor.
10429   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10430                      &Aliases[0], Aliases.size());
10431 }
10432
10433 // SelectionDAG::Combine - This is the entry point for the file.
10434 //
10435 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10436                            CodeGenOpt::Level OptLevel) {
10437   /// run - This is the main entry point to this class.
10438   ///
10439   DAGCombiner(*this, AA, OptLevel).Run(Level);
10440 }