[DAG] Refactor ReassociateOps - no functional change intended.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Turn on alias analysis during testing"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Include global information in alias analysis"));
58
59   /// Hidden option to stress test load slicing, i.e., when this option
60   /// is enabled, load slicing bypasses most of its profitability guards.
61   static cl::opt<bool>
62   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63                     cl::desc("Bypass the profitability model of load "
64                              "slicing"),
65                     cl::init(false));
66
67 //------------------------------ DAGCombiner ---------------------------------//
68
69   class DAGCombiner {
70     SelectionDAG &DAG;
71     const TargetLowering &TLI;
72     CombineLevel Level;
73     CodeGenOpt::Level OptLevel;
74     bool LegalOperations;
75     bool LegalTypes;
76     bool ForCodeSize;
77
78     // Worklist of all of the nodes that need to be simplified.
79     //
80     // This has the semantics that when adding to the worklist,
81     // the item added must be next to be processed. It should
82     // also only appear once. The naive approach to this takes
83     // linear time.
84     //
85     // To reduce the insert/remove time to logarithmic, we use
86     // a set and a vector to maintain our worklist.
87     //
88     // The set contains the items on the worklist, but does not
89     // maintain the order they should be visited.
90     //
91     // The vector maintains the order nodes should be visited, but may
92     // contain duplicate or removed nodes. When choosing a node to
93     // visit, we pop off the order stack until we find an item that is
94     // also in the contents set. All operations are O(log N).
95     SmallPtrSet<SDNode*, 64> WorkListContents;
96     SmallVector<SDNode*, 64> WorkListOrder;
97
98     // AA - Used for DAG load/store alias analysis.
99     AliasAnalysis &AA;
100
101     /// AddUsersToWorkList - When an instruction is simplified, add all users of
102     /// the instruction to the work lists because they might get more simplified
103     /// now.
104     ///
105     void AddUsersToWorkList(SDNode *N) {
106       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
107            UI != UE; ++UI)
108         AddToWorkList(*UI);
109     }
110
111     /// visit - call the node-specific routine that knows how to fold each
112     /// particular type of node.
113     SDValue visit(SDNode *N);
114
115   public:
116     /// AddToWorkList - Add to the work list making sure its instance is at the
117     /// back (next to be processed.)
118     void AddToWorkList(SDNode *N) {
119       WorkListContents.insert(N);
120       WorkListOrder.push_back(N);
121     }
122
123     /// removeFromWorkList - remove all instances of N from the worklist.
124     ///
125     void removeFromWorkList(SDNode *N) {
126       WorkListContents.erase(N);
127     }
128
129     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
130                       bool AddTo = true);
131
132     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133       return CombineTo(N, &Res, 1, AddTo);
134     }
135
136     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
137                       bool AddTo = true) {
138       SDValue To[] = { Res0, Res1 };
139       return CombineTo(N, To, 2, AddTo);
140     }
141
142     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
143
144   private:
145
146     /// SimplifyDemandedBits - Check the specified integer node value to see if
147     /// it can be simplified or if things it uses can be simplified by bit
148     /// propagation.  If so, return true.
149     bool SimplifyDemandedBits(SDValue Op) {
150       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151       APInt Demanded = APInt::getAllOnesValue(BitWidth);
152       return SimplifyDemandedBits(Op, Demanded);
153     }
154
155     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
156
157     bool CombineToPreIndexedLoadStore(SDNode *N);
158     bool CombineToPostIndexedLoadStore(SDNode *N);
159     bool SliceUpLoad(SDNode *N);
160
161     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165     SDValue PromoteIntBinOp(SDValue Op);
166     SDValue PromoteIntShiftOp(SDValue Op);
167     SDValue PromoteExtend(SDValue Op);
168     bool PromoteLoad(SDValue Op);
169
170     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172                          ISD::NodeType ExtType);
173
174     /// combine - call the node-specific routine that knows how to fold each
175     /// particular type of node. If that doesn't do anything, try the
176     /// target-specific DAG combines.
177     SDValue combine(SDNode *N);
178
179     // Visitation implementation - Implement dag node combining for different
180     // node types.  The semantics are as follows:
181     // Return Value:
182     //   SDValue.getNode() == 0 - No change was made
183     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
184     //   otherwise              - N should be replaced by the returned Operand.
185     //
186     SDValue visitTokenFactor(SDNode *N);
187     SDValue visitMERGE_VALUES(SDNode *N);
188     SDValue visitADD(SDNode *N);
189     SDValue visitSUB(SDNode *N);
190     SDValue visitADDC(SDNode *N);
191     SDValue visitSUBC(SDNode *N);
192     SDValue visitADDE(SDNode *N);
193     SDValue visitSUBE(SDNode *N);
194     SDValue visitMUL(SDNode *N);
195     SDValue visitSDIV(SDNode *N);
196     SDValue visitUDIV(SDNode *N);
197     SDValue visitSREM(SDNode *N);
198     SDValue visitUREM(SDNode *N);
199     SDValue visitMULHU(SDNode *N);
200     SDValue visitMULHS(SDNode *N);
201     SDValue visitSMUL_LOHI(SDNode *N);
202     SDValue visitUMUL_LOHI(SDNode *N);
203     SDValue visitSMULO(SDNode *N);
204     SDValue visitUMULO(SDNode *N);
205     SDValue visitSDIVREM(SDNode *N);
206     SDValue visitUDIVREM(SDNode *N);
207     SDValue visitAND(SDNode *N);
208     SDValue visitOR(SDNode *N);
209     SDValue visitXOR(SDNode *N);
210     SDValue SimplifyVBinOp(SDNode *N);
211     SDValue SimplifyVUnaryOp(SDNode *N);
212     SDValue visitSHL(SDNode *N);
213     SDValue visitSRA(SDNode *N);
214     SDValue visitSRL(SDNode *N);
215     SDValue visitCTLZ(SDNode *N);
216     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217     SDValue visitCTTZ(SDNode *N);
218     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219     SDValue visitCTPOP(SDNode *N);
220     SDValue visitSELECT(SDNode *N);
221     SDValue visitVSELECT(SDNode *N);
222     SDValue visitSELECT_CC(SDNode *N);
223     SDValue visitSETCC(SDNode *N);
224     SDValue visitSIGN_EXTEND(SDNode *N);
225     SDValue visitZERO_EXTEND(SDNode *N);
226     SDValue visitANY_EXTEND(SDNode *N);
227     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228     SDValue visitTRUNCATE(SDNode *N);
229     SDValue visitBITCAST(SDNode *N);
230     SDValue visitBUILD_PAIR(SDNode *N);
231     SDValue visitFADD(SDNode *N);
232     SDValue visitFSUB(SDNode *N);
233     SDValue visitFMUL(SDNode *N);
234     SDValue visitFMA(SDNode *N);
235     SDValue visitFDIV(SDNode *N);
236     SDValue visitFREM(SDNode *N);
237     SDValue visitFCOPYSIGN(SDNode *N);
238     SDValue visitSINT_TO_FP(SDNode *N);
239     SDValue visitUINT_TO_FP(SDNode *N);
240     SDValue visitFP_TO_SINT(SDNode *N);
241     SDValue visitFP_TO_UINT(SDNode *N);
242     SDValue visitFP_ROUND(SDNode *N);
243     SDValue visitFP_ROUND_INREG(SDNode *N);
244     SDValue visitFP_EXTEND(SDNode *N);
245     SDValue visitFNEG(SDNode *N);
246     SDValue visitFABS(SDNode *N);
247     SDValue visitFCEIL(SDNode *N);
248     SDValue visitFTRUNC(SDNode *N);
249     SDValue visitFFLOOR(SDNode *N);
250     SDValue visitBRCOND(SDNode *N);
251     SDValue visitBR_CC(SDNode *N);
252     SDValue visitLOAD(SDNode *N);
253     SDValue visitSTORE(SDNode *N);
254     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256     SDValue visitBUILD_VECTOR(SDNode *N);
257     SDValue visitCONCAT_VECTORS(SDNode *N);
258     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259     SDValue visitVECTOR_SHUFFLE(SDNode *N);
260
261     SDValue XformToShuffleWithZero(SDNode *N);
262     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
263
264     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
265
266     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270                              SDValue N3, ISD::CondCode CC,
271                              bool NotExtCompare = false);
272     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273                           SDLoc DL, bool foldBooleans = true);
274     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
275                                          unsigned HiOp);
276     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278     SDValue BuildSDIV(SDNode *N);
279     SDValue BuildUDIV(SDNode *N);
280     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281                                bool DemandHighBits = true);
282     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
284                               SDValue InnerPos, SDValue InnerNeg,
285                               unsigned PosOpcode, unsigned NegOpcode,
286                               SDLoc DL);
287     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
288     SDValue ReduceLoadWidth(SDNode *N);
289     SDValue ReduceLoadOpStoreWidth(SDNode *N);
290     SDValue TransformFPLoadStorePair(SDNode *N);
291     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
292     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
293
294     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
295
296     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
297     /// looking for aliasing nodes and adding them to the Aliases vector.
298     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
299                           SmallVectorImpl<SDValue> &Aliases);
300
301     /// isAlias - Return true if there is any possibility that the two addresses
302     /// overlap.
303     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
304                  const Value *SrcValue1, int SrcValueOffset1,
305                  unsigned SrcValueAlign1,
306                  const MDNode *TBAAInfo1,
307                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
308                  const Value *SrcValue2, int SrcValueOffset2,
309                  unsigned SrcValueAlign2,
310                  const MDNode *TBAAInfo2) const;
311
312     /// isAlias - Return true if there is any possibility that the two addresses
313     /// overlap.
314     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
315
316     /// FindAliasInfo - Extracts the relevant alias information from the memory
317     /// node.  Returns true if the operand was a load.
318     bool FindAliasInfo(SDNode *N,
319                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
320                        const Value *&SrcValue, int &SrcValueOffset,
321                        unsigned &SrcValueAlignment,
322                        const MDNode *&TBAAInfo) const;
323
324     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
325     /// looking for a better chain (aliasing node.)
326     SDValue FindBetterChain(SDNode *N, SDValue Chain);
327
328     /// Merge consecutive store operations into a wide store.
329     /// This optimization uses wide integers or vectors when possible.
330     /// \return True if some memory operations were changed.
331     bool MergeConsecutiveStores(StoreSDNode *N);
332
333   public:
334     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
335         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
336           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
337       AttributeSet FnAttrs =
338           DAG.getMachineFunction().getFunction()->getAttributes();
339       ForCodeSize =
340           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
341                                Attribute::OptimizeForSize) ||
342           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
343     }
344
345     /// Run - runs the dag combiner on all nodes in the work list
346     void Run(CombineLevel AtLevel);
347
348     SelectionDAG &getDAG() const { return DAG; }
349
350     /// getShiftAmountTy - Returns a type large enough to hold any valid
351     /// shift amount - before type legalization these can be huge.
352     EVT getShiftAmountTy(EVT LHSTy) {
353       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
354       if (LHSTy.isVector())
355         return LHSTy;
356       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
357                         : TLI.getPointerTy();
358     }
359
360     /// isTypeLegal - This method returns true if we are running before type
361     /// legalization or if the specified VT is legal.
362     bool isTypeLegal(const EVT &VT) {
363       if (!LegalTypes) return true;
364       return TLI.isTypeLegal(VT);
365     }
366
367     /// getSetCCResultType - Convenience wrapper around
368     /// TargetLowering::getSetCCResultType
369     EVT getSetCCResultType(EVT VT) const {
370       return TLI.getSetCCResultType(*DAG.getContext(), VT);
371     }
372   };
373 }
374
375
376 namespace {
377 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
378 /// nodes from the worklist.
379 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
380   DAGCombiner &DC;
381 public:
382   explicit WorkListRemover(DAGCombiner &dc)
383     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
384
385   virtual void NodeDeleted(SDNode *N, SDNode *E) {
386     DC.removeFromWorkList(N);
387   }
388 };
389 }
390
391 //===----------------------------------------------------------------------===//
392 //  TargetLowering::DAGCombinerInfo implementation
393 //===----------------------------------------------------------------------===//
394
395 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
396   ((DAGCombiner*)DC)->AddToWorkList(N);
397 }
398
399 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
400   ((DAGCombiner*)DC)->removeFromWorkList(N);
401 }
402
403 SDValue TargetLowering::DAGCombinerInfo::
404 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
405   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
406 }
407
408 SDValue TargetLowering::DAGCombinerInfo::
409 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
410   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
411 }
412
413
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
416   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
417 }
418
419 void TargetLowering::DAGCombinerInfo::
420 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
421   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
422 }
423
424 //===----------------------------------------------------------------------===//
425 // Helper Functions
426 //===----------------------------------------------------------------------===//
427
428 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
429 /// specified expression for the same cost as the expression itself, or 2 if we
430 /// can compute the negated form more cheaply than the expression itself.
431 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
432                                const TargetLowering &TLI,
433                                const TargetOptions *Options,
434                                unsigned Depth = 0) {
435   // fneg is removable even if it has multiple uses.
436   if (Op.getOpcode() == ISD::FNEG) return 2;
437
438   // Don't allow anything with multiple uses.
439   if (!Op.hasOneUse()) return 0;
440
441   // Don't recurse exponentially.
442   if (Depth > 6) return 0;
443
444   switch (Op.getOpcode()) {
445   default: return false;
446   case ISD::ConstantFP:
447     // Don't invert constant FP values after legalize.  The negated constant
448     // isn't necessarily legal.
449     return LegalOperations ? 0 : 1;
450   case ISD::FADD:
451     // FIXME: determine better conditions for this xform.
452     if (!Options->UnsafeFPMath) return 0;
453
454     // After operation legalization, it might not be legal to create new FSUBs.
455     if (LegalOperations &&
456         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
457       return 0;
458
459     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
460     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
461                                     Options, Depth + 1))
462       return V;
463     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
464     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
465                               Depth + 1);
466   case ISD::FSUB:
467     // We can't turn -(A-B) into B-A when we honor signed zeros.
468     if (!Options->UnsafeFPMath) return 0;
469
470     // fold (fneg (fsub A, B)) -> (fsub B, A)
471     return 1;
472
473   case ISD::FMUL:
474   case ISD::FDIV:
475     if (Options->HonorSignDependentRoundingFPMath()) return 0;
476
477     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
478     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
479                                     Options, Depth + 1))
480       return V;
481
482     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
483                               Depth + 1);
484
485   case ISD::FP_EXTEND:
486   case ISD::FP_ROUND:
487   case ISD::FSIN:
488     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
489                               Depth + 1);
490   }
491 }
492
493 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
494 /// returns the newly negated expression.
495 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
496                                     bool LegalOperations, unsigned Depth = 0) {
497   // fneg is removable even if it has multiple uses.
498   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
499
500   // Don't allow anything with multiple uses.
501   assert(Op.hasOneUse() && "Unknown reuse!");
502
503   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
504   switch (Op.getOpcode()) {
505   default: llvm_unreachable("Unknown code");
506   case ISD::ConstantFP: {
507     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
508     V.changeSign();
509     return DAG.getConstantFP(V, Op.getValueType());
510   }
511   case ISD::FADD:
512     // FIXME: determine better conditions for this xform.
513     assert(DAG.getTarget().Options.UnsafeFPMath);
514
515     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
516     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
517                            DAG.getTargetLoweringInfo(),
518                            &DAG.getTarget().Options, Depth+1))
519       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
520                          GetNegatedExpression(Op.getOperand(0), DAG,
521                                               LegalOperations, Depth+1),
522                          Op.getOperand(1));
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
525                        GetNegatedExpression(Op.getOperand(1), DAG,
526                                             LegalOperations, Depth+1),
527                        Op.getOperand(0));
528   case ISD::FSUB:
529     // We can't turn -(A-B) into B-A when we honor signed zeros.
530     assert(DAG.getTarget().Options.UnsafeFPMath);
531
532     // fold (fneg (fsub 0, B)) -> B
533     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
534       if (N0CFP->getValueAPF().isZero())
535         return Op.getOperand(1);
536
537     // fold (fneg (fsub A, B)) -> (fsub B, A)
538     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
539                        Op.getOperand(1), Op.getOperand(0));
540
541   case ISD::FMUL:
542   case ISD::FDIV:
543     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
544
545     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
546     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
547                            DAG.getTargetLoweringInfo(),
548                            &DAG.getTarget().Options, Depth+1))
549       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
550                          GetNegatedExpression(Op.getOperand(0), DAG,
551                                               LegalOperations, Depth+1),
552                          Op.getOperand(1));
553
554     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
555     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
556                        Op.getOperand(0),
557                        GetNegatedExpression(Op.getOperand(1), DAG,
558                                             LegalOperations, Depth+1));
559
560   case ISD::FP_EXTEND:
561   case ISD::FSIN:
562     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563                        GetNegatedExpression(Op.getOperand(0), DAG,
564                                             LegalOperations, Depth+1));
565   case ISD::FP_ROUND:
566       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
567                          GetNegatedExpression(Op.getOperand(0), DAG,
568                                               LegalOperations, Depth+1),
569                          Op.getOperand(1));
570   }
571 }
572
573
574 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
575 // that selects between the values 1 and 0, making it equivalent to a setcc.
576 // Also, set the incoming LHS, RHS, and CC references to the appropriate
577 // nodes based on the type of node we are checking.  This simplifies life a
578 // bit for the callers.
579 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
580                               SDValue &CC) {
581   if (N.getOpcode() == ISD::SETCC) {
582     LHS = N.getOperand(0);
583     RHS = N.getOperand(1);
584     CC  = N.getOperand(2);
585     return true;
586   }
587   if (N.getOpcode() == ISD::SELECT_CC &&
588       N.getOperand(2).getOpcode() == ISD::Constant &&
589       N.getOperand(3).getOpcode() == ISD::Constant &&
590       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
591       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
592     LHS = N.getOperand(0);
593     RHS = N.getOperand(1);
594     CC  = N.getOperand(4);
595     return true;
596   }
597   return false;
598 }
599
600 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
601 // one use.  If this is true, it allows the users to invert the operation for
602 // free when it is profitable to do so.
603 static bool isOneUseSetCC(SDValue N) {
604   SDValue N0, N1, N2;
605   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
606     return true;
607   return false;
608 }
609
610 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
611 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
612   if (isa<ConstantSDNode>(N))
613     return N.getNode();
614   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
615   if(BV && BV->isConstant())
616     return BV;
617   return NULL;
618 }
619
620 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
621                                     SDValue N0, SDValue N1) {
622   EVT VT = N0.getValueType();
623   if (N0.getOpcode() == Opc) {
624     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
625       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
626         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
627         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
628         if (!OpNode.getNode())
629           return SDValue();
630         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
631       }
632       if (N0.hasOneUse()) {
633         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
634         // use
635         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
636         if (!OpNode.getNode())
637           return SDValue();
638         AddToWorkList(OpNode.getNode());
639         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
640       }
641     }
642   }
643
644   if (N1.getOpcode() == Opc) {
645     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
646       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
647         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
648         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
649         if (!OpNode.getNode())
650           return SDValue();
651         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
652       }
653       if (N1.hasOneUse()) {
654         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
655         // use
656         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
657         if (!OpNode.getNode())
658           return SDValue();
659         AddToWorkList(OpNode.getNode());
660         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
661       }
662     }
663   }
664
665   return SDValue();
666 }
667
668 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
669                                bool AddTo) {
670   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
671   ++NodesCombined;
672   DEBUG(dbgs() << "\nReplacing.1 ";
673         N->dump(&DAG);
674         dbgs() << "\nWith: ";
675         To[0].getNode()->dump(&DAG);
676         dbgs() << " and " << NumTo-1 << " other values\n";
677         for (unsigned i = 0, e = NumTo; i != e; ++i)
678           assert((!To[i].getNode() ||
679                   N->getValueType(i) == To[i].getValueType()) &&
680                  "Cannot combine value to value of different type!"));
681   WorkListRemover DeadNodes(*this);
682   DAG.ReplaceAllUsesWith(N, To);
683   if (AddTo) {
684     // Push the new nodes and any users onto the worklist
685     for (unsigned i = 0, e = NumTo; i != e; ++i) {
686       if (To[i].getNode()) {
687         AddToWorkList(To[i].getNode());
688         AddUsersToWorkList(To[i].getNode());
689       }
690     }
691   }
692
693   // Finally, if the node is now dead, remove it from the graph.  The node
694   // may not be dead if the replacement process recursively simplified to
695   // something else needing this node.
696   if (N->use_empty()) {
697     // Nodes can be reintroduced into the worklist.  Make sure we do not
698     // process a node that has been replaced.
699     removeFromWorkList(N);
700
701     // Finally, since the node is now dead, remove it from the graph.
702     DAG.DeleteNode(N);
703   }
704   return SDValue(N, 0);
705 }
706
707 void DAGCombiner::
708 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
709   // Replace all uses.  If any nodes become isomorphic to other nodes and
710   // are deleted, make sure to remove them from our worklist.
711   WorkListRemover DeadNodes(*this);
712   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
713
714   // Push the new node and any (possibly new) users onto the worklist.
715   AddToWorkList(TLO.New.getNode());
716   AddUsersToWorkList(TLO.New.getNode());
717
718   // Finally, if the node is now dead, remove it from the graph.  The node
719   // may not be dead if the replacement process recursively simplified to
720   // something else needing this node.
721   if (TLO.Old.getNode()->use_empty()) {
722     removeFromWorkList(TLO.Old.getNode());
723
724     // If the operands of this node are only used by the node, they will now
725     // be dead.  Make sure to visit them first to delete dead nodes early.
726     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
727       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
728         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
729
730     DAG.DeleteNode(TLO.Old.getNode());
731   }
732 }
733
734 /// SimplifyDemandedBits - Check the specified integer node value to see if
735 /// it can be simplified or if things it uses can be simplified by bit
736 /// propagation.  If so, return true.
737 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
738   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
739   APInt KnownZero, KnownOne;
740   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
741     return false;
742
743   // Revisit the node.
744   AddToWorkList(Op.getNode());
745
746   // Replace the old value with the new one.
747   ++NodesCombined;
748   DEBUG(dbgs() << "\nReplacing.2 ";
749         TLO.Old.getNode()->dump(&DAG);
750         dbgs() << "\nWith: ";
751         TLO.New.getNode()->dump(&DAG);
752         dbgs() << '\n');
753
754   CommitTargetLoweringOpt(TLO);
755   return true;
756 }
757
758 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
759   SDLoc dl(Load);
760   EVT VT = Load->getValueType(0);
761   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
762
763   DEBUG(dbgs() << "\nReplacing.9 ";
764         Load->dump(&DAG);
765         dbgs() << "\nWith: ";
766         Trunc.getNode()->dump(&DAG);
767         dbgs() << '\n');
768   WorkListRemover DeadNodes(*this);
769   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
770   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
771   removeFromWorkList(Load);
772   DAG.DeleteNode(Load);
773   AddToWorkList(Trunc.getNode());
774 }
775
776 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
777   Replace = false;
778   SDLoc dl(Op);
779   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
780     EVT MemVT = LD->getMemoryVT();
781     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
782       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
783                                                   : ISD::EXTLOAD)
784       : LD->getExtensionType();
785     Replace = true;
786     return DAG.getExtLoad(ExtType, dl, PVT,
787                           LD->getChain(), LD->getBasePtr(),
788                           MemVT, LD->getMemOperand());
789   }
790
791   unsigned Opc = Op.getOpcode();
792   switch (Opc) {
793   default: break;
794   case ISD::AssertSext:
795     return DAG.getNode(ISD::AssertSext, dl, PVT,
796                        SExtPromoteOperand(Op.getOperand(0), PVT),
797                        Op.getOperand(1));
798   case ISD::AssertZext:
799     return DAG.getNode(ISD::AssertZext, dl, PVT,
800                        ZExtPromoteOperand(Op.getOperand(0), PVT),
801                        Op.getOperand(1));
802   case ISD::Constant: {
803     unsigned ExtOpc =
804       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
805     return DAG.getNode(ExtOpc, dl, PVT, Op);
806   }
807   }
808
809   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
810     return SDValue();
811   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
812 }
813
814 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
815   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
816     return SDValue();
817   EVT OldVT = Op.getValueType();
818   SDLoc dl(Op);
819   bool Replace = false;
820   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
821   if (NewOp.getNode() == 0)
822     return SDValue();
823   AddToWorkList(NewOp.getNode());
824
825   if (Replace)
826     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
827   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
828                      DAG.getValueType(OldVT));
829 }
830
831 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
832   EVT OldVT = Op.getValueType();
833   SDLoc dl(Op);
834   bool Replace = false;
835   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
836   if (NewOp.getNode() == 0)
837     return SDValue();
838   AddToWorkList(NewOp.getNode());
839
840   if (Replace)
841     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
842   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
843 }
844
845 /// PromoteIntBinOp - Promote the specified integer binary operation if the
846 /// target indicates it is beneficial. e.g. On x86, it's usually better to
847 /// promote i16 operations to i32 since i16 instructions are longer.
848 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
849   if (!LegalOperations)
850     return SDValue();
851
852   EVT VT = Op.getValueType();
853   if (VT.isVector() || !VT.isInteger())
854     return SDValue();
855
856   // If operation type is 'undesirable', e.g. i16 on x86, consider
857   // promoting it.
858   unsigned Opc = Op.getOpcode();
859   if (TLI.isTypeDesirableForOp(Opc, VT))
860     return SDValue();
861
862   EVT PVT = VT;
863   // Consult target whether it is a good idea to promote this operation and
864   // what's the right type to promote it to.
865   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
866     assert(PVT != VT && "Don't know what type to promote to!");
867
868     bool Replace0 = false;
869     SDValue N0 = Op.getOperand(0);
870     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
871     if (NN0.getNode() == 0)
872       return SDValue();
873
874     bool Replace1 = false;
875     SDValue N1 = Op.getOperand(1);
876     SDValue NN1;
877     if (N0 == N1)
878       NN1 = NN0;
879     else {
880       NN1 = PromoteOperand(N1, PVT, Replace1);
881       if (NN1.getNode() == 0)
882         return SDValue();
883     }
884
885     AddToWorkList(NN0.getNode());
886     if (NN1.getNode())
887       AddToWorkList(NN1.getNode());
888
889     if (Replace0)
890       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
891     if (Replace1)
892       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
893
894     DEBUG(dbgs() << "\nPromoting ";
895           Op.getNode()->dump(&DAG));
896     SDLoc dl(Op);
897     return DAG.getNode(ISD::TRUNCATE, dl, VT,
898                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
899   }
900   return SDValue();
901 }
902
903 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
904 /// target indicates it is beneficial. e.g. On x86, it's usually better to
905 /// promote i16 operations to i32 since i16 instructions are longer.
906 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
907   if (!LegalOperations)
908     return SDValue();
909
910   EVT VT = Op.getValueType();
911   if (VT.isVector() || !VT.isInteger())
912     return SDValue();
913
914   // If operation type is 'undesirable', e.g. i16 on x86, consider
915   // promoting it.
916   unsigned Opc = Op.getOpcode();
917   if (TLI.isTypeDesirableForOp(Opc, VT))
918     return SDValue();
919
920   EVT PVT = VT;
921   // Consult target whether it is a good idea to promote this operation and
922   // what's the right type to promote it to.
923   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924     assert(PVT != VT && "Don't know what type to promote to!");
925
926     bool Replace = false;
927     SDValue N0 = Op.getOperand(0);
928     if (Opc == ISD::SRA)
929       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
930     else if (Opc == ISD::SRL)
931       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
932     else
933       N0 = PromoteOperand(N0, PVT, Replace);
934     if (N0.getNode() == 0)
935       return SDValue();
936
937     AddToWorkList(N0.getNode());
938     if (Replace)
939       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
940
941     DEBUG(dbgs() << "\nPromoting ";
942           Op.getNode()->dump(&DAG));
943     SDLoc dl(Op);
944     return DAG.getNode(ISD::TRUNCATE, dl, VT,
945                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
946   }
947   return SDValue();
948 }
949
950 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
951   if (!LegalOperations)
952     return SDValue();
953
954   EVT VT = Op.getValueType();
955   if (VT.isVector() || !VT.isInteger())
956     return SDValue();
957
958   // If operation type is 'undesirable', e.g. i16 on x86, consider
959   // promoting it.
960   unsigned Opc = Op.getOpcode();
961   if (TLI.isTypeDesirableForOp(Opc, VT))
962     return SDValue();
963
964   EVT PVT = VT;
965   // Consult target whether it is a good idea to promote this operation and
966   // what's the right type to promote it to.
967   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
968     assert(PVT != VT && "Don't know what type to promote to!");
969     // fold (aext (aext x)) -> (aext x)
970     // fold (aext (zext x)) -> (zext x)
971     // fold (aext (sext x)) -> (sext x)
972     DEBUG(dbgs() << "\nPromoting ";
973           Op.getNode()->dump(&DAG));
974     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
975   }
976   return SDValue();
977 }
978
979 bool DAGCombiner::PromoteLoad(SDValue Op) {
980   if (!LegalOperations)
981     return false;
982
983   EVT VT = Op.getValueType();
984   if (VT.isVector() || !VT.isInteger())
985     return false;
986
987   // If operation type is 'undesirable', e.g. i16 on x86, consider
988   // promoting it.
989   unsigned Opc = Op.getOpcode();
990   if (TLI.isTypeDesirableForOp(Opc, VT))
991     return false;
992
993   EVT PVT = VT;
994   // Consult target whether it is a good idea to promote this operation and
995   // what's the right type to promote it to.
996   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
997     assert(PVT != VT && "Don't know what type to promote to!");
998
999     SDLoc dl(Op);
1000     SDNode *N = Op.getNode();
1001     LoadSDNode *LD = cast<LoadSDNode>(N);
1002     EVT MemVT = LD->getMemoryVT();
1003     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1004       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1005                                                   : ISD::EXTLOAD)
1006       : LD->getExtensionType();
1007     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1008                                    LD->getChain(), LD->getBasePtr(),
1009                                    MemVT, LD->getMemOperand());
1010     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1011
1012     DEBUG(dbgs() << "\nPromoting ";
1013           N->dump(&DAG);
1014           dbgs() << "\nTo: ";
1015           Result.getNode()->dump(&DAG);
1016           dbgs() << '\n');
1017     WorkListRemover DeadNodes(*this);
1018     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1019     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1020     removeFromWorkList(N);
1021     DAG.DeleteNode(N);
1022     AddToWorkList(Result.getNode());
1023     return true;
1024   }
1025   return false;
1026 }
1027
1028
1029 //===----------------------------------------------------------------------===//
1030 //  Main DAG Combiner implementation
1031 //===----------------------------------------------------------------------===//
1032
1033 void DAGCombiner::Run(CombineLevel AtLevel) {
1034   // set the instance variables, so that the various visit routines may use it.
1035   Level = AtLevel;
1036   LegalOperations = Level >= AfterLegalizeVectorOps;
1037   LegalTypes = Level >= AfterLegalizeTypes;
1038
1039   // Add all the dag nodes to the worklist.
1040   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1041        E = DAG.allnodes_end(); I != E; ++I)
1042     AddToWorkList(I);
1043
1044   // Create a dummy node (which is not added to allnodes), that adds a reference
1045   // to the root node, preventing it from being deleted, and tracking any
1046   // changes of the root.
1047   HandleSDNode Dummy(DAG.getRoot());
1048
1049   // The root of the dag may dangle to deleted nodes until the dag combiner is
1050   // done.  Set it to null to avoid confusion.
1051   DAG.setRoot(SDValue());
1052
1053   // while the worklist isn't empty, find a node and
1054   // try and combine it.
1055   while (!WorkListContents.empty()) {
1056     SDNode *N;
1057     // The WorkListOrder holds the SDNodes in order, but it may contain
1058     // duplicates.
1059     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1060     // worklist *should* contain, and check the node we want to visit is should
1061     // actually be visited.
1062     do {
1063       N = WorkListOrder.pop_back_val();
1064     } while (!WorkListContents.erase(N));
1065
1066     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1067     // N is deleted from the DAG, since they too may now be dead or may have a
1068     // reduced number of uses, allowing other xforms.
1069     if (N->use_empty() && N != &Dummy) {
1070       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1071         AddToWorkList(N->getOperand(i).getNode());
1072
1073       DAG.DeleteNode(N);
1074       continue;
1075     }
1076
1077     SDValue RV = combine(N);
1078
1079     if (RV.getNode() == 0)
1080       continue;
1081
1082     ++NodesCombined;
1083
1084     // If we get back the same node we passed in, rather than a new node or
1085     // zero, we know that the node must have defined multiple values and
1086     // CombineTo was used.  Since CombineTo takes care of the worklist
1087     // mechanics for us, we have no work to do in this case.
1088     if (RV.getNode() == N)
1089       continue;
1090
1091     assert(N->getOpcode() != ISD::DELETED_NODE &&
1092            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1093            "Node was deleted but visit returned new node!");
1094
1095     DEBUG(dbgs() << "\nReplacing.3 ";
1096           N->dump(&DAG);
1097           dbgs() << "\nWith: ";
1098           RV.getNode()->dump(&DAG);
1099           dbgs() << '\n');
1100
1101     // Transfer debug value.
1102     DAG.TransferDbgValues(SDValue(N, 0), RV);
1103     WorkListRemover DeadNodes(*this);
1104     if (N->getNumValues() == RV.getNode()->getNumValues())
1105       DAG.ReplaceAllUsesWith(N, RV.getNode());
1106     else {
1107       assert(N->getValueType(0) == RV.getValueType() &&
1108              N->getNumValues() == 1 && "Type mismatch");
1109       SDValue OpV = RV;
1110       DAG.ReplaceAllUsesWith(N, &OpV);
1111     }
1112
1113     // Push the new node and any users onto the worklist
1114     AddToWorkList(RV.getNode());
1115     AddUsersToWorkList(RV.getNode());
1116
1117     // Add any uses of the old node to the worklist in case this node is the
1118     // last one that uses them.  They may become dead after this node is
1119     // deleted.
1120     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1121       AddToWorkList(N->getOperand(i).getNode());
1122
1123     // Finally, if the node is now dead, remove it from the graph.  The node
1124     // may not be dead if the replacement process recursively simplified to
1125     // something else needing this node.
1126     if (N->use_empty()) {
1127       // Nodes can be reintroduced into the worklist.  Make sure we do not
1128       // process a node that has been replaced.
1129       removeFromWorkList(N);
1130
1131       // Finally, since the node is now dead, remove it from the graph.
1132       DAG.DeleteNode(N);
1133     }
1134   }
1135
1136   // If the root changed (e.g. it was a dead load, update the root).
1137   DAG.setRoot(Dummy.getValue());
1138   DAG.RemoveDeadNodes();
1139 }
1140
1141 SDValue DAGCombiner::visit(SDNode *N) {
1142   switch (N->getOpcode()) {
1143   default: break;
1144   case ISD::TokenFactor:        return visitTokenFactor(N);
1145   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1146   case ISD::ADD:                return visitADD(N);
1147   case ISD::SUB:                return visitSUB(N);
1148   case ISD::ADDC:               return visitADDC(N);
1149   case ISD::SUBC:               return visitSUBC(N);
1150   case ISD::ADDE:               return visitADDE(N);
1151   case ISD::SUBE:               return visitSUBE(N);
1152   case ISD::MUL:                return visitMUL(N);
1153   case ISD::SDIV:               return visitSDIV(N);
1154   case ISD::UDIV:               return visitUDIV(N);
1155   case ISD::SREM:               return visitSREM(N);
1156   case ISD::UREM:               return visitUREM(N);
1157   case ISD::MULHU:              return visitMULHU(N);
1158   case ISD::MULHS:              return visitMULHS(N);
1159   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1160   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1161   case ISD::SMULO:              return visitSMULO(N);
1162   case ISD::UMULO:              return visitUMULO(N);
1163   case ISD::SDIVREM:            return visitSDIVREM(N);
1164   case ISD::UDIVREM:            return visitUDIVREM(N);
1165   case ISD::AND:                return visitAND(N);
1166   case ISD::OR:                 return visitOR(N);
1167   case ISD::XOR:                return visitXOR(N);
1168   case ISD::SHL:                return visitSHL(N);
1169   case ISD::SRA:                return visitSRA(N);
1170   case ISD::SRL:                return visitSRL(N);
1171   case ISD::CTLZ:               return visitCTLZ(N);
1172   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1173   case ISD::CTTZ:               return visitCTTZ(N);
1174   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1175   case ISD::CTPOP:              return visitCTPOP(N);
1176   case ISD::SELECT:             return visitSELECT(N);
1177   case ISD::VSELECT:            return visitVSELECT(N);
1178   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1179   case ISD::SETCC:              return visitSETCC(N);
1180   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1181   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1182   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1183   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1184   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1185   case ISD::BITCAST:            return visitBITCAST(N);
1186   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1187   case ISD::FADD:               return visitFADD(N);
1188   case ISD::FSUB:               return visitFSUB(N);
1189   case ISD::FMUL:               return visitFMUL(N);
1190   case ISD::FMA:                return visitFMA(N);
1191   case ISD::FDIV:               return visitFDIV(N);
1192   case ISD::FREM:               return visitFREM(N);
1193   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1194   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1195   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1196   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1197   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1198   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1199   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1200   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1201   case ISD::FNEG:               return visitFNEG(N);
1202   case ISD::FABS:               return visitFABS(N);
1203   case ISD::FFLOOR:             return visitFFLOOR(N);
1204   case ISD::FCEIL:              return visitFCEIL(N);
1205   case ISD::FTRUNC:             return visitFTRUNC(N);
1206   case ISD::BRCOND:             return visitBRCOND(N);
1207   case ISD::BR_CC:              return visitBR_CC(N);
1208   case ISD::LOAD:               return visitLOAD(N);
1209   case ISD::STORE:              return visitSTORE(N);
1210   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1211   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1212   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1213   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1214   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1215   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1216   }
1217   return SDValue();
1218 }
1219
1220 SDValue DAGCombiner::combine(SDNode *N) {
1221   SDValue RV = visit(N);
1222
1223   // If nothing happened, try a target-specific DAG combine.
1224   if (RV.getNode() == 0) {
1225     assert(N->getOpcode() != ISD::DELETED_NODE &&
1226            "Node was deleted but visit returned NULL!");
1227
1228     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1229         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1230
1231       // Expose the DAG combiner to the target combiner impls.
1232       TargetLowering::DAGCombinerInfo
1233         DagCombineInfo(DAG, Level, false, this);
1234
1235       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1236     }
1237   }
1238
1239   // If nothing happened still, try promoting the operation.
1240   if (RV.getNode() == 0) {
1241     switch (N->getOpcode()) {
1242     default: break;
1243     case ISD::ADD:
1244     case ISD::SUB:
1245     case ISD::MUL:
1246     case ISD::AND:
1247     case ISD::OR:
1248     case ISD::XOR:
1249       RV = PromoteIntBinOp(SDValue(N, 0));
1250       break;
1251     case ISD::SHL:
1252     case ISD::SRA:
1253     case ISD::SRL:
1254       RV = PromoteIntShiftOp(SDValue(N, 0));
1255       break;
1256     case ISD::SIGN_EXTEND:
1257     case ISD::ZERO_EXTEND:
1258     case ISD::ANY_EXTEND:
1259       RV = PromoteExtend(SDValue(N, 0));
1260       break;
1261     case ISD::LOAD:
1262       if (PromoteLoad(SDValue(N, 0)))
1263         RV = SDValue(N, 0);
1264       break;
1265     }
1266   }
1267
1268   // If N is a commutative binary node, try commuting it to enable more
1269   // sdisel CSE.
1270   if (RV.getNode() == 0 &&
1271       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1272       N->getNumValues() == 1) {
1273     SDValue N0 = N->getOperand(0);
1274     SDValue N1 = N->getOperand(1);
1275
1276     // Constant operands are canonicalized to RHS.
1277     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1278       SDValue Ops[] = { N1, N0 };
1279       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1280                                             Ops, 2);
1281       if (CSENode)
1282         return SDValue(CSENode, 0);
1283     }
1284   }
1285
1286   return RV;
1287 }
1288
1289 /// getInputChainForNode - Given a node, return its input chain if it has one,
1290 /// otherwise return a null sd operand.
1291 static SDValue getInputChainForNode(SDNode *N) {
1292   if (unsigned NumOps = N->getNumOperands()) {
1293     if (N->getOperand(0).getValueType() == MVT::Other)
1294       return N->getOperand(0);
1295     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1296       return N->getOperand(NumOps-1);
1297     for (unsigned i = 1; i < NumOps-1; ++i)
1298       if (N->getOperand(i).getValueType() == MVT::Other)
1299         return N->getOperand(i);
1300   }
1301   return SDValue();
1302 }
1303
1304 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1305   // If N has two operands, where one has an input chain equal to the other,
1306   // the 'other' chain is redundant.
1307   if (N->getNumOperands() == 2) {
1308     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1309       return N->getOperand(0);
1310     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1311       return N->getOperand(1);
1312   }
1313
1314   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1315   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1316   SmallPtrSet<SDNode*, 16> SeenOps;
1317   bool Changed = false;             // If we should replace this token factor.
1318
1319   // Start out with this token factor.
1320   TFs.push_back(N);
1321
1322   // Iterate through token factors.  The TFs grows when new token factors are
1323   // encountered.
1324   for (unsigned i = 0; i < TFs.size(); ++i) {
1325     SDNode *TF = TFs[i];
1326
1327     // Check each of the operands.
1328     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1329       SDValue Op = TF->getOperand(i);
1330
1331       switch (Op.getOpcode()) {
1332       case ISD::EntryToken:
1333         // Entry tokens don't need to be added to the list. They are
1334         // rededundant.
1335         Changed = true;
1336         break;
1337
1338       case ISD::TokenFactor:
1339         if (Op.hasOneUse() &&
1340             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1341           // Queue up for processing.
1342           TFs.push_back(Op.getNode());
1343           // Clean up in case the token factor is removed.
1344           AddToWorkList(Op.getNode());
1345           Changed = true;
1346           break;
1347         }
1348         // Fall thru
1349
1350       default:
1351         // Only add if it isn't already in the list.
1352         if (SeenOps.insert(Op.getNode()))
1353           Ops.push_back(Op);
1354         else
1355           Changed = true;
1356         break;
1357       }
1358     }
1359   }
1360
1361   SDValue Result;
1362
1363   // If we've change things around then replace token factor.
1364   if (Changed) {
1365     if (Ops.empty()) {
1366       // The entry token is the only possible outcome.
1367       Result = DAG.getEntryNode();
1368     } else {
1369       // New and improved token factor.
1370       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1371                            MVT::Other, &Ops[0], Ops.size());
1372     }
1373
1374     // Don't add users to work list.
1375     return CombineTo(N, Result, false);
1376   }
1377
1378   return Result;
1379 }
1380
1381 /// MERGE_VALUES can always be eliminated.
1382 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1383   WorkListRemover DeadNodes(*this);
1384   // Replacing results may cause a different MERGE_VALUES to suddenly
1385   // be CSE'd with N, and carry its uses with it. Iterate until no
1386   // uses remain, to ensure that the node can be safely deleted.
1387   // First add the users of this node to the work list so that they
1388   // can be tried again once they have new operands.
1389   AddUsersToWorkList(N);
1390   do {
1391     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1392       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1393   } while (!N->use_empty());
1394   removeFromWorkList(N);
1395   DAG.DeleteNode(N);
1396   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1397 }
1398
1399 static
1400 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1401                               SelectionDAG &DAG) {
1402   EVT VT = N0.getValueType();
1403   SDValue N00 = N0.getOperand(0);
1404   SDValue N01 = N0.getOperand(1);
1405   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1406
1407   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1408       isa<ConstantSDNode>(N00.getOperand(1))) {
1409     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1410     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1411                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1412                                  N00.getOperand(0), N01),
1413                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1414                                  N00.getOperand(1), N01));
1415     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1416   }
1417
1418   return SDValue();
1419 }
1420
1421 SDValue DAGCombiner::visitADD(SDNode *N) {
1422   SDValue N0 = N->getOperand(0);
1423   SDValue N1 = N->getOperand(1);
1424   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1425   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1426   EVT VT = N0.getValueType();
1427
1428   // fold vector ops
1429   if (VT.isVector()) {
1430     SDValue FoldedVOp = SimplifyVBinOp(N);
1431     if (FoldedVOp.getNode()) return FoldedVOp;
1432
1433     // fold (add x, 0) -> x, vector edition
1434     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1435       return N0;
1436     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1437       return N1;
1438   }
1439
1440   // fold (add x, undef) -> undef
1441   if (N0.getOpcode() == ISD::UNDEF)
1442     return N0;
1443   if (N1.getOpcode() == ISD::UNDEF)
1444     return N1;
1445   // fold (add c1, c2) -> c1+c2
1446   if (N0C && N1C)
1447     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1448   // canonicalize constant to RHS
1449   if (N0C && !N1C)
1450     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1451   // fold (add x, 0) -> x
1452   if (N1C && N1C->isNullValue())
1453     return N0;
1454   // fold (add Sym, c) -> Sym+c
1455   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1456     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1457         GA->getOpcode() == ISD::GlobalAddress)
1458       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1459                                   GA->getOffset() +
1460                                     (uint64_t)N1C->getSExtValue());
1461   // fold ((c1-A)+c2) -> (c1+c2)-A
1462   if (N1C && N0.getOpcode() == ISD::SUB)
1463     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1464       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1465                          DAG.getConstant(N1C->getAPIntValue()+
1466                                          N0C->getAPIntValue(), VT),
1467                          N0.getOperand(1));
1468   // reassociate add
1469   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1470   if (RADD.getNode() != 0)
1471     return RADD;
1472   // fold ((0-A) + B) -> B-A
1473   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1474       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1475     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1476   // fold (A + (0-B)) -> A-B
1477   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1478       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1479     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1480   // fold (A+(B-A)) -> B
1481   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1482     return N1.getOperand(0);
1483   // fold ((B-A)+A) -> B
1484   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1485     return N0.getOperand(0);
1486   // fold (A+(B-(A+C))) to (B-C)
1487   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1488       N0 == N1.getOperand(1).getOperand(0))
1489     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1490                        N1.getOperand(1).getOperand(1));
1491   // fold (A+(B-(C+A))) to (B-C)
1492   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1493       N0 == N1.getOperand(1).getOperand(1))
1494     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1495                        N1.getOperand(1).getOperand(0));
1496   // fold (A+((B-A)+or-C)) to (B+or-C)
1497   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1498       N1.getOperand(0).getOpcode() == ISD::SUB &&
1499       N0 == N1.getOperand(0).getOperand(1))
1500     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1501                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1502
1503   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1504   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1505     SDValue N00 = N0.getOperand(0);
1506     SDValue N01 = N0.getOperand(1);
1507     SDValue N10 = N1.getOperand(0);
1508     SDValue N11 = N1.getOperand(1);
1509
1510     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1511       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1512                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1513                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1514   }
1515
1516   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1517     return SDValue(N, 0);
1518
1519   // fold (a+b) -> (a|b) iff a and b share no bits.
1520   if (VT.isInteger() && !VT.isVector()) {
1521     APInt LHSZero, LHSOne;
1522     APInt RHSZero, RHSOne;
1523     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1524
1525     if (LHSZero.getBoolValue()) {
1526       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1527
1528       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1529       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1530       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1531         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1532     }
1533   }
1534
1535   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1536   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1537     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1538     if (Result.getNode()) return Result;
1539   }
1540   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1541     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1542     if (Result.getNode()) return Result;
1543   }
1544
1545   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1546   if (N1.getOpcode() == ISD::SHL &&
1547       N1.getOperand(0).getOpcode() == ISD::SUB)
1548     if (ConstantSDNode *C =
1549           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1550       if (C->getAPIntValue() == 0)
1551         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1552                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1553                                        N1.getOperand(0).getOperand(1),
1554                                        N1.getOperand(1)));
1555   if (N0.getOpcode() == ISD::SHL &&
1556       N0.getOperand(0).getOpcode() == ISD::SUB)
1557     if (ConstantSDNode *C =
1558           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1559       if (C->getAPIntValue() == 0)
1560         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1561                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1562                                        N0.getOperand(0).getOperand(1),
1563                                        N0.getOperand(1)));
1564
1565   if (N1.getOpcode() == ISD::AND) {
1566     SDValue AndOp0 = N1.getOperand(0);
1567     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1568     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1569     unsigned DestBits = VT.getScalarType().getSizeInBits();
1570
1571     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1572     // and similar xforms where the inner op is either ~0 or 0.
1573     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1574       SDLoc DL(N);
1575       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1576     }
1577   }
1578
1579   // add (sext i1), X -> sub X, (zext i1)
1580   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1581       N0.getOperand(0).getValueType() == MVT::i1 &&
1582       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1583     SDLoc DL(N);
1584     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1585     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1586   }
1587
1588   return SDValue();
1589 }
1590
1591 SDValue DAGCombiner::visitADDC(SDNode *N) {
1592   SDValue N0 = N->getOperand(0);
1593   SDValue N1 = N->getOperand(1);
1594   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1596   EVT VT = N0.getValueType();
1597
1598   // If the flag result is dead, turn this into an ADD.
1599   if (!N->hasAnyUseOfValue(1))
1600     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1601                      DAG.getNode(ISD::CARRY_FALSE,
1602                                  SDLoc(N), MVT::Glue));
1603
1604   // canonicalize constant to RHS.
1605   if (N0C && !N1C)
1606     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1607
1608   // fold (addc x, 0) -> x + no carry out
1609   if (N1C && N1C->isNullValue())
1610     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1611                                         SDLoc(N), MVT::Glue));
1612
1613   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1614   APInt LHSZero, LHSOne;
1615   APInt RHSZero, RHSOne;
1616   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1617
1618   if (LHSZero.getBoolValue()) {
1619     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1620
1621     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1622     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1623     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1624       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1625                        DAG.getNode(ISD::CARRY_FALSE,
1626                                    SDLoc(N), MVT::Glue));
1627   }
1628
1629   return SDValue();
1630 }
1631
1632 SDValue DAGCombiner::visitADDE(SDNode *N) {
1633   SDValue N0 = N->getOperand(0);
1634   SDValue N1 = N->getOperand(1);
1635   SDValue CarryIn = N->getOperand(2);
1636   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1637   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1638
1639   // canonicalize constant to RHS
1640   if (N0C && !N1C)
1641     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1642                        N1, N0, CarryIn);
1643
1644   // fold (adde x, y, false) -> (addc x, y)
1645   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1646     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1647
1648   return SDValue();
1649 }
1650
1651 // Since it may not be valid to emit a fold to zero for vector initializers
1652 // check if we can before folding.
1653 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1654                              SelectionDAG &DAG,
1655                              bool LegalOperations, bool LegalTypes) {
1656   if (!VT.isVector())
1657     return DAG.getConstant(0, VT);
1658   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1659     return DAG.getConstant(0, VT);
1660   return SDValue();
1661 }
1662
1663 SDValue DAGCombiner::visitSUB(SDNode *N) {
1664   SDValue N0 = N->getOperand(0);
1665   SDValue N1 = N->getOperand(1);
1666   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1667   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1668   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1669     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1670   EVT VT = N0.getValueType();
1671
1672   // fold vector ops
1673   if (VT.isVector()) {
1674     SDValue FoldedVOp = SimplifyVBinOp(N);
1675     if (FoldedVOp.getNode()) return FoldedVOp;
1676
1677     // fold (sub x, 0) -> x, vector edition
1678     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1679       return N0;
1680   }
1681
1682   // fold (sub x, x) -> 0
1683   // FIXME: Refactor this and xor and other similar operations together.
1684   if (N0 == N1)
1685     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1686   // fold (sub c1, c2) -> c1-c2
1687   if (N0C && N1C)
1688     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1689   // fold (sub x, c) -> (add x, -c)
1690   if (N1C)
1691     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1692                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1693   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1694   if (N0C && N0C->isAllOnesValue())
1695     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1696   // fold A-(A-B) -> B
1697   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1698     return N1.getOperand(1);
1699   // fold (A+B)-A -> B
1700   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1701     return N0.getOperand(1);
1702   // fold (A+B)-B -> A
1703   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1704     return N0.getOperand(0);
1705   // fold C2-(A+C1) -> (C2-C1)-A
1706   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1707     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1708                                    VT);
1709     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1710                        N1.getOperand(0));
1711   }
1712   // fold ((A+(B+or-C))-B) -> A+or-C
1713   if (N0.getOpcode() == ISD::ADD &&
1714       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1715        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1716       N0.getOperand(1).getOperand(0) == N1)
1717     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1718                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1719   // fold ((A+(C+B))-B) -> A+C
1720   if (N0.getOpcode() == ISD::ADD &&
1721       N0.getOperand(1).getOpcode() == ISD::ADD &&
1722       N0.getOperand(1).getOperand(1) == N1)
1723     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1724                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1725   // fold ((A-(B-C))-C) -> A-B
1726   if (N0.getOpcode() == ISD::SUB &&
1727       N0.getOperand(1).getOpcode() == ISD::SUB &&
1728       N0.getOperand(1).getOperand(1) == N1)
1729     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1731
1732   // If either operand of a sub is undef, the result is undef
1733   if (N0.getOpcode() == ISD::UNDEF)
1734     return N0;
1735   if (N1.getOpcode() == ISD::UNDEF)
1736     return N1;
1737
1738   // If the relocation model supports it, consider symbol offsets.
1739   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1740     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1741       // fold (sub Sym, c) -> Sym-c
1742       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1743         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1744                                     GA->getOffset() -
1745                                       (uint64_t)N1C->getSExtValue());
1746       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1747       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1748         if (GA->getGlobal() == GB->getGlobal())
1749           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1750                                  VT);
1751     }
1752
1753   return SDValue();
1754 }
1755
1756 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1757   SDValue N0 = N->getOperand(0);
1758   SDValue N1 = N->getOperand(1);
1759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761   EVT VT = N0.getValueType();
1762
1763   // If the flag result is dead, turn this into an SUB.
1764   if (!N->hasAnyUseOfValue(1))
1765     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1766                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1767                                  MVT::Glue));
1768
1769   // fold (subc x, x) -> 0 + no borrow
1770   if (N0 == N1)
1771     return CombineTo(N, DAG.getConstant(0, VT),
1772                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1773                                  MVT::Glue));
1774
1775   // fold (subc x, 0) -> x + no borrow
1776   if (N1C && N1C->isNullValue())
1777     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1778                                         MVT::Glue));
1779
1780   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1781   if (N0C && N0C->isAllOnesValue())
1782     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1783                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1784                                  MVT::Glue));
1785
1786   return SDValue();
1787 }
1788
1789 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1790   SDValue N0 = N->getOperand(0);
1791   SDValue N1 = N->getOperand(1);
1792   SDValue CarryIn = N->getOperand(2);
1793
1794   // fold (sube x, y, false) -> (subc x, y)
1795   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1796     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1797
1798   return SDValue();
1799 }
1800
1801 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1802 /// elements are all the same constant or undefined.
1803 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1804   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1805   if (!C)
1806     return false;
1807
1808   APInt SplatUndef;
1809   unsigned SplatBitSize;
1810   bool HasAnyUndefs;
1811   EVT EltVT = N->getValueType(0).getVectorElementType();
1812   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1813                              HasAnyUndefs) &&
1814           EltVT.getSizeInBits() >= SplatBitSize);
1815 }
1816
1817 SDValue DAGCombiner::visitMUL(SDNode *N) {
1818   SDValue N0 = N->getOperand(0);
1819   SDValue N1 = N->getOperand(1);
1820   EVT VT = N0.getValueType();
1821
1822   // fold (mul x, undef) -> 0
1823   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1824     return DAG.getConstant(0, VT);
1825
1826   bool N0IsConst = false;
1827   bool N1IsConst = false;
1828   APInt ConstValue0, ConstValue1;
1829   // fold vector ops
1830   if (VT.isVector()) {
1831     SDValue FoldedVOp = SimplifyVBinOp(N);
1832     if (FoldedVOp.getNode()) return FoldedVOp;
1833
1834     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1835     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1836   } else {
1837     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1838     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1839                             : APInt();
1840     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1841     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1842                             : APInt();
1843   }
1844
1845   // fold (mul c1, c2) -> c1*c2
1846   if (N0IsConst && N1IsConst)
1847     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1848
1849   // canonicalize constant to RHS
1850   if (N0IsConst && !N1IsConst)
1851     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1852   // fold (mul x, 0) -> 0
1853   if (N1IsConst && ConstValue1 == 0)
1854     return N1;
1855   // We require a splat of the entire scalar bit width for non-contiguous
1856   // bit patterns.
1857   bool IsFullSplat =
1858     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1859   // fold (mul x, 1) -> x
1860   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1861     return N0;
1862   // fold (mul x, -1) -> 0-x
1863   if (N1IsConst && ConstValue1.isAllOnesValue())
1864     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1865                        DAG.getConstant(0, VT), N0);
1866   // fold (mul x, (1 << c)) -> x << c
1867   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1868     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1869                        DAG.getConstant(ConstValue1.logBase2(),
1870                                        getShiftAmountTy(N0.getValueType())));
1871   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1872   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1873     unsigned Log2Val = (-ConstValue1).logBase2();
1874     // FIXME: If the input is something that is easily negated (e.g. a
1875     // single-use add), we should put the negate there.
1876     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1877                        DAG.getConstant(0, VT),
1878                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1879                             DAG.getConstant(Log2Val,
1880                                       getShiftAmountTy(N0.getValueType()))));
1881   }
1882
1883   APInt Val;
1884   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1885   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1886       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1887                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1888     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1889                              N1, N0.getOperand(1));
1890     AddToWorkList(C3.getNode());
1891     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1892                        N0.getOperand(0), C3);
1893   }
1894
1895   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1896   // use.
1897   {
1898     SDValue Sh(0,0), Y(0,0);
1899     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1900     if (N0.getOpcode() == ISD::SHL &&
1901         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1902                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1903         N0.getNode()->hasOneUse()) {
1904       Sh = N0; Y = N1;
1905     } else if (N1.getOpcode() == ISD::SHL &&
1906                isa<ConstantSDNode>(N1.getOperand(1)) &&
1907                N1.getNode()->hasOneUse()) {
1908       Sh = N1; Y = N0;
1909     }
1910
1911     if (Sh.getNode()) {
1912       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913                                 Sh.getOperand(0), Y);
1914       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1915                          Mul, Sh.getOperand(1));
1916     }
1917   }
1918
1919   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1920   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1921       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922                      isa<ConstantSDNode>(N0.getOperand(1))))
1923     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1924                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1925                                    N0.getOperand(0), N1),
1926                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1927                                    N0.getOperand(1), N1));
1928
1929   // reassociate mul
1930   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1931   if (RMUL.getNode() != 0)
1932     return RMUL;
1933
1934   return SDValue();
1935 }
1936
1937 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1938   SDValue N0 = N->getOperand(0);
1939   SDValue N1 = N->getOperand(1);
1940   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1942   EVT VT = N->getValueType(0);
1943
1944   // fold vector ops
1945   if (VT.isVector()) {
1946     SDValue FoldedVOp = SimplifyVBinOp(N);
1947     if (FoldedVOp.getNode()) return FoldedVOp;
1948   }
1949
1950   // fold (sdiv c1, c2) -> c1/c2
1951   if (N0C && N1C && !N1C->isNullValue())
1952     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1953   // fold (sdiv X, 1) -> X
1954   if (N1C && N1C->getAPIntValue() == 1LL)
1955     return N0;
1956   // fold (sdiv X, -1) -> 0-X
1957   if (N1C && N1C->isAllOnesValue())
1958     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1959                        DAG.getConstant(0, VT), N0);
1960   // If we know the sign bits of both operands are zero, strength reduce to a
1961   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1962   if (!VT.isVector()) {
1963     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1964       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1965                          N0, N1);
1966   }
1967   // fold (sdiv X, pow2) -> simple ops after legalize
1968   if (N1C && !N1C->isNullValue() &&
1969       (N1C->getAPIntValue().isPowerOf2() ||
1970        (-N1C->getAPIntValue()).isPowerOf2())) {
1971     // If dividing by powers of two is cheap, then don't perform the following
1972     // fold.
1973     if (TLI.isPow2DivCheap())
1974       return SDValue();
1975
1976     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1977
1978     // Splat the sign bit into the register
1979     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1980                               DAG.getConstant(VT.getSizeInBits()-1,
1981                                        getShiftAmountTy(N0.getValueType())));
1982     AddToWorkList(SGN.getNode());
1983
1984     // Add (N0 < 0) ? abs2 - 1 : 0;
1985     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1986                               DAG.getConstant(VT.getSizeInBits() - lg2,
1987                                        getShiftAmountTy(SGN.getValueType())));
1988     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1989     AddToWorkList(SRL.getNode());
1990     AddToWorkList(ADD.getNode());    // Divide by pow2
1991     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1992                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1993
1994     // If we're dividing by a positive value, we're done.  Otherwise, we must
1995     // negate the result.
1996     if (N1C->getAPIntValue().isNonNegative())
1997       return SRA;
1998
1999     AddToWorkList(SRA.getNode());
2000     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2001                        DAG.getConstant(0, VT), SRA);
2002   }
2003
2004   // if integer divide is expensive and we satisfy the requirements, emit an
2005   // alternate sequence.
2006   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2007     SDValue Op = BuildSDIV(N);
2008     if (Op.getNode()) return Op;
2009   }
2010
2011   // undef / X -> 0
2012   if (N0.getOpcode() == ISD::UNDEF)
2013     return DAG.getConstant(0, VT);
2014   // X / undef -> undef
2015   if (N1.getOpcode() == ISD::UNDEF)
2016     return N1;
2017
2018   return SDValue();
2019 }
2020
2021 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2022   SDValue N0 = N->getOperand(0);
2023   SDValue N1 = N->getOperand(1);
2024   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2025   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2026   EVT VT = N->getValueType(0);
2027
2028   // fold vector ops
2029   if (VT.isVector()) {
2030     SDValue FoldedVOp = SimplifyVBinOp(N);
2031     if (FoldedVOp.getNode()) return FoldedVOp;
2032   }
2033
2034   // fold (udiv c1, c2) -> c1/c2
2035   if (N0C && N1C && !N1C->isNullValue())
2036     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2037   // fold (udiv x, (1 << c)) -> x >>u c
2038   if (N1C && N1C->getAPIntValue().isPowerOf2())
2039     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2040                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2041                                        getShiftAmountTy(N0.getValueType())));
2042   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2043   if (N1.getOpcode() == ISD::SHL) {
2044     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2045       if (SHC->getAPIntValue().isPowerOf2()) {
2046         EVT ADDVT = N1.getOperand(1).getValueType();
2047         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2048                                   N1.getOperand(1),
2049                                   DAG.getConstant(SHC->getAPIntValue()
2050                                                                   .logBase2(),
2051                                                   ADDVT));
2052         AddToWorkList(Add.getNode());
2053         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2054       }
2055     }
2056   }
2057   // fold (udiv x, c) -> alternate
2058   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2059     SDValue Op = BuildUDIV(N);
2060     if (Op.getNode()) return Op;
2061   }
2062
2063   // undef / X -> 0
2064   if (N0.getOpcode() == ISD::UNDEF)
2065     return DAG.getConstant(0, VT);
2066   // X / undef -> undef
2067   if (N1.getOpcode() == ISD::UNDEF)
2068     return N1;
2069
2070   return SDValue();
2071 }
2072
2073 SDValue DAGCombiner::visitSREM(SDNode *N) {
2074   SDValue N0 = N->getOperand(0);
2075   SDValue N1 = N->getOperand(1);
2076   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2077   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2078   EVT VT = N->getValueType(0);
2079
2080   // fold (srem c1, c2) -> c1%c2
2081   if (N0C && N1C && !N1C->isNullValue())
2082     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2083   // If we know the sign bits of both operands are zero, strength reduce to a
2084   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2085   if (!VT.isVector()) {
2086     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2088   }
2089
2090   // If X/C can be simplified by the division-by-constant logic, lower
2091   // X%C to the equivalent of X-X/C*C.
2092   if (N1C && !N1C->isNullValue()) {
2093     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2094     AddToWorkList(Div.getNode());
2095     SDValue OptimizedDiv = combine(Div.getNode());
2096     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2097       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2098                                 OptimizedDiv, N1);
2099       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2100       AddToWorkList(Mul.getNode());
2101       return Sub;
2102     }
2103   }
2104
2105   // undef % X -> 0
2106   if (N0.getOpcode() == ISD::UNDEF)
2107     return DAG.getConstant(0, VT);
2108   // X % undef -> undef
2109   if (N1.getOpcode() == ISD::UNDEF)
2110     return N1;
2111
2112   return SDValue();
2113 }
2114
2115 SDValue DAGCombiner::visitUREM(SDNode *N) {
2116   SDValue N0 = N->getOperand(0);
2117   SDValue N1 = N->getOperand(1);
2118   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2119   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2120   EVT VT = N->getValueType(0);
2121
2122   // fold (urem c1, c2) -> c1%c2
2123   if (N0C && N1C && !N1C->isNullValue())
2124     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2125   // fold (urem x, pow2) -> (and x, pow2-1)
2126   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2127     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2128                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2129   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2130   if (N1.getOpcode() == ISD::SHL) {
2131     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2132       if (SHC->getAPIntValue().isPowerOf2()) {
2133         SDValue Add =
2134           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2135                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2136                                  VT));
2137         AddToWorkList(Add.getNode());
2138         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2139       }
2140     }
2141   }
2142
2143   // If X/C can be simplified by the division-by-constant logic, lower
2144   // X%C to the equivalent of X-X/C*C.
2145   if (N1C && !N1C->isNullValue()) {
2146     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2147     AddToWorkList(Div.getNode());
2148     SDValue OptimizedDiv = combine(Div.getNode());
2149     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2150       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2151                                 OptimizedDiv, N1);
2152       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2153       AddToWorkList(Mul.getNode());
2154       return Sub;
2155     }
2156   }
2157
2158   // undef % X -> 0
2159   if (N0.getOpcode() == ISD::UNDEF)
2160     return DAG.getConstant(0, VT);
2161   // X % undef -> undef
2162   if (N1.getOpcode() == ISD::UNDEF)
2163     return N1;
2164
2165   return SDValue();
2166 }
2167
2168 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2169   SDValue N0 = N->getOperand(0);
2170   SDValue N1 = N->getOperand(1);
2171   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2172   EVT VT = N->getValueType(0);
2173   SDLoc DL(N);
2174
2175   // fold (mulhs x, 0) -> 0
2176   if (N1C && N1C->isNullValue())
2177     return N1;
2178   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2179   if (N1C && N1C->getAPIntValue() == 1)
2180     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2181                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2182                                        getShiftAmountTy(N0.getValueType())));
2183   // fold (mulhs x, undef) -> 0
2184   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2185     return DAG.getConstant(0, VT);
2186
2187   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2188   // plus a shift.
2189   if (VT.isSimple() && !VT.isVector()) {
2190     MVT Simple = VT.getSimpleVT();
2191     unsigned SimpleSize = Simple.getSizeInBits();
2192     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2193     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2194       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2195       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2196       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2197       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2198             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2199       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2200     }
2201   }
2202
2203   return SDValue();
2204 }
2205
2206 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2207   SDValue N0 = N->getOperand(0);
2208   SDValue N1 = N->getOperand(1);
2209   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2210   EVT VT = N->getValueType(0);
2211   SDLoc DL(N);
2212
2213   // fold (mulhu x, 0) -> 0
2214   if (N1C && N1C->isNullValue())
2215     return N1;
2216   // fold (mulhu x, 1) -> 0
2217   if (N1C && N1C->getAPIntValue() == 1)
2218     return DAG.getConstant(0, N0.getValueType());
2219   // fold (mulhu x, undef) -> 0
2220   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2221     return DAG.getConstant(0, VT);
2222
2223   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2224   // plus a shift.
2225   if (VT.isSimple() && !VT.isVector()) {
2226     MVT Simple = VT.getSimpleVT();
2227     unsigned SimpleSize = Simple.getSizeInBits();
2228     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2229     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2230       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2231       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2232       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2233       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2234             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2235       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2236     }
2237   }
2238
2239   return SDValue();
2240 }
2241
2242 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2243 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2244 /// that are being performed. Return true if a simplification was made.
2245 ///
2246 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2247                                                 unsigned HiOp) {
2248   // If the high half is not needed, just compute the low half.
2249   bool HiExists = N->hasAnyUseOfValue(1);
2250   if (!HiExists &&
2251       (!LegalOperations ||
2252        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2253     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2254                               N->op_begin(), N->getNumOperands());
2255     return CombineTo(N, Res, Res);
2256   }
2257
2258   // If the low half is not needed, just compute the high half.
2259   bool LoExists = N->hasAnyUseOfValue(0);
2260   if (!LoExists &&
2261       (!LegalOperations ||
2262        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2263     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2264                               N->op_begin(), N->getNumOperands());
2265     return CombineTo(N, Res, Res);
2266   }
2267
2268   // If both halves are used, return as it is.
2269   if (LoExists && HiExists)
2270     return SDValue();
2271
2272   // If the two computed results can be simplified separately, separate them.
2273   if (LoExists) {
2274     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2275                              N->op_begin(), N->getNumOperands());
2276     AddToWorkList(Lo.getNode());
2277     SDValue LoOpt = combine(Lo.getNode());
2278     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2279         (!LegalOperations ||
2280          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2281       return CombineTo(N, LoOpt, LoOpt);
2282   }
2283
2284   if (HiExists) {
2285     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2286                              N->op_begin(), N->getNumOperands());
2287     AddToWorkList(Hi.getNode());
2288     SDValue HiOpt = combine(Hi.getNode());
2289     if (HiOpt.getNode() && HiOpt != Hi &&
2290         (!LegalOperations ||
2291          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2292       return CombineTo(N, HiOpt, HiOpt);
2293   }
2294
2295   return SDValue();
2296 }
2297
2298 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2299   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2300   if (Res.getNode()) return Res;
2301
2302   EVT VT = N->getValueType(0);
2303   SDLoc DL(N);
2304
2305   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2306   // plus a shift.
2307   if (VT.isSimple() && !VT.isVector()) {
2308     MVT Simple = VT.getSimpleVT();
2309     unsigned SimpleSize = Simple.getSizeInBits();
2310     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2313       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2314       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2315       // Compute the high part as N1.
2316       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2317             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2318       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2319       // Compute the low part as N0.
2320       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2321       return CombineTo(N, Lo, Hi);
2322     }
2323   }
2324
2325   return SDValue();
2326 }
2327
2328 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2329   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2330   if (Res.getNode()) return Res;
2331
2332   EVT VT = N->getValueType(0);
2333   SDLoc DL(N);
2334
2335   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2336   // plus a shift.
2337   if (VT.isSimple() && !VT.isVector()) {
2338     MVT Simple = VT.getSimpleVT();
2339     unsigned SimpleSize = Simple.getSizeInBits();
2340     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2341     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2342       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2343       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2344       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2345       // Compute the high part as N1.
2346       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2347             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2348       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2349       // Compute the low part as N0.
2350       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2351       return CombineTo(N, Lo, Hi);
2352     }
2353   }
2354
2355   return SDValue();
2356 }
2357
2358 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2359   // (smulo x, 2) -> (saddo x, x)
2360   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2361     if (C2->getAPIntValue() == 2)
2362       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2363                          N->getOperand(0), N->getOperand(0));
2364
2365   return SDValue();
2366 }
2367
2368 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2369   // (umulo x, 2) -> (uaddo x, x)
2370   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2371     if (C2->getAPIntValue() == 2)
2372       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2373                          N->getOperand(0), N->getOperand(0));
2374
2375   return SDValue();
2376 }
2377
2378 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2379   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2380   if (Res.getNode()) return Res;
2381
2382   return SDValue();
2383 }
2384
2385 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2386   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2387   if (Res.getNode()) return Res;
2388
2389   return SDValue();
2390 }
2391
2392 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2393 /// two operands of the same opcode, try to simplify it.
2394 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2395   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2396   EVT VT = N0.getValueType();
2397   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2398
2399   // Bail early if none of these transforms apply.
2400   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2401
2402   // For each of OP in AND/OR/XOR:
2403   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2404   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2405   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2406   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2407   //
2408   // do not sink logical op inside of a vector extend, since it may combine
2409   // into a vsetcc.
2410   EVT Op0VT = N0.getOperand(0).getValueType();
2411   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2412        N0.getOpcode() == ISD::SIGN_EXTEND ||
2413        // Avoid infinite looping with PromoteIntBinOp.
2414        (N0.getOpcode() == ISD::ANY_EXTEND &&
2415         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2416        (N0.getOpcode() == ISD::TRUNCATE &&
2417         (!TLI.isZExtFree(VT, Op0VT) ||
2418          !TLI.isTruncateFree(Op0VT, VT)) &&
2419         TLI.isTypeLegal(Op0VT))) &&
2420       !VT.isVector() &&
2421       Op0VT == N1.getOperand(0).getValueType() &&
2422       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2423     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2424                                  N0.getOperand(0).getValueType(),
2425                                  N0.getOperand(0), N1.getOperand(0));
2426     AddToWorkList(ORNode.getNode());
2427     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2428   }
2429
2430   // For each of OP in SHL/SRL/SRA/AND...
2431   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2432   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2433   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2434   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2435        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2436       N0.getOperand(1) == N1.getOperand(1)) {
2437     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2438                                  N0.getOperand(0).getValueType(),
2439                                  N0.getOperand(0), N1.getOperand(0));
2440     AddToWorkList(ORNode.getNode());
2441     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2442                        ORNode, N0.getOperand(1));
2443   }
2444
2445   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2446   // Only perform this optimization after type legalization and before
2447   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2448   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2449   // we don't want to undo this promotion.
2450   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2451   // on scalars.
2452   if ((N0.getOpcode() == ISD::BITCAST ||
2453        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2454       Level == AfterLegalizeTypes) {
2455     SDValue In0 = N0.getOperand(0);
2456     SDValue In1 = N1.getOperand(0);
2457     EVT In0Ty = In0.getValueType();
2458     EVT In1Ty = In1.getValueType();
2459     SDLoc DL(N);
2460     // If both incoming values are integers, and the original types are the
2461     // same.
2462     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2463       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2464       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2465       AddToWorkList(Op.getNode());
2466       return BC;
2467     }
2468   }
2469
2470   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2471   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2472   // If both shuffles use the same mask, and both shuffle within a single
2473   // vector, then it is worthwhile to move the swizzle after the operation.
2474   // The type-legalizer generates this pattern when loading illegal
2475   // vector types from memory. In many cases this allows additional shuffle
2476   // optimizations.
2477   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2478       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2479       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2480     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2481     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2482
2483     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2484            "Inputs to shuffles are not the same type");
2485
2486     unsigned NumElts = VT.getVectorNumElements();
2487
2488     // Check that both shuffles use the same mask. The masks are known to be of
2489     // the same length because the result vector type is the same.
2490     bool SameMask = true;
2491     for (unsigned i = 0; i != NumElts; ++i) {
2492       int Idx0 = SVN0->getMaskElt(i);
2493       int Idx1 = SVN1->getMaskElt(i);
2494       if (Idx0 != Idx1) {
2495         SameMask = false;
2496         break;
2497       }
2498     }
2499
2500     if (SameMask) {
2501       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2502                                N0.getOperand(0), N1.getOperand(0));
2503       AddToWorkList(Op.getNode());
2504       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2505                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitAND(SDNode *N) {
2513   SDValue N0 = N->getOperand(0);
2514   SDValue N1 = N->getOperand(1);
2515   SDValue LL, LR, RL, RR, CC0, CC1;
2516   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2517   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2518   EVT VT = N1.getValueType();
2519   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2520
2521   // fold vector ops
2522   if (VT.isVector()) {
2523     SDValue FoldedVOp = SimplifyVBinOp(N);
2524     if (FoldedVOp.getNode()) return FoldedVOp;
2525
2526     // fold (and x, 0) -> 0, vector edition
2527     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2528       return N0;
2529     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2530       return N1;
2531
2532     // fold (and x, -1) -> x, vector edition
2533     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2534       return N1;
2535     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2536       return N0;
2537   }
2538
2539   // fold (and x, undef) -> 0
2540   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2541     return DAG.getConstant(0, VT);
2542   // fold (and c1, c2) -> c1&c2
2543   if (N0C && N1C)
2544     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2545   // canonicalize constant to RHS
2546   if (N0C && !N1C)
2547     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2548   // fold (and x, -1) -> x
2549   if (N1C && N1C->isAllOnesValue())
2550     return N0;
2551   // if (and x, c) is known to be zero, return 0
2552   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2553                                    APInt::getAllOnesValue(BitWidth)))
2554     return DAG.getConstant(0, VT);
2555   // reassociate and
2556   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2557   if (RAND.getNode() != 0)
2558     return RAND;
2559   // fold (and (or x, C), D) -> D if (C & D) == D
2560   if (N1C && N0.getOpcode() == ISD::OR)
2561     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2562       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2563         return N1;
2564   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2565   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2566     SDValue N0Op0 = N0.getOperand(0);
2567     APInt Mask = ~N1C->getAPIntValue();
2568     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2569     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2570       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2571                                  N0.getValueType(), N0Op0);
2572
2573       // Replace uses of the AND with uses of the Zero extend node.
2574       CombineTo(N, Zext);
2575
2576       // We actually want to replace all uses of the any_extend with the
2577       // zero_extend, to avoid duplicating things.  This will later cause this
2578       // AND to be folded.
2579       CombineTo(N0.getNode(), Zext);
2580       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2581     }
2582   }
2583   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2584   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2585   // already be zero by virtue of the width of the base type of the load.
2586   //
2587   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2588   // more cases.
2589   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2590        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2591       N0.getOpcode() == ISD::LOAD) {
2592     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2593                                          N0 : N0.getOperand(0) );
2594
2595     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2596     // This can be a pure constant or a vector splat, in which case we treat the
2597     // vector as a scalar and use the splat value.
2598     APInt Constant = APInt::getNullValue(1);
2599     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2600       Constant = C->getAPIntValue();
2601     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2602       APInt SplatValue, SplatUndef;
2603       unsigned SplatBitSize;
2604       bool HasAnyUndefs;
2605       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2606                                              SplatBitSize, HasAnyUndefs);
2607       if (IsSplat) {
2608         // Undef bits can contribute to a possible optimisation if set, so
2609         // set them.
2610         SplatValue |= SplatUndef;
2611
2612         // The splat value may be something like "0x00FFFFFF", which means 0 for
2613         // the first vector value and FF for the rest, repeating. We need a mask
2614         // that will apply equally to all members of the vector, so AND all the
2615         // lanes of the constant together.
2616         EVT VT = Vector->getValueType(0);
2617         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2618
2619         // If the splat value has been compressed to a bitlength lower
2620         // than the size of the vector lane, we need to re-expand it to
2621         // the lane size.
2622         if (BitWidth > SplatBitSize)
2623           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2624                SplatBitSize < BitWidth;
2625                SplatBitSize = SplatBitSize * 2)
2626             SplatValue |= SplatValue.shl(SplatBitSize);
2627
2628         Constant = APInt::getAllOnesValue(BitWidth);
2629         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2630           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2631       }
2632     }
2633
2634     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2635     // actually legal and isn't going to get expanded, else this is a false
2636     // optimisation.
2637     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2638                                                     Load->getMemoryVT());
2639
2640     // Resize the constant to the same size as the original memory access before
2641     // extension. If it is still the AllOnesValue then this AND is completely
2642     // unneeded.
2643     Constant =
2644       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2645
2646     bool B;
2647     switch (Load->getExtensionType()) {
2648     default: B = false; break;
2649     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2650     case ISD::ZEXTLOAD:
2651     case ISD::NON_EXTLOAD: B = true; break;
2652     }
2653
2654     if (B && Constant.isAllOnesValue()) {
2655       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2656       // preserve semantics once we get rid of the AND.
2657       SDValue NewLoad(Load, 0);
2658       if (Load->getExtensionType() == ISD::EXTLOAD) {
2659         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2660                               Load->getValueType(0), SDLoc(Load),
2661                               Load->getChain(), Load->getBasePtr(),
2662                               Load->getOffset(), Load->getMemoryVT(),
2663                               Load->getMemOperand());
2664         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2665         if (Load->getNumValues() == 3) {
2666           // PRE/POST_INC loads have 3 values.
2667           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2668                            NewLoad.getValue(2) };
2669           CombineTo(Load, To, 3, true);
2670         } else {
2671           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2672         }
2673       }
2674
2675       // Fold the AND away, taking care not to fold to the old load node if we
2676       // replaced it.
2677       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2678
2679       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2680     }
2681   }
2682   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2683   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2684     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2685     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2686
2687     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2688         LL.getValueType().isInteger()) {
2689       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2690       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2691         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2692                                      LR.getValueType(), LL, RL);
2693         AddToWorkList(ORNode.getNode());
2694         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2695       }
2696       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2697       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2698         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2699                                       LR.getValueType(), LL, RL);
2700         AddToWorkList(ANDNode.getNode());
2701         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2702       }
2703       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2704       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2705         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2706                                      LR.getValueType(), LL, RL);
2707         AddToWorkList(ORNode.getNode());
2708         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2709       }
2710     }
2711     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2712     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2713         Op0 == Op1 && LL.getValueType().isInteger() &&
2714       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2715                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2716                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2717                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2718       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2719                                     LL, DAG.getConstant(1, LL.getValueType()));
2720       AddToWorkList(ADDNode.getNode());
2721       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2722                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2723     }
2724     // canonicalize equivalent to ll == rl
2725     if (LL == RR && LR == RL) {
2726       Op1 = ISD::getSetCCSwappedOperands(Op1);
2727       std::swap(RL, RR);
2728     }
2729     if (LL == RL && LR == RR) {
2730       bool isInteger = LL.getValueType().isInteger();
2731       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2732       if (Result != ISD::SETCC_INVALID &&
2733           (!LegalOperations ||
2734            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2735             TLI.isOperationLegal(ISD::SETCC,
2736                             getSetCCResultType(N0.getSimpleValueType())))))
2737         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2738                             LL, LR, Result);
2739     }
2740   }
2741
2742   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2743   if (N0.getOpcode() == N1.getOpcode()) {
2744     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2745     if (Tmp.getNode()) return Tmp;
2746   }
2747
2748   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2749   // fold (and (sra)) -> (and (srl)) when possible.
2750   if (!VT.isVector() &&
2751       SimplifyDemandedBits(SDValue(N, 0)))
2752     return SDValue(N, 0);
2753
2754   // fold (zext_inreg (extload x)) -> (zextload x)
2755   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2756     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2757     EVT MemVT = LN0->getMemoryVT();
2758     // If we zero all the possible extended bits, then we can turn this into
2759     // a zextload if we are running before legalize or the operation is legal.
2760     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2761     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2762                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2763         ((!LegalOperations && !LN0->isVolatile()) ||
2764          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2765       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2766                                        LN0->getChain(), LN0->getBasePtr(),
2767                                        MemVT, LN0->getMemOperand());
2768       AddToWorkList(N);
2769       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2770       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2771     }
2772   }
2773   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2774   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2775       N0.hasOneUse()) {
2776     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2777     EVT MemVT = LN0->getMemoryVT();
2778     // If we zero all the possible extended bits, then we can turn this into
2779     // a zextload if we are running before legalize or the operation is legal.
2780     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2781     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2782                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2783         ((!LegalOperations && !LN0->isVolatile()) ||
2784          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2785       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2786                                        LN0->getChain(), LN0->getBasePtr(),
2787                                        MemVT, LN0->getMemOperand());
2788       AddToWorkList(N);
2789       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2790       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2791     }
2792   }
2793
2794   // fold (and (load x), 255) -> (zextload x, i8)
2795   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2796   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2797   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2798               (N0.getOpcode() == ISD::ANY_EXTEND &&
2799                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2800     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2801     LoadSDNode *LN0 = HasAnyExt
2802       ? cast<LoadSDNode>(N0.getOperand(0))
2803       : cast<LoadSDNode>(N0);
2804     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2805         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2806       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2807       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2808         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2809         EVT LoadedVT = LN0->getMemoryVT();
2810
2811         if (ExtVT == LoadedVT &&
2812             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2813           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2814
2815           SDValue NewLoad =
2816             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2817                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2818                            LN0->getMemOperand());
2819           AddToWorkList(N);
2820           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2821           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2822         }
2823
2824         // Do not change the width of a volatile load.
2825         // Do not generate loads of non-round integer types since these can
2826         // be expensive (and would be wrong if the type is not byte sized).
2827         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2828             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2829           EVT PtrType = LN0->getOperand(1).getValueType();
2830
2831           unsigned Alignment = LN0->getAlignment();
2832           SDValue NewPtr = LN0->getBasePtr();
2833
2834           // For big endian targets, we need to add an offset to the pointer
2835           // to load the correct bytes.  For little endian systems, we merely
2836           // need to read fewer bytes from the same pointer.
2837           if (TLI.isBigEndian()) {
2838             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2839             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2840             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2841             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2842                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2843             Alignment = MinAlign(Alignment, PtrOff);
2844           }
2845
2846           AddToWorkList(NewPtr.getNode());
2847
2848           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2849           SDValue Load =
2850             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2851                            LN0->getChain(), NewPtr,
2852                            LN0->getPointerInfo(),
2853                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2854                            Alignment, LN0->getTBAAInfo());
2855           AddToWorkList(N);
2856           CombineTo(LN0, Load, Load.getValue(1));
2857           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2858         }
2859       }
2860     }
2861   }
2862
2863   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2864       VT.getSizeInBits() <= 64) {
2865     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2866       APInt ADDC = ADDI->getAPIntValue();
2867       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2868         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2869         // immediate for an add, but it is legal if its top c2 bits are set,
2870         // transform the ADD so the immediate doesn't need to be materialized
2871         // in a register.
2872         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2873           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2874                                              SRLI->getZExtValue());
2875           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2876             ADDC |= Mask;
2877             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2878               SDValue NewAdd =
2879                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2880                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2881               CombineTo(N0.getNode(), NewAdd);
2882               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2883             }
2884           }
2885         }
2886       }
2887     }
2888   }
2889
2890   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2891   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2892     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2893                                        N0.getOperand(1), false);
2894     if (BSwap.getNode())
2895       return BSwap;
2896   }
2897
2898   return SDValue();
2899 }
2900
2901 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2902 ///
2903 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2904                                         bool DemandHighBits) {
2905   if (!LegalOperations)
2906     return SDValue();
2907
2908   EVT VT = N->getValueType(0);
2909   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2910     return SDValue();
2911   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2912     return SDValue();
2913
2914   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2915   bool LookPassAnd0 = false;
2916   bool LookPassAnd1 = false;
2917   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2918       std::swap(N0, N1);
2919   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2920       std::swap(N0, N1);
2921   if (N0.getOpcode() == ISD::AND) {
2922     if (!N0.getNode()->hasOneUse())
2923       return SDValue();
2924     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2925     if (!N01C || N01C->getZExtValue() != 0xFF00)
2926       return SDValue();
2927     N0 = N0.getOperand(0);
2928     LookPassAnd0 = true;
2929   }
2930
2931   if (N1.getOpcode() == ISD::AND) {
2932     if (!N1.getNode()->hasOneUse())
2933       return SDValue();
2934     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2935     if (!N11C || N11C->getZExtValue() != 0xFF)
2936       return SDValue();
2937     N1 = N1.getOperand(0);
2938     LookPassAnd1 = true;
2939   }
2940
2941   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2942     std::swap(N0, N1);
2943   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2944     return SDValue();
2945   if (!N0.getNode()->hasOneUse() ||
2946       !N1.getNode()->hasOneUse())
2947     return SDValue();
2948
2949   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2950   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2951   if (!N01C || !N11C)
2952     return SDValue();
2953   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2954     return SDValue();
2955
2956   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2957   SDValue N00 = N0->getOperand(0);
2958   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2959     if (!N00.getNode()->hasOneUse())
2960       return SDValue();
2961     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2962     if (!N001C || N001C->getZExtValue() != 0xFF)
2963       return SDValue();
2964     N00 = N00.getOperand(0);
2965     LookPassAnd0 = true;
2966   }
2967
2968   SDValue N10 = N1->getOperand(0);
2969   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2970     if (!N10.getNode()->hasOneUse())
2971       return SDValue();
2972     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2973     if (!N101C || N101C->getZExtValue() != 0xFF00)
2974       return SDValue();
2975     N10 = N10.getOperand(0);
2976     LookPassAnd1 = true;
2977   }
2978
2979   if (N00 != N10)
2980     return SDValue();
2981
2982   // Make sure everything beyond the low halfword gets set to zero since the SRL
2983   // 16 will clear the top bits.
2984   unsigned OpSizeInBits = VT.getSizeInBits();
2985   if (DemandHighBits && OpSizeInBits > 16) {
2986     // If the left-shift isn't masked out then the only way this is a bswap is
2987     // if all bits beyond the low 8 are 0. In that case the entire pattern
2988     // reduces to a left shift anyway: leave it for other parts of the combiner.
2989     if (!LookPassAnd0)
2990       return SDValue();
2991
2992     // However, if the right shift isn't masked out then it might be because
2993     // it's not needed. See if we can spot that too.
2994     if (!LookPassAnd1 &&
2995         !DAG.MaskedValueIsZero(
2996             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2997       return SDValue();
2998   }
2999
3000   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3001   if (OpSizeInBits > 16)
3002     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3003                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3004   return Res;
3005 }
3006
3007 /// isBSwapHWordElement - Return true if the specified node is an element
3008 /// that makes up a 32-bit packed halfword byteswap. i.e.
3009 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3010 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3011   if (!N.getNode()->hasOneUse())
3012     return false;
3013
3014   unsigned Opc = N.getOpcode();
3015   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3016     return false;
3017
3018   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3019   if (!N1C)
3020     return false;
3021
3022   unsigned Num;
3023   switch (N1C->getZExtValue()) {
3024   default:
3025     return false;
3026   case 0xFF:       Num = 0; break;
3027   case 0xFF00:     Num = 1; break;
3028   case 0xFF0000:   Num = 2; break;
3029   case 0xFF000000: Num = 3; break;
3030   }
3031
3032   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3033   SDValue N0 = N.getOperand(0);
3034   if (Opc == ISD::AND) {
3035     if (Num == 0 || Num == 2) {
3036       // (x >> 8) & 0xff
3037       // (x >> 8) & 0xff0000
3038       if (N0.getOpcode() != ISD::SRL)
3039         return false;
3040       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3041       if (!C || C->getZExtValue() != 8)
3042         return false;
3043     } else {
3044       // (x << 8) & 0xff00
3045       // (x << 8) & 0xff000000
3046       if (N0.getOpcode() != ISD::SHL)
3047         return false;
3048       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3049       if (!C || C->getZExtValue() != 8)
3050         return false;
3051     }
3052   } else if (Opc == ISD::SHL) {
3053     // (x & 0xff) << 8
3054     // (x & 0xff0000) << 8
3055     if (Num != 0 && Num != 2)
3056       return false;
3057     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3058     if (!C || C->getZExtValue() != 8)
3059       return false;
3060   } else { // Opc == ISD::SRL
3061     // (x & 0xff00) >> 8
3062     // (x & 0xff000000) >> 8
3063     if (Num != 1 && Num != 3)
3064       return false;
3065     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3066     if (!C || C->getZExtValue() != 8)
3067       return false;
3068   }
3069
3070   if (Parts[Num])
3071     return false;
3072
3073   Parts[Num] = N0.getOperand(0).getNode();
3074   return true;
3075 }
3076
3077 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3078 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3079 /// => (rotl (bswap x), 16)
3080 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3081   if (!LegalOperations)
3082     return SDValue();
3083
3084   EVT VT = N->getValueType(0);
3085   if (VT != MVT::i32)
3086     return SDValue();
3087   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3088     return SDValue();
3089
3090   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3091   // Look for either
3092   // (or (or (and), (and)), (or (and), (and)))
3093   // (or (or (or (and), (and)), (and)), (and))
3094   if (N0.getOpcode() != ISD::OR)
3095     return SDValue();
3096   SDValue N00 = N0.getOperand(0);
3097   SDValue N01 = N0.getOperand(1);
3098
3099   if (N1.getOpcode() == ISD::OR &&
3100       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3101     // (or (or (and), (and)), (or (and), (and)))
3102     SDValue N000 = N00.getOperand(0);
3103     if (!isBSwapHWordElement(N000, Parts))
3104       return SDValue();
3105
3106     SDValue N001 = N00.getOperand(1);
3107     if (!isBSwapHWordElement(N001, Parts))
3108       return SDValue();
3109     SDValue N010 = N01.getOperand(0);
3110     if (!isBSwapHWordElement(N010, Parts))
3111       return SDValue();
3112     SDValue N011 = N01.getOperand(1);
3113     if (!isBSwapHWordElement(N011, Parts))
3114       return SDValue();
3115   } else {
3116     // (or (or (or (and), (and)), (and)), (and))
3117     if (!isBSwapHWordElement(N1, Parts))
3118       return SDValue();
3119     if (!isBSwapHWordElement(N01, Parts))
3120       return SDValue();
3121     if (N00.getOpcode() != ISD::OR)
3122       return SDValue();
3123     SDValue N000 = N00.getOperand(0);
3124     if (!isBSwapHWordElement(N000, Parts))
3125       return SDValue();
3126     SDValue N001 = N00.getOperand(1);
3127     if (!isBSwapHWordElement(N001, Parts))
3128       return SDValue();
3129   }
3130
3131   // Make sure the parts are all coming from the same node.
3132   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3133     return SDValue();
3134
3135   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3136                               SDValue(Parts[0],0));
3137
3138   // Result of the bswap should be rotated by 16. If it's not legal, then
3139   // do  (x << 16) | (x >> 16).
3140   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3141   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3142     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3143   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3144     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3145   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3146                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3147                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3148 }
3149
3150 SDValue DAGCombiner::visitOR(SDNode *N) {
3151   SDValue N0 = N->getOperand(0);
3152   SDValue N1 = N->getOperand(1);
3153   SDValue LL, LR, RL, RR, CC0, CC1;
3154   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3155   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3156   EVT VT = N1.getValueType();
3157
3158   // fold vector ops
3159   if (VT.isVector()) {
3160     SDValue FoldedVOp = SimplifyVBinOp(N);
3161     if (FoldedVOp.getNode()) return FoldedVOp;
3162
3163     // fold (or x, 0) -> x, vector edition
3164     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3165       return N1;
3166     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3167       return N0;
3168
3169     // fold (or x, -1) -> -1, vector edition
3170     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3171       return N0;
3172     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3173       return N1;
3174   }
3175
3176   // fold (or x, undef) -> -1
3177   if (!LegalOperations &&
3178       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3179     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3180     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3181   }
3182   // fold (or c1, c2) -> c1|c2
3183   if (N0C && N1C)
3184     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3185   // canonicalize constant to RHS
3186   if (N0C && !N1C)
3187     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3188   // fold (or x, 0) -> x
3189   if (N1C && N1C->isNullValue())
3190     return N0;
3191   // fold (or x, -1) -> -1
3192   if (N1C && N1C->isAllOnesValue())
3193     return N1;
3194   // fold (or x, c) -> c iff (x & ~c) == 0
3195   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3196     return N1;
3197
3198   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3199   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3200   if (BSwap.getNode() != 0)
3201     return BSwap;
3202   BSwap = MatchBSwapHWordLow(N, N0, N1);
3203   if (BSwap.getNode() != 0)
3204     return BSwap;
3205
3206   // reassociate or
3207   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3208   if (ROR.getNode() != 0)
3209     return ROR;
3210   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3211   // iff (c1 & c2) == 0.
3212   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3213              isa<ConstantSDNode>(N0.getOperand(1))) {
3214     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3215     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3216       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3217                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3218                                      N0.getOperand(0), N1),
3219                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3220   }
3221   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3222   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3223     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3224     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3225
3226     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3227         LL.getValueType().isInteger()) {
3228       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3229       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3230       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3231           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3232         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3233                                      LR.getValueType(), LL, RL);
3234         AddToWorkList(ORNode.getNode());
3235         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3236       }
3237       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3238       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3239       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3240           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3241         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3242                                       LR.getValueType(), LL, RL);
3243         AddToWorkList(ANDNode.getNode());
3244         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3245       }
3246     }
3247     // canonicalize equivalent to ll == rl
3248     if (LL == RR && LR == RL) {
3249       Op1 = ISD::getSetCCSwappedOperands(Op1);
3250       std::swap(RL, RR);
3251     }
3252     if (LL == RL && LR == RR) {
3253       bool isInteger = LL.getValueType().isInteger();
3254       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3255       if (Result != ISD::SETCC_INVALID &&
3256           (!LegalOperations ||
3257            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3258             TLI.isOperationLegal(ISD::SETCC,
3259               getSetCCResultType(N0.getValueType())))))
3260         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3261                             LL, LR, Result);
3262     }
3263   }
3264
3265   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3266   if (N0.getOpcode() == N1.getOpcode()) {
3267     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3268     if (Tmp.getNode()) return Tmp;
3269   }
3270
3271   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3272   if (N0.getOpcode() == ISD::AND &&
3273       N1.getOpcode() == ISD::AND &&
3274       N0.getOperand(1).getOpcode() == ISD::Constant &&
3275       N1.getOperand(1).getOpcode() == ISD::Constant &&
3276       // Don't increase # computations.
3277       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3278     // We can only do this xform if we know that bits from X that are set in C2
3279     // but not in C1 are already zero.  Likewise for Y.
3280     const APInt &LHSMask =
3281       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3282     const APInt &RHSMask =
3283       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3284
3285     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3286         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3287       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3288                               N0.getOperand(0), N1.getOperand(0));
3289       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3290                          DAG.getConstant(LHSMask | RHSMask, VT));
3291     }
3292   }
3293
3294   // See if this is some rotate idiom.
3295   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3296     return SDValue(Rot, 0);
3297
3298   // Simplify the operands using demanded-bits information.
3299   if (!VT.isVector() &&
3300       SimplifyDemandedBits(SDValue(N, 0)))
3301     return SDValue(N, 0);
3302
3303   return SDValue();
3304 }
3305
3306 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3307 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3308   if (Op.getOpcode() == ISD::AND) {
3309     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3310       Mask = Op.getOperand(1);
3311       Op = Op.getOperand(0);
3312     } else {
3313       return false;
3314     }
3315   }
3316
3317   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3318     Shift = Op;
3319     return true;
3320   }
3321
3322   return false;
3323 }
3324
3325 // Return true if we can prove that, whenever Neg and Pos are both in the
3326 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3327 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3328 //
3329 //     (or (shift1 X, Neg), (shift2 X, Pos))
3330 //
3331 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3332 // shift1 by Neg.  The range [0, OpSize) means that we only need to consider
3333 // shift amounts with defined behavior.
3334 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3335   // If OpSize is a power of 2 then:
3336   //
3337   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3338   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3339   //
3340   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3341   // for the stronger condition:
3342   //
3343   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3344   //
3345   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3346   // we can just replace Neg with Neg' for the rest of the function.
3347   //
3348   // In other cases we check for the even stronger condition:
3349   //
3350   //     Neg == OpSize - Pos                                    [B]
3351   //
3352   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3353   // behavior if Pos == 0 (and consequently Neg == OpSize).
3354   // 
3355   // We could actually use [A] whenever OpSize is a power of 2, but the
3356   // only extra cases that it would match are those uninteresting ones
3357   // where Neg and Pos are never in range at the same time.  E.g. for
3358   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3359   // as well as (sub 32, Pos), but:
3360   //
3361   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3362   //
3363   // always invokes undefined behavior for 32-bit X.
3364   //
3365   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3366   unsigned LoBits = 0;
3367   if (Neg.getOpcode() == ISD::AND &&
3368       isPowerOf2_64(OpSize) &&
3369       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3370       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3371     Neg = Neg.getOperand(0);
3372     LoBits = Log2_64(OpSize);
3373   }
3374
3375   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3376   if (Neg.getOpcode() != ISD::SUB)
3377     return 0;
3378   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3379   if (!NegC)
3380     return 0;
3381   SDValue NegOp1 = Neg.getOperand(1);
3382
3383   // The condition we need is now:
3384   //
3385   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3386   //
3387   // If NegOp1 == Pos then we need:
3388   //
3389   //              OpSize & Mask == NegC & Mask
3390   //
3391   // (because "x & Mask" is a truncation and distributes through subtraction).
3392   APInt Width;
3393   if (Pos == NegOp1)
3394     Width = NegC->getAPIntValue();
3395   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3396   // Then the condition we want to prove becomes:
3397   //
3398   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3399   //
3400   // which, again because "x & Mask" is a truncation, becomes:
3401   //
3402   //                NegC & Mask == (OpSize - PosC) & Mask
3403   //              OpSize & Mask == (NegC + PosC) & Mask
3404   else if (Pos.getOpcode() == ISD::ADD &&
3405            Pos.getOperand(0) == NegOp1 &&
3406            Pos.getOperand(1).getOpcode() == ISD::Constant)
3407     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3408              NegC->getAPIntValue());
3409   else
3410     return false;
3411
3412   // Now we just need to check that OpSize & Mask == Width & Mask.
3413   if (LoBits)
3414     return Width.getLoBits(LoBits) == 0;
3415   return Width == OpSize;
3416 }
3417
3418 // A subroutine of MatchRotate used once we have found an OR of two opposite
3419 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3420 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3421 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3422 // Neg with outer conversions stripped away.
3423 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3424                                        SDValue Neg, SDValue InnerPos,
3425                                        SDValue InnerNeg, unsigned PosOpcode,
3426                                        unsigned NegOpcode, SDLoc DL) {
3427   // fold (or (shl x, (*ext y)),
3428   //          (srl x, (*ext (sub 32, y)))) ->
3429   //   (rotl x, y) or (rotr x, (sub 32, y))
3430   //
3431   // fold (or (shl x, (*ext (sub 32, y))),
3432   //          (srl x, (*ext y))) ->
3433   //   (rotr x, y) or (rotl x, (sub 32, y))
3434   EVT VT = Shifted.getValueType();
3435   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3436     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3437     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3438                        HasPos ? Pos : Neg).getNode();
3439   }
3440
3441   // fold (or (shl (*ext x), (*ext y)),
3442   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3443   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3444   //
3445   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3446   //          (srl (*ext x), (*ext y))) ->
3447   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3448   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3449       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3450     SDValue InnerShifted = Shifted.getOperand(0);
3451     EVT InnerVT = InnerShifted.getValueType();
3452     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3453     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3454       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3455         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3456                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3457         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3458       }
3459     }
3460   }
3461
3462   return 0;
3463 }
3464
3465 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3466 // idioms for rotate, and if the target supports rotation instructions, generate
3467 // a rot[lr].
3468 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3469   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3470   EVT VT = LHS.getValueType();
3471   if (!TLI.isTypeLegal(VT)) return 0;
3472
3473   // The target must have at least one rotate flavor.
3474   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3475   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3476   if (!HasROTL && !HasROTR) return 0;
3477
3478   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3479   SDValue LHSShift;   // The shift.
3480   SDValue LHSMask;    // AND value if any.
3481   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3482     return 0; // Not part of a rotate.
3483
3484   SDValue RHSShift;   // The shift.
3485   SDValue RHSMask;    // AND value if any.
3486   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3487     return 0; // Not part of a rotate.
3488
3489   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3490     return 0;   // Not shifting the same value.
3491
3492   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3493     return 0;   // Shifts must disagree.
3494
3495   // Canonicalize shl to left side in a shl/srl pair.
3496   if (RHSShift.getOpcode() == ISD::SHL) {
3497     std::swap(LHS, RHS);
3498     std::swap(LHSShift, RHSShift);
3499     std::swap(LHSMask , RHSMask );
3500   }
3501
3502   unsigned OpSizeInBits = VT.getSizeInBits();
3503   SDValue LHSShiftArg = LHSShift.getOperand(0);
3504   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3505   SDValue RHSShiftArg = RHSShift.getOperand(0);
3506   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3507
3508   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3509   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3510   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3511       RHSShiftAmt.getOpcode() == ISD::Constant) {
3512     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3513     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3514     if ((LShVal + RShVal) != OpSizeInBits)
3515       return 0;
3516
3517     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3518                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3519
3520     // If there is an AND of either shifted operand, apply it to the result.
3521     if (LHSMask.getNode() || RHSMask.getNode()) {
3522       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3523
3524       if (LHSMask.getNode()) {
3525         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3526         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3527       }
3528       if (RHSMask.getNode()) {
3529         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3530         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3531       }
3532
3533       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3534     }
3535
3536     return Rot.getNode();
3537   }
3538
3539   // If there is a mask here, and we have a variable shift, we can't be sure
3540   // that we're masking out the right stuff.
3541   if (LHSMask.getNode() || RHSMask.getNode())
3542     return 0;
3543
3544   // If the shift amount is sign/zext/any-extended just peel it off.
3545   SDValue LExtOp0 = LHSShiftAmt;
3546   SDValue RExtOp0 = RHSShiftAmt;
3547   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3548        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3549        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3550        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3551       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3552        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3553        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3554        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3555     LExtOp0 = LHSShiftAmt.getOperand(0);
3556     RExtOp0 = RHSShiftAmt.getOperand(0);
3557   }
3558
3559   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3560                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3561   if (TryL)
3562     return TryL;
3563
3564   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3565                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3566   if (TryR)
3567     return TryR;
3568
3569   return 0;
3570 }
3571
3572 SDValue DAGCombiner::visitXOR(SDNode *N) {
3573   SDValue N0 = N->getOperand(0);
3574   SDValue N1 = N->getOperand(1);
3575   SDValue LHS, RHS, CC;
3576   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3577   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3578   EVT VT = N0.getValueType();
3579
3580   // fold vector ops
3581   if (VT.isVector()) {
3582     SDValue FoldedVOp = SimplifyVBinOp(N);
3583     if (FoldedVOp.getNode()) return FoldedVOp;
3584
3585     // fold (xor x, 0) -> x, vector edition
3586     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3587       return N1;
3588     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3589       return N0;
3590   }
3591
3592   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3593   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3594     return DAG.getConstant(0, VT);
3595   // fold (xor x, undef) -> undef
3596   if (N0.getOpcode() == ISD::UNDEF)
3597     return N0;
3598   if (N1.getOpcode() == ISD::UNDEF)
3599     return N1;
3600   // fold (xor c1, c2) -> c1^c2
3601   if (N0C && N1C)
3602     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3603   // canonicalize constant to RHS
3604   if (N0C && !N1C)
3605     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3606   // fold (xor x, 0) -> x
3607   if (N1C && N1C->isNullValue())
3608     return N0;
3609   // reassociate xor
3610   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3611   if (RXOR.getNode() != 0)
3612     return RXOR;
3613
3614   // fold !(x cc y) -> (x !cc y)
3615   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3616     bool isInt = LHS.getValueType().isInteger();
3617     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3618                                                isInt);
3619
3620     if (!LegalOperations ||
3621         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3622       switch (N0.getOpcode()) {
3623       default:
3624         llvm_unreachable("Unhandled SetCC Equivalent!");
3625       case ISD::SETCC:
3626         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3627       case ISD::SELECT_CC:
3628         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3629                                N0.getOperand(3), NotCC);
3630       }
3631     }
3632   }
3633
3634   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3635   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3636       N0.getNode()->hasOneUse() &&
3637       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3638     SDValue V = N0.getOperand(0);
3639     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3640                     DAG.getConstant(1, V.getValueType()));
3641     AddToWorkList(V.getNode());
3642     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3643   }
3644
3645   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3646   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3647       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3648     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3649     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3650       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3651       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3652       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3653       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3654       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3655     }
3656   }
3657   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3658   if (N1C && N1C->isAllOnesValue() &&
3659       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3660     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3661     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3662       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3663       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3664       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3665       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3666       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3667     }
3668   }
3669   // fold (xor (and x, y), y) -> (and (not x), y)
3670   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3671       N0->getOperand(1) == N1) {
3672     SDValue X = N0->getOperand(0);
3673     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3674     AddToWorkList(NotX.getNode());
3675     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3676   }
3677   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3678   if (N1C && N0.getOpcode() == ISD::XOR) {
3679     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3680     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3681     if (N00C)
3682       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3683                          DAG.getConstant(N1C->getAPIntValue() ^
3684                                          N00C->getAPIntValue(), VT));
3685     if (N01C)
3686       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3687                          DAG.getConstant(N1C->getAPIntValue() ^
3688                                          N01C->getAPIntValue(), VT));
3689   }
3690   // fold (xor x, x) -> 0
3691   if (N0 == N1)
3692     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3693
3694   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3695   if (N0.getOpcode() == N1.getOpcode()) {
3696     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3697     if (Tmp.getNode()) return Tmp;
3698   }
3699
3700   // Simplify the expression using non-local knowledge.
3701   if (!VT.isVector() &&
3702       SimplifyDemandedBits(SDValue(N, 0)))
3703     return SDValue(N, 0);
3704
3705   return SDValue();
3706 }
3707
3708 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3709 /// the shift amount is a constant.
3710 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3711   SDNode *LHS = N->getOperand(0).getNode();
3712   if (!LHS->hasOneUse()) return SDValue();
3713
3714   // We want to pull some binops through shifts, so that we have (and (shift))
3715   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3716   // thing happens with address calculations, so it's important to canonicalize
3717   // it.
3718   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3719
3720   switch (LHS->getOpcode()) {
3721   default: return SDValue();
3722   case ISD::OR:
3723   case ISD::XOR:
3724     HighBitSet = false; // We can only transform sra if the high bit is clear.
3725     break;
3726   case ISD::AND:
3727     HighBitSet = true;  // We can only transform sra if the high bit is set.
3728     break;
3729   case ISD::ADD:
3730     if (N->getOpcode() != ISD::SHL)
3731       return SDValue(); // only shl(add) not sr[al](add).
3732     HighBitSet = false; // We can only transform sra if the high bit is clear.
3733     break;
3734   }
3735
3736   // We require the RHS of the binop to be a constant as well.
3737   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3738   if (!BinOpCst) return SDValue();
3739
3740   // FIXME: disable this unless the input to the binop is a shift by a constant.
3741   // If it is not a shift, it pessimizes some common cases like:
3742   //
3743   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3744   //    int bar(int *X, int i) { return X[i & 255]; }
3745   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3746   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3747        BinOpLHSVal->getOpcode() != ISD::SRA &&
3748        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3749       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3750     return SDValue();
3751
3752   EVT VT = N->getValueType(0);
3753
3754   // If this is a signed shift right, and the high bit is modified by the
3755   // logical operation, do not perform the transformation. The highBitSet
3756   // boolean indicates the value of the high bit of the constant which would
3757   // cause it to be modified for this operation.
3758   if (N->getOpcode() == ISD::SRA) {
3759     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3760     if (BinOpRHSSignSet != HighBitSet)
3761       return SDValue();
3762   }
3763
3764   // Fold the constants, shifting the binop RHS by the shift amount.
3765   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3766                                N->getValueType(0),
3767                                LHS->getOperand(1), N->getOperand(1));
3768
3769   // Create the new shift.
3770   SDValue NewShift = DAG.getNode(N->getOpcode(),
3771                                  SDLoc(LHS->getOperand(0)),
3772                                  VT, LHS->getOperand(0), N->getOperand(1));
3773
3774   // Create the new binop.
3775   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3776 }
3777
3778 SDValue DAGCombiner::visitSHL(SDNode *N) {
3779   SDValue N0 = N->getOperand(0);
3780   SDValue N1 = N->getOperand(1);
3781   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3782   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3783   EVT VT = N0.getValueType();
3784   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3785
3786   // fold vector ops
3787   if (VT.isVector()) {
3788     SDValue FoldedVOp = SimplifyVBinOp(N);
3789     if (FoldedVOp.getNode()) return FoldedVOp;
3790   }
3791
3792   // fold (shl c1, c2) -> c1<<c2
3793   if (N0C && N1C)
3794     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3795   // fold (shl 0, x) -> 0
3796   if (N0C && N0C->isNullValue())
3797     return N0;
3798   // fold (shl x, c >= size(x)) -> undef
3799   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3800     return DAG.getUNDEF(VT);
3801   // fold (shl x, 0) -> x
3802   if (N1C && N1C->isNullValue())
3803     return N0;
3804   // fold (shl undef, x) -> 0
3805   if (N0.getOpcode() == ISD::UNDEF)
3806     return DAG.getConstant(0, VT);
3807   // if (shl x, c) is known to be zero, return 0
3808   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3809                             APInt::getAllOnesValue(OpSizeInBits)))
3810     return DAG.getConstant(0, VT);
3811   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3812   if (N1.getOpcode() == ISD::TRUNCATE &&
3813       N1.getOperand(0).getOpcode() == ISD::AND &&
3814       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3815     SDValue N101 = N1.getOperand(0).getOperand(1);
3816     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3817       EVT TruncVT = N1.getValueType();
3818       SDValue N100 = N1.getOperand(0).getOperand(0);
3819       APInt TruncC = N101C->getAPIntValue();
3820       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3821       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3822                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3823                                      DAG.getNode(ISD::TRUNCATE,
3824                                                  SDLoc(N),
3825                                                  TruncVT, N100),
3826                                      DAG.getConstant(TruncC, TruncVT)));
3827     }
3828   }
3829
3830   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3831     return SDValue(N, 0);
3832
3833   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3834   if (N1C && N0.getOpcode() == ISD::SHL &&
3835       N0.getOperand(1).getOpcode() == ISD::Constant) {
3836     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3837     uint64_t c2 = N1C->getZExtValue();
3838     if (c1 + c2 >= OpSizeInBits)
3839       return DAG.getConstant(0, VT);
3840     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3841                        DAG.getConstant(c1 + c2, N1.getValueType()));
3842   }
3843
3844   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3845   // For this to be valid, the second form must not preserve any of the bits
3846   // that are shifted out by the inner shift in the first form.  This means
3847   // the outer shift size must be >= the number of bits added by the ext.
3848   // As a corollary, we don't care what kind of ext it is.
3849   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3850               N0.getOpcode() == ISD::ANY_EXTEND ||
3851               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3852       N0.getOperand(0).getOpcode() == ISD::SHL &&
3853       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3854     uint64_t c1 =
3855       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3856     uint64_t c2 = N1C->getZExtValue();
3857     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3858     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3859     if (c2 >= OpSizeInBits - InnerShiftSize) {
3860       if (c1 + c2 >= OpSizeInBits)
3861         return DAG.getConstant(0, VT);
3862       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3863                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3864                                      N0.getOperand(0)->getOperand(0)),
3865                          DAG.getConstant(c1 + c2, N1.getValueType()));
3866     }
3867   }
3868
3869   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3870   // Only fold this if the inner zext has no other uses to avoid increasing
3871   // the total number of instructions.
3872   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3873       N0.getOperand(0).getOpcode() == ISD::SRL &&
3874       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3875     uint64_t c1 =
3876       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3877     if (c1 < VT.getSizeInBits()) {
3878       uint64_t c2 = N1C->getZExtValue();
3879       if (c1 == c2) {
3880         SDValue NewOp0 = N0.getOperand(0);
3881         EVT CountVT = NewOp0.getOperand(1).getValueType();
3882         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3883                                      NewOp0, DAG.getConstant(c2, CountVT));
3884         AddToWorkList(NewSHL.getNode());
3885         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3886       }
3887     }
3888   }
3889
3890   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3891   //                               (and (srl x, (sub c1, c2), MASK)
3892   // Only fold this if the inner shift has no other uses -- if it does, folding
3893   // this will increase the total number of instructions.
3894   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3895       N0.getOperand(1).getOpcode() == ISD::Constant) {
3896     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3897     if (c1 < VT.getSizeInBits()) {
3898       uint64_t c2 = N1C->getZExtValue();
3899       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3900                                          VT.getSizeInBits() - c1);
3901       SDValue Shift;
3902       if (c2 > c1) {
3903         Mask = Mask.shl(c2-c1);
3904         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3905                             DAG.getConstant(c2-c1, N1.getValueType()));
3906       } else {
3907         Mask = Mask.lshr(c1-c2);
3908         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3909                             DAG.getConstant(c1-c2, N1.getValueType()));
3910       }
3911       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3912                          DAG.getConstant(Mask, VT));
3913     }
3914   }
3915   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3916   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3917     SDValue HiBitsMask =
3918       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3919                                             VT.getSizeInBits() -
3920                                               N1C->getZExtValue()),
3921                       VT);
3922     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3923                        HiBitsMask);
3924   }
3925
3926   if (N1C) {
3927     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3928     if (NewSHL.getNode())
3929       return NewSHL;
3930   }
3931
3932   return SDValue();
3933 }
3934
3935 SDValue DAGCombiner::visitSRA(SDNode *N) {
3936   SDValue N0 = N->getOperand(0);
3937   SDValue N1 = N->getOperand(1);
3938   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3940   EVT VT = N0.getValueType();
3941   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3942
3943   // fold vector ops
3944   if (VT.isVector()) {
3945     SDValue FoldedVOp = SimplifyVBinOp(N);
3946     if (FoldedVOp.getNode()) return FoldedVOp;
3947   }
3948
3949   // fold (sra c1, c2) -> (sra c1, c2)
3950   if (N0C && N1C)
3951     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3952   // fold (sra 0, x) -> 0
3953   if (N0C && N0C->isNullValue())
3954     return N0;
3955   // fold (sra -1, x) -> -1
3956   if (N0C && N0C->isAllOnesValue())
3957     return N0;
3958   // fold (sra x, (setge c, size(x))) -> undef
3959   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3960     return DAG.getUNDEF(VT);
3961   // fold (sra x, 0) -> x
3962   if (N1C && N1C->isNullValue())
3963     return N0;
3964   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3965   // sext_inreg.
3966   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3967     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3968     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3969     if (VT.isVector())
3970       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3971                                ExtVT, VT.getVectorNumElements());
3972     if ((!LegalOperations ||
3973          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3974       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3975                          N0.getOperand(0), DAG.getValueType(ExtVT));
3976   }
3977
3978   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3979   if (N1C && N0.getOpcode() == ISD::SRA) {
3980     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3981       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3982       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3983       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3984                          DAG.getConstant(Sum, N1C->getValueType(0)));
3985     }
3986   }
3987
3988   // fold (sra (shl X, m), (sub result_size, n))
3989   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3990   // result_size - n != m.
3991   // If truncate is free for the target sext(shl) is likely to result in better
3992   // code.
3993   if (N0.getOpcode() == ISD::SHL) {
3994     // Get the two constanst of the shifts, CN0 = m, CN = n.
3995     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3996     if (N01C && N1C) {
3997       // Determine what the truncate's result bitsize and type would be.
3998       EVT TruncVT =
3999         EVT::getIntegerVT(*DAG.getContext(),
4000                           OpSizeInBits - N1C->getZExtValue());
4001       // Determine the residual right-shift amount.
4002       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4003
4004       // If the shift is not a no-op (in which case this should be just a sign
4005       // extend already), the truncated to type is legal, sign_extend is legal
4006       // on that type, and the truncate to that type is both legal and free,
4007       // perform the transform.
4008       if ((ShiftAmt > 0) &&
4009           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4010           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4011           TLI.isTruncateFree(VT, TruncVT)) {
4012
4013           SDValue Amt = DAG.getConstant(ShiftAmt,
4014               getShiftAmountTy(N0.getOperand(0).getValueType()));
4015           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4016                                       N0.getOperand(0), Amt);
4017           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4018                                       Shift);
4019           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4020                              N->getValueType(0), Trunc);
4021       }
4022     }
4023   }
4024
4025   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4026   if (N1.getOpcode() == ISD::TRUNCATE &&
4027       N1.getOperand(0).getOpcode() == ISD::AND &&
4028       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4029     SDValue N101 = N1.getOperand(0).getOperand(1);
4030     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4031       EVT TruncVT = N1.getValueType();
4032       SDValue N100 = N1.getOperand(0).getOperand(0);
4033       APInt TruncC = N101C->getAPIntValue();
4034       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4035       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4036                          DAG.getNode(ISD::AND, SDLoc(N),
4037                                      TruncVT,
4038                                      DAG.getNode(ISD::TRUNCATE,
4039                                                  SDLoc(N),
4040                                                  TruncVT, N100),
4041                                      DAG.getConstant(TruncC, TruncVT)));
4042     }
4043   }
4044
4045   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4046   //      if c1 is equal to the number of bits the trunc removes
4047   if (N0.getOpcode() == ISD::TRUNCATE &&
4048       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4049        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4050       N0.getOperand(0).hasOneUse() &&
4051       N0.getOperand(0).getOperand(1).hasOneUse() &&
4052       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4053     EVT LargeVT = N0.getOperand(0).getValueType();
4054     ConstantSDNode *LargeShiftAmt =
4055       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4056
4057     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4058         LargeShiftAmt->getZExtValue()) {
4059       SDValue Amt =
4060         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4061               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4062       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4063                                 N0.getOperand(0).getOperand(0), Amt);
4064       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4065     }
4066   }
4067
4068   // Simplify, based on bits shifted out of the LHS.
4069   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4070     return SDValue(N, 0);
4071
4072
4073   // If the sign bit is known to be zero, switch this to a SRL.
4074   if (DAG.SignBitIsZero(N0))
4075     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4076
4077   if (N1C) {
4078     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4079     if (NewSRA.getNode())
4080       return NewSRA;
4081   }
4082
4083   return SDValue();
4084 }
4085
4086 SDValue DAGCombiner::visitSRL(SDNode *N) {
4087   SDValue N0 = N->getOperand(0);
4088   SDValue N1 = N->getOperand(1);
4089   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4090   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4091   EVT VT = N0.getValueType();
4092   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4093
4094   // fold vector ops
4095   if (VT.isVector()) {
4096     SDValue FoldedVOp = SimplifyVBinOp(N);
4097     if (FoldedVOp.getNode()) return FoldedVOp;
4098   }
4099
4100   // fold (srl c1, c2) -> c1 >>u c2
4101   if (N0C && N1C)
4102     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4103   // fold (srl 0, x) -> 0
4104   if (N0C && N0C->isNullValue())
4105     return N0;
4106   // fold (srl x, c >= size(x)) -> undef
4107   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4108     return DAG.getUNDEF(VT);
4109   // fold (srl x, 0) -> x
4110   if (N1C && N1C->isNullValue())
4111     return N0;
4112   // if (srl x, c) is known to be zero, return 0
4113   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4114                                    APInt::getAllOnesValue(OpSizeInBits)))
4115     return DAG.getConstant(0, VT);
4116
4117   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4118   if (N1C && N0.getOpcode() == ISD::SRL &&
4119       N0.getOperand(1).getOpcode() == ISD::Constant) {
4120     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4121     uint64_t c2 = N1C->getZExtValue();
4122     if (c1 + c2 >= OpSizeInBits)
4123       return DAG.getConstant(0, VT);
4124     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4125                        DAG.getConstant(c1 + c2, N1.getValueType()));
4126   }
4127
4128   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4129   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4130       N0.getOperand(0).getOpcode() == ISD::SRL &&
4131       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4132     uint64_t c1 =
4133       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4134     uint64_t c2 = N1C->getZExtValue();
4135     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4136     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4137     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4138     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4139     if (c1 + OpSizeInBits == InnerShiftSize) {
4140       if (c1 + c2 >= InnerShiftSize)
4141         return DAG.getConstant(0, VT);
4142       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4143                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4144                                      N0.getOperand(0)->getOperand(0),
4145                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4146     }
4147   }
4148
4149   // fold (srl (shl x, c), c) -> (and x, cst2)
4150   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4151       N0.getValueSizeInBits() <= 64) {
4152     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4153     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4154                        DAG.getConstant(~0ULL >> ShAmt, VT));
4155   }
4156
4157   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4158   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4159     // Shifting in all undef bits?
4160     EVT SmallVT = N0.getOperand(0).getValueType();
4161     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4162       return DAG.getUNDEF(VT);
4163
4164     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4165       uint64_t ShiftAmt = N1C->getZExtValue();
4166       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4167                                        N0.getOperand(0),
4168                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4169       AddToWorkList(SmallShift.getNode());
4170       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4171       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4172                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4173                          DAG.getConstant(Mask, VT));
4174     }
4175   }
4176
4177   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4178   // bit, which is unmodified by sra.
4179   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4180     if (N0.getOpcode() == ISD::SRA)
4181       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4182   }
4183
4184   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4185   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4186       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4187     APInt KnownZero, KnownOne;
4188     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4189
4190     // If any of the input bits are KnownOne, then the input couldn't be all
4191     // zeros, thus the result of the srl will always be zero.
4192     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4193
4194     // If all of the bits input the to ctlz node are known to be zero, then
4195     // the result of the ctlz is "32" and the result of the shift is one.
4196     APInt UnknownBits = ~KnownZero;
4197     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4198
4199     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4200     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4201       // Okay, we know that only that the single bit specified by UnknownBits
4202       // could be set on input to the CTLZ node. If this bit is set, the SRL
4203       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4204       // to an SRL/XOR pair, which is likely to simplify more.
4205       unsigned ShAmt = UnknownBits.countTrailingZeros();
4206       SDValue Op = N0.getOperand(0);
4207
4208       if (ShAmt) {
4209         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4210                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4211         AddToWorkList(Op.getNode());
4212       }
4213
4214       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4215                          Op, DAG.getConstant(1, VT));
4216     }
4217   }
4218
4219   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4220   if (N1.getOpcode() == ISD::TRUNCATE &&
4221       N1.getOperand(0).getOpcode() == ISD::AND &&
4222       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4223     SDValue N101 = N1.getOperand(0).getOperand(1);
4224     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4225       EVT TruncVT = N1.getValueType();
4226       SDValue N100 = N1.getOperand(0).getOperand(0);
4227       APInt TruncC = N101C->getAPIntValue();
4228       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4229       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4230                          DAG.getNode(ISD::AND, SDLoc(N),
4231                                      TruncVT,
4232                                      DAG.getNode(ISD::TRUNCATE,
4233                                                  SDLoc(N),
4234                                                  TruncVT, N100),
4235                                      DAG.getConstant(TruncC, TruncVT)));
4236     }
4237   }
4238
4239   // fold operands of srl based on knowledge that the low bits are not
4240   // demanded.
4241   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4242     return SDValue(N, 0);
4243
4244   if (N1C) {
4245     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4246     if (NewSRL.getNode())
4247       return NewSRL;
4248   }
4249
4250   // Attempt to convert a srl of a load into a narrower zero-extending load.
4251   SDValue NarrowLoad = ReduceLoadWidth(N);
4252   if (NarrowLoad.getNode())
4253     return NarrowLoad;
4254
4255   // Here is a common situation. We want to optimize:
4256   //
4257   //   %a = ...
4258   //   %b = and i32 %a, 2
4259   //   %c = srl i32 %b, 1
4260   //   brcond i32 %c ...
4261   //
4262   // into
4263   //
4264   //   %a = ...
4265   //   %b = and %a, 2
4266   //   %c = setcc eq %b, 0
4267   //   brcond %c ...
4268   //
4269   // However when after the source operand of SRL is optimized into AND, the SRL
4270   // itself may not be optimized further. Look for it and add the BRCOND into
4271   // the worklist.
4272   if (N->hasOneUse()) {
4273     SDNode *Use = *N->use_begin();
4274     if (Use->getOpcode() == ISD::BRCOND)
4275       AddToWorkList(Use);
4276     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4277       // Also look pass the truncate.
4278       Use = *Use->use_begin();
4279       if (Use->getOpcode() == ISD::BRCOND)
4280         AddToWorkList(Use);
4281     }
4282   }
4283
4284   return SDValue();
4285 }
4286
4287 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4288   SDValue N0 = N->getOperand(0);
4289   EVT VT = N->getValueType(0);
4290
4291   // fold (ctlz c1) -> c2
4292   if (isa<ConstantSDNode>(N0))
4293     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4294   return SDValue();
4295 }
4296
4297 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4298   SDValue N0 = N->getOperand(0);
4299   EVT VT = N->getValueType(0);
4300
4301   // fold (ctlz_zero_undef c1) -> c2
4302   if (isa<ConstantSDNode>(N0))
4303     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4304   return SDValue();
4305 }
4306
4307 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4308   SDValue N0 = N->getOperand(0);
4309   EVT VT = N->getValueType(0);
4310
4311   // fold (cttz c1) -> c2
4312   if (isa<ConstantSDNode>(N0))
4313     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4314   return SDValue();
4315 }
4316
4317 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4318   SDValue N0 = N->getOperand(0);
4319   EVT VT = N->getValueType(0);
4320
4321   // fold (cttz_zero_undef c1) -> c2
4322   if (isa<ConstantSDNode>(N0))
4323     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4324   return SDValue();
4325 }
4326
4327 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4328   SDValue N0 = N->getOperand(0);
4329   EVT VT = N->getValueType(0);
4330
4331   // fold (ctpop c1) -> c2
4332   if (isa<ConstantSDNode>(N0))
4333     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4334   return SDValue();
4335 }
4336
4337 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4338   SDValue N0 = N->getOperand(0);
4339   SDValue N1 = N->getOperand(1);
4340   SDValue N2 = N->getOperand(2);
4341   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4342   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4343   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4344   EVT VT = N->getValueType(0);
4345   EVT VT0 = N0.getValueType();
4346
4347   // fold (select C, X, X) -> X
4348   if (N1 == N2)
4349     return N1;
4350   // fold (select true, X, Y) -> X
4351   if (N0C && !N0C->isNullValue())
4352     return N1;
4353   // fold (select false, X, Y) -> Y
4354   if (N0C && N0C->isNullValue())
4355     return N2;
4356   // fold (select C, 1, X) -> (or C, X)
4357   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4358     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4359   // fold (select C, 0, 1) -> (xor C, 1)
4360   if (VT.isInteger() &&
4361       (VT0 == MVT::i1 ||
4362        (VT0.isInteger() &&
4363         TLI.getBooleanContents(false) ==
4364         TargetLowering::ZeroOrOneBooleanContent)) &&
4365       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4366     SDValue XORNode;
4367     if (VT == VT0)
4368       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4369                          N0, DAG.getConstant(1, VT0));
4370     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4371                           N0, DAG.getConstant(1, VT0));
4372     AddToWorkList(XORNode.getNode());
4373     if (VT.bitsGT(VT0))
4374       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4375     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4376   }
4377   // fold (select C, 0, X) -> (and (not C), X)
4378   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4379     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4380     AddToWorkList(NOTNode.getNode());
4381     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4382   }
4383   // fold (select C, X, 1) -> (or (not C), X)
4384   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4385     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4386     AddToWorkList(NOTNode.getNode());
4387     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4388   }
4389   // fold (select C, X, 0) -> (and C, X)
4390   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4391     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4392   // fold (select X, X, Y) -> (or X, Y)
4393   // fold (select X, 1, Y) -> (or X, Y)
4394   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4395     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4396   // fold (select X, Y, X) -> (and X, Y)
4397   // fold (select X, Y, 0) -> (and X, Y)
4398   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4399     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4400
4401   // If we can fold this based on the true/false value, do so.
4402   if (SimplifySelectOps(N, N1, N2))
4403     return SDValue(N, 0);  // Don't revisit N.
4404
4405   // fold selects based on a setcc into other things, such as min/max/abs
4406   if (N0.getOpcode() == ISD::SETCC) {
4407     // FIXME:
4408     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4409     // having to say they don't support SELECT_CC on every type the DAG knows
4410     // about, since there is no way to mark an opcode illegal at all value types
4411     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4412         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4413       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4414                          N0.getOperand(0), N0.getOperand(1),
4415                          N1, N2, N0.getOperand(2));
4416     return SimplifySelect(SDLoc(N), N0, N1, N2);
4417   }
4418
4419   return SDValue();
4420 }
4421
4422 static
4423 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4424   SDLoc DL(N);
4425   EVT LoVT, HiVT;
4426   llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4427
4428   // Split the inputs.
4429   SDValue Lo, Hi, LL, LH, RL, RH;
4430   llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4431   llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4432
4433   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4434   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4435
4436   return std::make_pair(Lo, Hi);
4437 }
4438
4439 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4440   SDValue N0 = N->getOperand(0);
4441   SDValue N1 = N->getOperand(1);
4442   SDValue N2 = N->getOperand(2);
4443   SDLoc DL(N);
4444
4445   // Canonicalize integer abs.
4446   // vselect (setg[te] X,  0),  X, -X ->
4447   // vselect (setgt    X, -1),  X, -X ->
4448   // vselect (setl[te] X,  0), -X,  X ->
4449   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4450   if (N0.getOpcode() == ISD::SETCC) {
4451     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4452     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4453     bool isAbs = false;
4454     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4455
4456     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4457          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4458         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4459       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4460     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4461              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4462       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4463
4464     if (isAbs) {
4465       EVT VT = LHS.getValueType();
4466       SDValue Shift = DAG.getNode(
4467           ISD::SRA, DL, VT, LHS,
4468           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4469       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4470       AddToWorkList(Shift.getNode());
4471       AddToWorkList(Add.getNode());
4472       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4473     }
4474   }
4475
4476   // If the VSELECT result requires splitting and the mask is provided by a
4477   // SETCC, then split both nodes and its operands before legalization. This
4478   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4479   // and enables future optimizations (e.g. min/max pattern matching on X86).
4480   if (N0.getOpcode() == ISD::SETCC) {
4481     EVT VT = N->getValueType(0);
4482
4483     // Check if any splitting is required.
4484     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4485         TargetLowering::TypeSplitVector)
4486       return SDValue();
4487
4488     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4489     llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4490     llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4491     llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4492
4493     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4494     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4495
4496     // Add the new VSELECT nodes to the work list in case they need to be split
4497     // again.
4498     AddToWorkList(Lo.getNode());
4499     AddToWorkList(Hi.getNode());
4500
4501     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4502   }
4503
4504   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4505   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4506     return N1;
4507   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4508   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4509     return N2;
4510
4511   return SDValue();
4512 }
4513
4514 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4515   SDValue N0 = N->getOperand(0);
4516   SDValue N1 = N->getOperand(1);
4517   SDValue N2 = N->getOperand(2);
4518   SDValue N3 = N->getOperand(3);
4519   SDValue N4 = N->getOperand(4);
4520   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4521
4522   // fold select_cc lhs, rhs, x, x, cc -> x
4523   if (N2 == N3)
4524     return N2;
4525
4526   // Determine if the condition we're dealing with is constant
4527   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4528                               N0, N1, CC, SDLoc(N), false);
4529   if (SCC.getNode()) {
4530     AddToWorkList(SCC.getNode());
4531
4532     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4533       if (!SCCC->isNullValue())
4534         return N2;    // cond always true -> true val
4535       else
4536         return N3;    // cond always false -> false val
4537     }
4538
4539     // Fold to a simpler select_cc
4540     if (SCC.getOpcode() == ISD::SETCC)
4541       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4542                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4543                          SCC.getOperand(2));
4544   }
4545
4546   // If we can fold this based on the true/false value, do so.
4547   if (SimplifySelectOps(N, N2, N3))
4548     return SDValue(N, 0);  // Don't revisit N.
4549
4550   // fold select_cc into other things, such as min/max/abs
4551   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4552 }
4553
4554 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4555   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4556                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4557                        SDLoc(N));
4558 }
4559
4560 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4561 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4562 // transformation. Returns true if extension are possible and the above
4563 // mentioned transformation is profitable.
4564 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4565                                     unsigned ExtOpc,
4566                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4567                                     const TargetLowering &TLI) {
4568   bool HasCopyToRegUses = false;
4569   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4570   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4571                             UE = N0.getNode()->use_end();
4572        UI != UE; ++UI) {
4573     SDNode *User = *UI;
4574     if (User == N)
4575       continue;
4576     if (UI.getUse().getResNo() != N0.getResNo())
4577       continue;
4578     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4579     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4580       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4581       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4582         // Sign bits will be lost after a zext.
4583         return false;
4584       bool Add = false;
4585       for (unsigned i = 0; i != 2; ++i) {
4586         SDValue UseOp = User->getOperand(i);
4587         if (UseOp == N0)
4588           continue;
4589         if (!isa<ConstantSDNode>(UseOp))
4590           return false;
4591         Add = true;
4592       }
4593       if (Add)
4594         ExtendNodes.push_back(User);
4595       continue;
4596     }
4597     // If truncates aren't free and there are users we can't
4598     // extend, it isn't worthwhile.
4599     if (!isTruncFree)
4600       return false;
4601     // Remember if this value is live-out.
4602     if (User->getOpcode() == ISD::CopyToReg)
4603       HasCopyToRegUses = true;
4604   }
4605
4606   if (HasCopyToRegUses) {
4607     bool BothLiveOut = false;
4608     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4609          UI != UE; ++UI) {
4610       SDUse &Use = UI.getUse();
4611       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4612         BothLiveOut = true;
4613         break;
4614       }
4615     }
4616     if (BothLiveOut)
4617       // Both unextended and extended values are live out. There had better be
4618       // a good reason for the transformation.
4619       return ExtendNodes.size();
4620   }
4621   return true;
4622 }
4623
4624 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4625                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4626                                   ISD::NodeType ExtType) {
4627   // Extend SetCC uses if necessary.
4628   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4629     SDNode *SetCC = SetCCs[i];
4630     SmallVector<SDValue, 4> Ops;
4631
4632     for (unsigned j = 0; j != 2; ++j) {
4633       SDValue SOp = SetCC->getOperand(j);
4634       if (SOp == Trunc)
4635         Ops.push_back(ExtLoad);
4636       else
4637         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4638     }
4639
4640     Ops.push_back(SetCC->getOperand(2));
4641     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4642                                  &Ops[0], Ops.size()));
4643   }
4644 }
4645
4646 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4647   SDValue N0 = N->getOperand(0);
4648   EVT VT = N->getValueType(0);
4649
4650   // fold (sext c1) -> c1
4651   if (isa<ConstantSDNode>(N0))
4652     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4653
4654   // fold (sext (sext x)) -> (sext x)
4655   // fold (sext (aext x)) -> (sext x)
4656   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4657     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4658                        N0.getOperand(0));
4659
4660   if (N0.getOpcode() == ISD::TRUNCATE) {
4661     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4662     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4663     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4664     if (NarrowLoad.getNode()) {
4665       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4666       if (NarrowLoad.getNode() != N0.getNode()) {
4667         CombineTo(N0.getNode(), NarrowLoad);
4668         // CombineTo deleted the truncate, if needed, but not what's under it.
4669         AddToWorkList(oye);
4670       }
4671       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4672     }
4673
4674     // See if the value being truncated is already sign extended.  If so, just
4675     // eliminate the trunc/sext pair.
4676     SDValue Op = N0.getOperand(0);
4677     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4678     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4679     unsigned DestBits = VT.getScalarType().getSizeInBits();
4680     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4681
4682     if (OpBits == DestBits) {
4683       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4684       // bits, it is already ready.
4685       if (NumSignBits > DestBits-MidBits)
4686         return Op;
4687     } else if (OpBits < DestBits) {
4688       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4689       // bits, just sext from i32.
4690       if (NumSignBits > OpBits-MidBits)
4691         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4692     } else {
4693       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4694       // bits, just truncate to i32.
4695       if (NumSignBits > OpBits-MidBits)
4696         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4697     }
4698
4699     // fold (sext (truncate x)) -> (sextinreg x).
4700     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4701                                                  N0.getValueType())) {
4702       if (OpBits < DestBits)
4703         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4704       else if (OpBits > DestBits)
4705         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4706       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4707                          DAG.getValueType(N0.getValueType()));
4708     }
4709   }
4710
4711   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4712   // None of the supported targets knows how to perform load and sign extend
4713   // on vectors in one instruction.  We only perform this transformation on
4714   // scalars.
4715   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4716       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4717        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4718     bool DoXform = true;
4719     SmallVector<SDNode*, 4> SetCCs;
4720     if (!N0.hasOneUse())
4721       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4722     if (DoXform) {
4723       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4724       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4725                                        LN0->getChain(),
4726                                        LN0->getBasePtr(), N0.getValueType(),
4727                                        LN0->getMemOperand());
4728       CombineTo(N, ExtLoad);
4729       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4730                                   N0.getValueType(), ExtLoad);
4731       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4732       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4733                       ISD::SIGN_EXTEND);
4734       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4735     }
4736   }
4737
4738   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4739   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4740   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4741       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4742     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4743     EVT MemVT = LN0->getMemoryVT();
4744     if ((!LegalOperations && !LN0->isVolatile()) ||
4745         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4746       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4747                                        LN0->getChain(),
4748                                        LN0->getBasePtr(), MemVT,
4749                                        LN0->getMemOperand());
4750       CombineTo(N, ExtLoad);
4751       CombineTo(N0.getNode(),
4752                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4753                             N0.getValueType(), ExtLoad),
4754                 ExtLoad.getValue(1));
4755       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4756     }
4757   }
4758
4759   // fold (sext (and/or/xor (load x), cst)) ->
4760   //      (and/or/xor (sextload x), (sext cst))
4761   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4762        N0.getOpcode() == ISD::XOR) &&
4763       isa<LoadSDNode>(N0.getOperand(0)) &&
4764       N0.getOperand(1).getOpcode() == ISD::Constant &&
4765       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4766       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4767     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4768     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4769       bool DoXform = true;
4770       SmallVector<SDNode*, 4> SetCCs;
4771       if (!N0.hasOneUse())
4772         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4773                                           SetCCs, TLI);
4774       if (DoXform) {
4775         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4776                                          LN0->getChain(), LN0->getBasePtr(),
4777                                          LN0->getMemoryVT(),
4778                                          LN0->getMemOperand());
4779         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4780         Mask = Mask.sext(VT.getSizeInBits());
4781         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4782                                   ExtLoad, DAG.getConstant(Mask, VT));
4783         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4784                                     SDLoc(N0.getOperand(0)),
4785                                     N0.getOperand(0).getValueType(), ExtLoad);
4786         CombineTo(N, And);
4787         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4788         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4789                         ISD::SIGN_EXTEND);
4790         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4791       }
4792     }
4793   }
4794
4795   if (N0.getOpcode() == ISD::SETCC) {
4796     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4797     // Only do this before legalize for now.
4798     if (VT.isVector() && !LegalOperations &&
4799         TLI.getBooleanContents(true) ==
4800           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4801       EVT N0VT = N0.getOperand(0).getValueType();
4802       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4803       // of the same size as the compared operands. Only optimize sext(setcc())
4804       // if this is the case.
4805       EVT SVT = getSetCCResultType(N0VT);
4806
4807       // We know that the # elements of the results is the same as the
4808       // # elements of the compare (and the # elements of the compare result
4809       // for that matter).  Check to see that they are the same size.  If so,
4810       // we know that the element size of the sext'd result matches the
4811       // element size of the compare operands.
4812       if (VT.getSizeInBits() == SVT.getSizeInBits())
4813         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4814                              N0.getOperand(1),
4815                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4816
4817       // If the desired elements are smaller or larger than the source
4818       // elements we can use a matching integer vector type and then
4819       // truncate/sign extend
4820       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4821       if (SVT == MatchingVectorType) {
4822         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4823                                N0.getOperand(0), N0.getOperand(1),
4824                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4825         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4826       }
4827     }
4828
4829     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4830     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4831     SDValue NegOne =
4832       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4833     SDValue SCC =
4834       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4835                        NegOne, DAG.getConstant(0, VT),
4836                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4837     if (SCC.getNode()) return SCC;
4838     if (!VT.isVector() &&
4839         (!LegalOperations ||
4840          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4841       return DAG.getSelect(SDLoc(N), VT,
4842                            DAG.getSetCC(SDLoc(N),
4843                            getSetCCResultType(VT),
4844                            N0.getOperand(0), N0.getOperand(1),
4845                            cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4846                            NegOne, DAG.getConstant(0, VT));
4847     }
4848   }
4849
4850   // fold (sext x) -> (zext x) if the sign bit is known zero.
4851   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4852       DAG.SignBitIsZero(N0))
4853     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4854
4855   return SDValue();
4856 }
4857
4858 // isTruncateOf - If N is a truncate of some other value, return true, record
4859 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4860 // This function computes KnownZero to avoid a duplicated call to
4861 // ComputeMaskedBits in the caller.
4862 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4863                          APInt &KnownZero) {
4864   APInt KnownOne;
4865   if (N->getOpcode() == ISD::TRUNCATE) {
4866     Op = N->getOperand(0);
4867     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4868     return true;
4869   }
4870
4871   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4872       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4873     return false;
4874
4875   SDValue Op0 = N->getOperand(0);
4876   SDValue Op1 = N->getOperand(1);
4877   assert(Op0.getValueType() == Op1.getValueType());
4878
4879   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4880   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4881   if (COp0 && COp0->isNullValue())
4882     Op = Op1;
4883   else if (COp1 && COp1->isNullValue())
4884     Op = Op0;
4885   else
4886     return false;
4887
4888   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4889
4890   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4891     return false;
4892
4893   return true;
4894 }
4895
4896 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4897   SDValue N0 = N->getOperand(0);
4898   EVT VT = N->getValueType(0);
4899
4900   // fold (zext c1) -> c1
4901   if (isa<ConstantSDNode>(N0))
4902     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4903   // fold (zext (zext x)) -> (zext x)
4904   // fold (zext (aext x)) -> (zext x)
4905   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4906     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4907                        N0.getOperand(0));
4908
4909   // fold (zext (truncate x)) -> (zext x) or
4910   //      (zext (truncate x)) -> (truncate x)
4911   // This is valid when the truncated bits of x are already zero.
4912   // FIXME: We should extend this to work for vectors too.
4913   SDValue Op;
4914   APInt KnownZero;
4915   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4916     APInt TruncatedBits =
4917       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4918       APInt(Op.getValueSizeInBits(), 0) :
4919       APInt::getBitsSet(Op.getValueSizeInBits(),
4920                         N0.getValueSizeInBits(),
4921                         std::min(Op.getValueSizeInBits(),
4922                                  VT.getSizeInBits()));
4923     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4924       if (VT.bitsGT(Op.getValueType()))
4925         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4926       if (VT.bitsLT(Op.getValueType()))
4927         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4928
4929       return Op;
4930     }
4931   }
4932
4933   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4934   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4935   if (N0.getOpcode() == ISD::TRUNCATE) {
4936     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4937     if (NarrowLoad.getNode()) {
4938       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4939       if (NarrowLoad.getNode() != N0.getNode()) {
4940         CombineTo(N0.getNode(), NarrowLoad);
4941         // CombineTo deleted the truncate, if needed, but not what's under it.
4942         AddToWorkList(oye);
4943       }
4944       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4945     }
4946   }
4947
4948   // fold (zext (truncate x)) -> (and x, mask)
4949   if (N0.getOpcode() == ISD::TRUNCATE &&
4950       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4951
4952     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4953     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4954     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4955     if (NarrowLoad.getNode()) {
4956       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4957       if (NarrowLoad.getNode() != N0.getNode()) {
4958         CombineTo(N0.getNode(), NarrowLoad);
4959         // CombineTo deleted the truncate, if needed, but not what's under it.
4960         AddToWorkList(oye);
4961       }
4962       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4963     }
4964
4965     SDValue Op = N0.getOperand(0);
4966     if (Op.getValueType().bitsLT(VT)) {
4967       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4968       AddToWorkList(Op.getNode());
4969     } else if (Op.getValueType().bitsGT(VT)) {
4970       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4971       AddToWorkList(Op.getNode());
4972     }
4973     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4974                                   N0.getValueType().getScalarType());
4975   }
4976
4977   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4978   // if either of the casts is not free.
4979   if (N0.getOpcode() == ISD::AND &&
4980       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4981       N0.getOperand(1).getOpcode() == ISD::Constant &&
4982       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4983                            N0.getValueType()) ||
4984        !TLI.isZExtFree(N0.getValueType(), VT))) {
4985     SDValue X = N0.getOperand(0).getOperand(0);
4986     if (X.getValueType().bitsLT(VT)) {
4987       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4988     } else if (X.getValueType().bitsGT(VT)) {
4989       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4990     }
4991     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4992     Mask = Mask.zext(VT.getSizeInBits());
4993     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4994                        X, DAG.getConstant(Mask, VT));
4995   }
4996
4997   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4998   // None of the supported targets knows how to perform load and vector_zext
4999   // on vectors in one instruction.  We only perform this transformation on
5000   // scalars.
5001   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5002       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5003        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5004     bool DoXform = true;
5005     SmallVector<SDNode*, 4> SetCCs;
5006     if (!N0.hasOneUse())
5007       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5008     if (DoXform) {
5009       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5010       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5011                                        LN0->getChain(),
5012                                        LN0->getBasePtr(), N0.getValueType(),
5013                                        LN0->getMemOperand());
5014       CombineTo(N, ExtLoad);
5015       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5016                                   N0.getValueType(), ExtLoad);
5017       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5018
5019       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5020                       ISD::ZERO_EXTEND);
5021       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5022     }
5023   }
5024
5025   // fold (zext (and/or/xor (load x), cst)) ->
5026   //      (and/or/xor (zextload x), (zext cst))
5027   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5028        N0.getOpcode() == ISD::XOR) &&
5029       isa<LoadSDNode>(N0.getOperand(0)) &&
5030       N0.getOperand(1).getOpcode() == ISD::Constant &&
5031       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5032       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5033     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5034     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5035       bool DoXform = true;
5036       SmallVector<SDNode*, 4> SetCCs;
5037       if (!N0.hasOneUse())
5038         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5039                                           SetCCs, TLI);
5040       if (DoXform) {
5041         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5042                                          LN0->getChain(), LN0->getBasePtr(),
5043                                          LN0->getMemoryVT(),
5044                                          LN0->getMemOperand());
5045         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5046         Mask = Mask.zext(VT.getSizeInBits());
5047         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5048                                   ExtLoad, DAG.getConstant(Mask, VT));
5049         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5050                                     SDLoc(N0.getOperand(0)),
5051                                     N0.getOperand(0).getValueType(), ExtLoad);
5052         CombineTo(N, And);
5053         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5054         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5055                         ISD::ZERO_EXTEND);
5056         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5057       }
5058     }
5059   }
5060
5061   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5062   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5063   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5064       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5065     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5066     EVT MemVT = LN0->getMemoryVT();
5067     if ((!LegalOperations && !LN0->isVolatile()) ||
5068         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5069       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5070                                        LN0->getChain(),
5071                                        LN0->getBasePtr(), MemVT,
5072                                        LN0->getMemOperand());
5073       CombineTo(N, ExtLoad);
5074       CombineTo(N0.getNode(),
5075                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5076                             ExtLoad),
5077                 ExtLoad.getValue(1));
5078       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5079     }
5080   }
5081
5082   if (N0.getOpcode() == ISD::SETCC) {
5083     if (!LegalOperations && VT.isVector() &&
5084         N0.getValueType().getVectorElementType() == MVT::i1) {
5085       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5086       // Only do this before legalize for now.
5087       EVT N0VT = N0.getOperand(0).getValueType();
5088       EVT EltVT = VT.getVectorElementType();
5089       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5090                                     DAG.getConstant(1, EltVT));
5091       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5092         // We know that the # elements of the results is the same as the
5093         // # elements of the compare (and the # elements of the compare result
5094         // for that matter).  Check to see that they are the same size.  If so,
5095         // we know that the element size of the sext'd result matches the
5096         // element size of the compare operands.
5097         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5098                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5099                                          N0.getOperand(1),
5100                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5101                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5102                                        &OneOps[0], OneOps.size()));
5103
5104       // If the desired elements are smaller or larger than the source
5105       // elements we can use a matching integer vector type and then
5106       // truncate/sign extend
5107       EVT MatchingElementType =
5108         EVT::getIntegerVT(*DAG.getContext(),
5109                           N0VT.getScalarType().getSizeInBits());
5110       EVT MatchingVectorType =
5111         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5112                          N0VT.getVectorNumElements());
5113       SDValue VsetCC =
5114         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5115                       N0.getOperand(1),
5116                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5117       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5118                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5119                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5120                                      &OneOps[0], OneOps.size()));
5121     }
5122
5123     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5124     SDValue SCC =
5125       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5126                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5127                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5128     if (SCC.getNode()) return SCC;
5129   }
5130
5131   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5132   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5133       isa<ConstantSDNode>(N0.getOperand(1)) &&
5134       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5135       N0.hasOneUse()) {
5136     SDValue ShAmt = N0.getOperand(1);
5137     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5138     if (N0.getOpcode() == ISD::SHL) {
5139       SDValue InnerZExt = N0.getOperand(0);
5140       // If the original shl may be shifting out bits, do not perform this
5141       // transformation.
5142       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5143         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5144       if (ShAmtVal > KnownZeroBits)
5145         return SDValue();
5146     }
5147
5148     SDLoc DL(N);
5149
5150     // Ensure that the shift amount is wide enough for the shifted value.
5151     if (VT.getSizeInBits() >= 256)
5152       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5153
5154     return DAG.getNode(N0.getOpcode(), DL, VT,
5155                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5156                        ShAmt);
5157   }
5158
5159   return SDValue();
5160 }
5161
5162 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5163   SDValue N0 = N->getOperand(0);
5164   EVT VT = N->getValueType(0);
5165
5166   // fold (aext c1) -> c1
5167   if (isa<ConstantSDNode>(N0))
5168     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5169   // fold (aext (aext x)) -> (aext x)
5170   // fold (aext (zext x)) -> (zext x)
5171   // fold (aext (sext x)) -> (sext x)
5172   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5173       N0.getOpcode() == ISD::ZERO_EXTEND ||
5174       N0.getOpcode() == ISD::SIGN_EXTEND)
5175     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5176
5177   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5178   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5179   if (N0.getOpcode() == ISD::TRUNCATE) {
5180     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5181     if (NarrowLoad.getNode()) {
5182       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5183       if (NarrowLoad.getNode() != N0.getNode()) {
5184         CombineTo(N0.getNode(), NarrowLoad);
5185         // CombineTo deleted the truncate, if needed, but not what's under it.
5186         AddToWorkList(oye);
5187       }
5188       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5189     }
5190   }
5191
5192   // fold (aext (truncate x))
5193   if (N0.getOpcode() == ISD::TRUNCATE) {
5194     SDValue TruncOp = N0.getOperand(0);
5195     if (TruncOp.getValueType() == VT)
5196       return TruncOp; // x iff x size == zext size.
5197     if (TruncOp.getValueType().bitsGT(VT))
5198       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5199     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5200   }
5201
5202   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5203   // if the trunc is not free.
5204   if (N0.getOpcode() == ISD::AND &&
5205       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5206       N0.getOperand(1).getOpcode() == ISD::Constant &&
5207       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5208                           N0.getValueType())) {
5209     SDValue X = N0.getOperand(0).getOperand(0);
5210     if (X.getValueType().bitsLT(VT)) {
5211       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5212     } else if (X.getValueType().bitsGT(VT)) {
5213       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5214     }
5215     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5216     Mask = Mask.zext(VT.getSizeInBits());
5217     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5218                        X, DAG.getConstant(Mask, VT));
5219   }
5220
5221   // fold (aext (load x)) -> (aext (truncate (extload x)))
5222   // None of the supported targets knows how to perform load and any_ext
5223   // on vectors in one instruction.  We only perform this transformation on
5224   // scalars.
5225   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5226       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5227        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5228     bool DoXform = true;
5229     SmallVector<SDNode*, 4> SetCCs;
5230     if (!N0.hasOneUse())
5231       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5232     if (DoXform) {
5233       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5234       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5235                                        LN0->getChain(),
5236                                        LN0->getBasePtr(), N0.getValueType(),
5237                                        LN0->getMemOperand());
5238       CombineTo(N, ExtLoad);
5239       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5240                                   N0.getValueType(), ExtLoad);
5241       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5242       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5243                       ISD::ANY_EXTEND);
5244       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5245     }
5246   }
5247
5248   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5249   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5250   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5251   if (N0.getOpcode() == ISD::LOAD &&
5252       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5253       N0.hasOneUse()) {
5254     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5255     EVT MemVT = LN0->getMemoryVT();
5256     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5257                                      VT, LN0->getChain(), LN0->getBasePtr(),
5258                                      MemVT, LN0->getMemOperand());
5259     CombineTo(N, ExtLoad);
5260     CombineTo(N0.getNode(),
5261               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5262                           N0.getValueType(), ExtLoad),
5263               ExtLoad.getValue(1));
5264     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5265   }
5266
5267   if (N0.getOpcode() == ISD::SETCC) {
5268     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5269     // Only do this before legalize for now.
5270     if (VT.isVector() && !LegalOperations) {
5271       EVT N0VT = N0.getOperand(0).getValueType();
5272         // We know that the # elements of the results is the same as the
5273         // # elements of the compare (and the # elements of the compare result
5274         // for that matter).  Check to see that they are the same size.  If so,
5275         // we know that the element size of the sext'd result matches the
5276         // element size of the compare operands.
5277       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5278         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5279                              N0.getOperand(1),
5280                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5281       // If the desired elements are smaller or larger than the source
5282       // elements we can use a matching integer vector type and then
5283       // truncate/sign extend
5284       else {
5285         EVT MatchingElementType =
5286           EVT::getIntegerVT(*DAG.getContext(),
5287                             N0VT.getScalarType().getSizeInBits());
5288         EVT MatchingVectorType =
5289           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5290                            N0VT.getVectorNumElements());
5291         SDValue VsetCC =
5292           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5293                         N0.getOperand(1),
5294                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5295         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5296       }
5297     }
5298
5299     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5300     SDValue SCC =
5301       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5302                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5303                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5304     if (SCC.getNode())
5305       return SCC;
5306   }
5307
5308   return SDValue();
5309 }
5310
5311 /// GetDemandedBits - See if the specified operand can be simplified with the
5312 /// knowledge that only the bits specified by Mask are used.  If so, return the
5313 /// simpler operand, otherwise return a null SDValue.
5314 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5315   switch (V.getOpcode()) {
5316   default: break;
5317   case ISD::Constant: {
5318     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5319     assert(CV != 0 && "Const value should be ConstSDNode.");
5320     const APInt &CVal = CV->getAPIntValue();
5321     APInt NewVal = CVal & Mask;
5322     if (NewVal != CVal)
5323       return DAG.getConstant(NewVal, V.getValueType());
5324     break;
5325   }
5326   case ISD::OR:
5327   case ISD::XOR:
5328     // If the LHS or RHS don't contribute bits to the or, drop them.
5329     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5330       return V.getOperand(1);
5331     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5332       return V.getOperand(0);
5333     break;
5334   case ISD::SRL:
5335     // Only look at single-use SRLs.
5336     if (!V.getNode()->hasOneUse())
5337       break;
5338     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5339       // See if we can recursively simplify the LHS.
5340       unsigned Amt = RHSC->getZExtValue();
5341
5342       // Watch out for shift count overflow though.
5343       if (Amt >= Mask.getBitWidth()) break;
5344       APInt NewMask = Mask << Amt;
5345       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5346       if (SimplifyLHS.getNode())
5347         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5348                            SimplifyLHS, V.getOperand(1));
5349     }
5350   }
5351   return SDValue();
5352 }
5353
5354 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5355 /// bits and then truncated to a narrower type and where N is a multiple
5356 /// of number of bits of the narrower type, transform it to a narrower load
5357 /// from address + N / num of bits of new type. If the result is to be
5358 /// extended, also fold the extension to form a extending load.
5359 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5360   unsigned Opc = N->getOpcode();
5361
5362   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5363   SDValue N0 = N->getOperand(0);
5364   EVT VT = N->getValueType(0);
5365   EVT ExtVT = VT;
5366
5367   // This transformation isn't valid for vector loads.
5368   if (VT.isVector())
5369     return SDValue();
5370
5371   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5372   // extended to VT.
5373   if (Opc == ISD::SIGN_EXTEND_INREG) {
5374     ExtType = ISD::SEXTLOAD;
5375     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5376   } else if (Opc == ISD::SRL) {
5377     // Another special-case: SRL is basically zero-extending a narrower value.
5378     ExtType = ISD::ZEXTLOAD;
5379     N0 = SDValue(N, 0);
5380     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5381     if (!N01) return SDValue();
5382     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5383                               VT.getSizeInBits() - N01->getZExtValue());
5384   }
5385   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5386     return SDValue();
5387
5388   unsigned EVTBits = ExtVT.getSizeInBits();
5389
5390   // Do not generate loads of non-round integer types since these can
5391   // be expensive (and would be wrong if the type is not byte sized).
5392   if (!ExtVT.isRound())
5393     return SDValue();
5394
5395   unsigned ShAmt = 0;
5396   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5397     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5398       ShAmt = N01->getZExtValue();
5399       // Is the shift amount a multiple of size of VT?
5400       if ((ShAmt & (EVTBits-1)) == 0) {
5401         N0 = N0.getOperand(0);
5402         // Is the load width a multiple of size of VT?
5403         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5404           return SDValue();
5405       }
5406
5407       // At this point, we must have a load or else we can't do the transform.
5408       if (!isa<LoadSDNode>(N0)) return SDValue();
5409
5410       // Because a SRL must be assumed to *need* to zero-extend the high bits
5411       // (as opposed to anyext the high bits), we can't combine the zextload
5412       // lowering of SRL and an sextload.
5413       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5414         return SDValue();
5415
5416       // If the shift amount is larger than the input type then we're not
5417       // accessing any of the loaded bytes.  If the load was a zextload/extload
5418       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5419       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5420         return SDValue();
5421     }
5422   }
5423
5424   // If the load is shifted left (and the result isn't shifted back right),
5425   // we can fold the truncate through the shift.
5426   unsigned ShLeftAmt = 0;
5427   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5428       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5429     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5430       ShLeftAmt = N01->getZExtValue();
5431       N0 = N0.getOperand(0);
5432     }
5433   }
5434
5435   // If we haven't found a load, we can't narrow it.  Don't transform one with
5436   // multiple uses, this would require adding a new load.
5437   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5438     return SDValue();
5439
5440   // Don't change the width of a volatile load.
5441   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5442   if (LN0->isVolatile())
5443     return SDValue();
5444
5445   // Verify that we are actually reducing a load width here.
5446   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5447     return SDValue();
5448
5449   // For the transform to be legal, the load must produce only two values
5450   // (the value loaded and the chain).  Don't transform a pre-increment
5451   // load, for example, which produces an extra value.  Otherwise the
5452   // transformation is not equivalent, and the downstream logic to replace
5453   // uses gets things wrong.
5454   if (LN0->getNumValues() > 2)
5455     return SDValue();
5456
5457   // If the load that we're shrinking is an extload and we're not just
5458   // discarding the extension we can't simply shrink the load. Bail.
5459   // TODO: It would be possible to merge the extensions in some cases.
5460   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5461       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5462     return SDValue();
5463
5464   EVT PtrType = N0.getOperand(1).getValueType();
5465
5466   if (PtrType == MVT::Untyped || PtrType.isExtended())
5467     // It's not possible to generate a constant of extended or untyped type.
5468     return SDValue();
5469
5470   // For big endian targets, we need to adjust the offset to the pointer to
5471   // load the correct bytes.
5472   if (TLI.isBigEndian()) {
5473     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5474     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5475     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5476   }
5477
5478   uint64_t PtrOff = ShAmt / 8;
5479   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5480   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5481                                PtrType, LN0->getBasePtr(),
5482                                DAG.getConstant(PtrOff, PtrType));
5483   AddToWorkList(NewPtr.getNode());
5484
5485   SDValue Load;
5486   if (ExtType == ISD::NON_EXTLOAD)
5487     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5488                         LN0->getPointerInfo().getWithOffset(PtrOff),
5489                         LN0->isVolatile(), LN0->isNonTemporal(),
5490                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5491   else
5492     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5493                           LN0->getPointerInfo().getWithOffset(PtrOff),
5494                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5495                           NewAlign, LN0->getTBAAInfo());
5496
5497   // Replace the old load's chain with the new load's chain.
5498   WorkListRemover DeadNodes(*this);
5499   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5500
5501   // Shift the result left, if we've swallowed a left shift.
5502   SDValue Result = Load;
5503   if (ShLeftAmt != 0) {
5504     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5505     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5506       ShImmTy = VT;
5507     // If the shift amount is as large as the result size (but, presumably,
5508     // no larger than the source) then the useful bits of the result are
5509     // zero; we can't simply return the shortened shift, because the result
5510     // of that operation is undefined.
5511     if (ShLeftAmt >= VT.getSizeInBits())
5512       Result = DAG.getConstant(0, VT);
5513     else
5514       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5515                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5516   }
5517
5518   // Return the new loaded value.
5519   return Result;
5520 }
5521
5522 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5523   SDValue N0 = N->getOperand(0);
5524   SDValue N1 = N->getOperand(1);
5525   EVT VT = N->getValueType(0);
5526   EVT EVT = cast<VTSDNode>(N1)->getVT();
5527   unsigned VTBits = VT.getScalarType().getSizeInBits();
5528   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5529
5530   // fold (sext_in_reg c1) -> c1
5531   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5532     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5533
5534   // If the input is already sign extended, just drop the extension.
5535   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5536     return N0;
5537
5538   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5539   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5540       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5541     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5542                        N0.getOperand(0), N1);
5543
5544   // fold (sext_in_reg (sext x)) -> (sext x)
5545   // fold (sext_in_reg (aext x)) -> (sext x)
5546   // if x is small enough.
5547   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5548     SDValue N00 = N0.getOperand(0);
5549     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5550         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5551       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5552   }
5553
5554   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5555   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5556     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5557
5558   // fold operands of sext_in_reg based on knowledge that the top bits are not
5559   // demanded.
5560   if (SimplifyDemandedBits(SDValue(N, 0)))
5561     return SDValue(N, 0);
5562
5563   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5564   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5565   SDValue NarrowLoad = ReduceLoadWidth(N);
5566   if (NarrowLoad.getNode())
5567     return NarrowLoad;
5568
5569   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5570   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5571   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5572   if (N0.getOpcode() == ISD::SRL) {
5573     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5574       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5575         // We can turn this into an SRA iff the input to the SRL is already sign
5576         // extended enough.
5577         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5578         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5579           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5580                              N0.getOperand(0), N0.getOperand(1));
5581       }
5582   }
5583
5584   // fold (sext_inreg (extload x)) -> (sextload x)
5585   if (ISD::isEXTLoad(N0.getNode()) &&
5586       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5587       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5588       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5589        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5590     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5591     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5592                                      LN0->getChain(),
5593                                      LN0->getBasePtr(), EVT,
5594                                      LN0->getMemOperand());
5595     CombineTo(N, ExtLoad);
5596     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5597     AddToWorkList(ExtLoad.getNode());
5598     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5599   }
5600   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5601   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5602       N0.hasOneUse() &&
5603       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5604       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5605        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5606     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5607     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5608                                      LN0->getChain(),
5609                                      LN0->getBasePtr(), EVT,
5610                                      LN0->getMemOperand());
5611     CombineTo(N, ExtLoad);
5612     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5613     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5614   }
5615
5616   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5617   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5618     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5619                                        N0.getOperand(1), false);
5620     if (BSwap.getNode() != 0)
5621       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5622                          BSwap, N1);
5623   }
5624
5625   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5626   // into a build_vector.
5627   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5628     SmallVector<SDValue, 8> Elts;
5629     unsigned NumElts = N0->getNumOperands();
5630     unsigned ShAmt = VTBits - EVTBits;
5631
5632     for (unsigned i = 0; i != NumElts; ++i) {
5633       SDValue Op = N0->getOperand(i);
5634       if (Op->getOpcode() == ISD::UNDEF) {
5635         Elts.push_back(Op);
5636         continue;
5637       }
5638
5639       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5640       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5641       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5642                                      Op.getValueType()));
5643     }
5644
5645     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5646   }
5647
5648   return SDValue();
5649 }
5650
5651 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5652   SDValue N0 = N->getOperand(0);
5653   EVT VT = N->getValueType(0);
5654   bool isLE = TLI.isLittleEndian();
5655
5656   // noop truncate
5657   if (N0.getValueType() == N->getValueType(0))
5658     return N0;
5659   // fold (truncate c1) -> c1
5660   if (isa<ConstantSDNode>(N0))
5661     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5662   // fold (truncate (truncate x)) -> (truncate x)
5663   if (N0.getOpcode() == ISD::TRUNCATE)
5664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5665   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5666   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5667       N0.getOpcode() == ISD::SIGN_EXTEND ||
5668       N0.getOpcode() == ISD::ANY_EXTEND) {
5669     if (N0.getOperand(0).getValueType().bitsLT(VT))
5670       // if the source is smaller than the dest, we still need an extend
5671       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5672                          N0.getOperand(0));
5673     if (N0.getOperand(0).getValueType().bitsGT(VT))
5674       // if the source is larger than the dest, than we just need the truncate
5675       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5676     // if the source and dest are the same type, we can drop both the extend
5677     // and the truncate.
5678     return N0.getOperand(0);
5679   }
5680
5681   // Fold extract-and-trunc into a narrow extract. For example:
5682   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5683   //   i32 y = TRUNCATE(i64 x)
5684   //        -- becomes --
5685   //   v16i8 b = BITCAST (v2i64 val)
5686   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5687   //
5688   // Note: We only run this optimization after type legalization (which often
5689   // creates this pattern) and before operation legalization after which
5690   // we need to be more careful about the vector instructions that we generate.
5691   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5692       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5693
5694     EVT VecTy = N0.getOperand(0).getValueType();
5695     EVT ExTy = N0.getValueType();
5696     EVT TrTy = N->getValueType(0);
5697
5698     unsigned NumElem = VecTy.getVectorNumElements();
5699     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5700
5701     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5702     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5703
5704     SDValue EltNo = N0->getOperand(1);
5705     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5706       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5707       EVT IndexTy = TLI.getVectorIdxTy();
5708       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5709
5710       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5711                               NVT, N0.getOperand(0));
5712
5713       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5714                          SDLoc(N), TrTy, V,
5715                          DAG.getConstant(Index, IndexTy));
5716     }
5717   }
5718
5719   // Fold a series of buildvector, bitcast, and truncate if possible.
5720   // For example fold
5721   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5722   //   (2xi32 (buildvector x, y)).
5723   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5724       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5725       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5726       N0.getOperand(0).hasOneUse()) {
5727
5728     SDValue BuildVect = N0.getOperand(0);
5729     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5730     EVT TruncVecEltTy = VT.getVectorElementType();
5731
5732     // Check that the element types match.
5733     if (BuildVectEltTy == TruncVecEltTy) {
5734       // Now we only need to compute the offset of the truncated elements.
5735       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5736       unsigned TruncVecNumElts = VT.getVectorNumElements();
5737       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5738
5739       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5740              "Invalid number of elements");
5741
5742       SmallVector<SDValue, 8> Opnds;
5743       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5744         Opnds.push_back(BuildVect.getOperand(i));
5745
5746       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5747                          Opnds.size());
5748     }
5749   }
5750
5751   // See if we can simplify the input to this truncate through knowledge that
5752   // only the low bits are being used.
5753   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5754   // Currently we only perform this optimization on scalars because vectors
5755   // may have different active low bits.
5756   if (!VT.isVector()) {
5757     SDValue Shorter =
5758       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5759                                                VT.getSizeInBits()));
5760     if (Shorter.getNode())
5761       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5762   }
5763   // fold (truncate (load x)) -> (smaller load x)
5764   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5765   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5766     SDValue Reduced = ReduceLoadWidth(N);
5767     if (Reduced.getNode())
5768       return Reduced;
5769     // Handle the case where the load remains an extending load even
5770     // after truncation.
5771     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5772       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5773       if (!LN0->isVolatile() &&
5774           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5775         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5776                                          VT, LN0->getChain(), LN0->getBasePtr(),
5777                                          LN0->getMemoryVT(),
5778                                          LN0->getMemOperand());
5779         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5780         return NewLoad;
5781       }
5782     }
5783   }
5784   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5785   // where ... are all 'undef'.
5786   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5787     SmallVector<EVT, 8> VTs;
5788     SDValue V;
5789     unsigned Idx = 0;
5790     unsigned NumDefs = 0;
5791
5792     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5793       SDValue X = N0.getOperand(i);
5794       if (X.getOpcode() != ISD::UNDEF) {
5795         V = X;
5796         Idx = i;
5797         NumDefs++;
5798       }
5799       // Stop if more than one members are non-undef.
5800       if (NumDefs > 1)
5801         break;
5802       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5803                                      VT.getVectorElementType(),
5804                                      X.getValueType().getVectorNumElements()));
5805     }
5806
5807     if (NumDefs == 0)
5808       return DAG.getUNDEF(VT);
5809
5810     if (NumDefs == 1) {
5811       assert(V.getNode() && "The single defined operand is empty!");
5812       SmallVector<SDValue, 8> Opnds;
5813       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5814         if (i != Idx) {
5815           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5816           continue;
5817         }
5818         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5819         AddToWorkList(NV.getNode());
5820         Opnds.push_back(NV);
5821       }
5822       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5823                          &Opnds[0], Opnds.size());
5824     }
5825   }
5826
5827   // Simplify the operands using demanded-bits information.
5828   if (!VT.isVector() &&
5829       SimplifyDemandedBits(SDValue(N, 0)))
5830     return SDValue(N, 0);
5831
5832   return SDValue();
5833 }
5834
5835 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5836   SDValue Elt = N->getOperand(i);
5837   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5838     return Elt.getNode();
5839   return Elt.getOperand(Elt.getResNo()).getNode();
5840 }
5841
5842 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5843 /// if load locations are consecutive.
5844 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5845   assert(N->getOpcode() == ISD::BUILD_PAIR);
5846
5847   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5848   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5849   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5850       LD1->getPointerInfo().getAddrSpace() !=
5851          LD2->getPointerInfo().getAddrSpace())
5852     return SDValue();
5853   EVT LD1VT = LD1->getValueType(0);
5854
5855   if (ISD::isNON_EXTLoad(LD2) &&
5856       LD2->hasOneUse() &&
5857       // If both are volatile this would reduce the number of volatile loads.
5858       // If one is volatile it might be ok, but play conservative and bail out.
5859       !LD1->isVolatile() &&
5860       !LD2->isVolatile() &&
5861       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5862     unsigned Align = LD1->getAlignment();
5863     unsigned NewAlign = TLI.getDataLayout()->
5864       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5865
5866     if (NewAlign <= Align &&
5867         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5868       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5869                          LD1->getBasePtr(), LD1->getPointerInfo(),
5870                          false, false, false, Align);
5871   }
5872
5873   return SDValue();
5874 }
5875
5876 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5877   SDValue N0 = N->getOperand(0);
5878   EVT VT = N->getValueType(0);
5879
5880   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5881   // Only do this before legalize, since afterward the target may be depending
5882   // on the bitconvert.
5883   // First check to see if this is all constant.
5884   if (!LegalTypes &&
5885       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5886       VT.isVector()) {
5887     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5888
5889     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5890     assert(!DestEltVT.isVector() &&
5891            "Element type of vector ValueType must not be vector!");
5892     if (isSimple)
5893       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5894   }
5895
5896   // If the input is a constant, let getNode fold it.
5897   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5898     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5899     if (Res.getNode() != N) {
5900       if (!LegalOperations ||
5901           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5902         return Res;
5903
5904       // Folding it resulted in an illegal node, and it's too late to
5905       // do that. Clean up the old node and forego the transformation.
5906       // Ideally this won't happen very often, because instcombine
5907       // and the earlier dagcombine runs (where illegal nodes are
5908       // permitted) should have folded most of them already.
5909       DAG.DeleteNode(Res.getNode());
5910     }
5911   }
5912
5913   // (conv (conv x, t1), t2) -> (conv x, t2)
5914   if (N0.getOpcode() == ISD::BITCAST)
5915     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5916                        N0.getOperand(0));
5917
5918   // fold (conv (load x)) -> (load (conv*)x)
5919   // If the resultant load doesn't need a higher alignment than the original!
5920   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5921       // Do not change the width of a volatile load.
5922       !cast<LoadSDNode>(N0)->isVolatile() &&
5923       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5924       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5925     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5926     unsigned Align = TLI.getDataLayout()->
5927       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5928     unsigned OrigAlign = LN0->getAlignment();
5929
5930     if (Align <= OrigAlign) {
5931       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5932                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5933                                  LN0->isVolatile(), LN0->isNonTemporal(),
5934                                  LN0->isInvariant(), OrigAlign,
5935                                  LN0->getTBAAInfo());
5936       AddToWorkList(N);
5937       CombineTo(N0.getNode(),
5938                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5939                             N0.getValueType(), Load),
5940                 Load.getValue(1));
5941       return Load;
5942     }
5943   }
5944
5945   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5946   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5947   // This often reduces constant pool loads.
5948   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5949        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5950       N0.getNode()->hasOneUse() && VT.isInteger() &&
5951       !VT.isVector() && !N0.getValueType().isVector()) {
5952     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5953                                   N0.getOperand(0));
5954     AddToWorkList(NewConv.getNode());
5955
5956     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5957     if (N0.getOpcode() == ISD::FNEG)
5958       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5959                          NewConv, DAG.getConstant(SignBit, VT));
5960     assert(N0.getOpcode() == ISD::FABS);
5961     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5962                        NewConv, DAG.getConstant(~SignBit, VT));
5963   }
5964
5965   // fold (bitconvert (fcopysign cst, x)) ->
5966   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5967   // Note that we don't handle (copysign x, cst) because this can always be
5968   // folded to an fneg or fabs.
5969   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5970       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5971       VT.isInteger() && !VT.isVector()) {
5972     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5973     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5974     if (isTypeLegal(IntXVT)) {
5975       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5976                               IntXVT, N0.getOperand(1));
5977       AddToWorkList(X.getNode());
5978
5979       // If X has a different width than the result/lhs, sext it or truncate it.
5980       unsigned VTWidth = VT.getSizeInBits();
5981       if (OrigXWidth < VTWidth) {
5982         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5983         AddToWorkList(X.getNode());
5984       } else if (OrigXWidth > VTWidth) {
5985         // To get the sign bit in the right place, we have to shift it right
5986         // before truncating.
5987         X = DAG.getNode(ISD::SRL, SDLoc(X),
5988                         X.getValueType(), X,
5989                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5990         AddToWorkList(X.getNode());
5991         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5992         AddToWorkList(X.getNode());
5993       }
5994
5995       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5996       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5997                       X, DAG.getConstant(SignBit, VT));
5998       AddToWorkList(X.getNode());
5999
6000       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6001                                 VT, N0.getOperand(0));
6002       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6003                         Cst, DAG.getConstant(~SignBit, VT));
6004       AddToWorkList(Cst.getNode());
6005
6006       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6007     }
6008   }
6009
6010   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6011   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6012     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6013     if (CombineLD.getNode())
6014       return CombineLD;
6015   }
6016
6017   return SDValue();
6018 }
6019
6020 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6021   EVT VT = N->getValueType(0);
6022   return CombineConsecutiveLoads(N, VT);
6023 }
6024
6025 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6026 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6027 /// destination element value type.
6028 SDValue DAGCombiner::
6029 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6030   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6031
6032   // If this is already the right type, we're done.
6033   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6034
6035   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6036   unsigned DstBitSize = DstEltVT.getSizeInBits();
6037
6038   // If this is a conversion of N elements of one type to N elements of another
6039   // type, convert each element.  This handles FP<->INT cases.
6040   if (SrcBitSize == DstBitSize) {
6041     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6042                               BV->getValueType(0).getVectorNumElements());
6043
6044     // Due to the FP element handling below calling this routine recursively,
6045     // we can end up with a scalar-to-vector node here.
6046     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6047       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6048                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6049                                      DstEltVT, BV->getOperand(0)));
6050
6051     SmallVector<SDValue, 8> Ops;
6052     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6053       SDValue Op = BV->getOperand(i);
6054       // If the vector element type is not legal, the BUILD_VECTOR operands
6055       // are promoted and implicitly truncated.  Make that explicit here.
6056       if (Op.getValueType() != SrcEltVT)
6057         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6058       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6059                                 DstEltVT, Op));
6060       AddToWorkList(Ops.back().getNode());
6061     }
6062     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6063                        &Ops[0], Ops.size());
6064   }
6065
6066   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6067   // handle annoying details of growing/shrinking FP values, we convert them to
6068   // int first.
6069   if (SrcEltVT.isFloatingPoint()) {
6070     // Convert the input float vector to a int vector where the elements are the
6071     // same sizes.
6072     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6073     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6074     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6075     SrcEltVT = IntVT;
6076   }
6077
6078   // Now we know the input is an integer vector.  If the output is a FP type,
6079   // convert to integer first, then to FP of the right size.
6080   if (DstEltVT.isFloatingPoint()) {
6081     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6082     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6083     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6084
6085     // Next, convert to FP elements of the same size.
6086     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6087   }
6088
6089   // Okay, we know the src/dst types are both integers of differing types.
6090   // Handling growing first.
6091   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6092   if (SrcBitSize < DstBitSize) {
6093     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6094
6095     SmallVector<SDValue, 8> Ops;
6096     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6097          i += NumInputsPerOutput) {
6098       bool isLE = TLI.isLittleEndian();
6099       APInt NewBits = APInt(DstBitSize, 0);
6100       bool EltIsUndef = true;
6101       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6102         // Shift the previously computed bits over.
6103         NewBits <<= SrcBitSize;
6104         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6105         if (Op.getOpcode() == ISD::UNDEF) continue;
6106         EltIsUndef = false;
6107
6108         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6109                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6110       }
6111
6112       if (EltIsUndef)
6113         Ops.push_back(DAG.getUNDEF(DstEltVT));
6114       else
6115         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6116     }
6117
6118     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6119     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6120                        &Ops[0], Ops.size());
6121   }
6122
6123   // Finally, this must be the case where we are shrinking elements: each input
6124   // turns into multiple outputs.
6125   bool isS2V = ISD::isScalarToVector(BV);
6126   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6127   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6128                             NumOutputsPerInput*BV->getNumOperands());
6129   SmallVector<SDValue, 8> Ops;
6130
6131   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6132     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6133       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6134         Ops.push_back(DAG.getUNDEF(DstEltVT));
6135       continue;
6136     }
6137
6138     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6139                   getAPIntValue().zextOrTrunc(SrcBitSize);
6140
6141     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6142       APInt ThisVal = OpVal.trunc(DstBitSize);
6143       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6144       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6145         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6146         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6147                            Ops[0]);
6148       OpVal = OpVal.lshr(DstBitSize);
6149     }
6150
6151     // For big endian targets, swap the order of the pieces of each element.
6152     if (TLI.isBigEndian())
6153       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6154   }
6155
6156   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6157                      &Ops[0], Ops.size());
6158 }
6159
6160 SDValue DAGCombiner::visitFADD(SDNode *N) {
6161   SDValue N0 = N->getOperand(0);
6162   SDValue N1 = N->getOperand(1);
6163   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6164   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6165   EVT VT = N->getValueType(0);
6166
6167   // fold vector ops
6168   if (VT.isVector()) {
6169     SDValue FoldedVOp = SimplifyVBinOp(N);
6170     if (FoldedVOp.getNode()) return FoldedVOp;
6171   }
6172
6173   // fold (fadd c1, c2) -> c1 + c2
6174   if (N0CFP && N1CFP)
6175     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6176   // canonicalize constant to RHS
6177   if (N0CFP && !N1CFP)
6178     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6179   // fold (fadd A, 0) -> A
6180   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6181       N1CFP->getValueAPF().isZero())
6182     return N0;
6183   // fold (fadd A, (fneg B)) -> (fsub A, B)
6184   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6185     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6186     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6187                        GetNegatedExpression(N1, DAG, LegalOperations));
6188   // fold (fadd (fneg A), B) -> (fsub B, A)
6189   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6190     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6191     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6192                        GetNegatedExpression(N0, DAG, LegalOperations));
6193
6194   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6195   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6196       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6197       isa<ConstantFPSDNode>(N0.getOperand(1)))
6198     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6199                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6200                                    N0.getOperand(1), N1));
6201
6202   // No FP constant should be created after legalization as Instruction
6203   // Selection pass has hard time in dealing with FP constant.
6204   //
6205   // We don't need test this condition for transformation like following, as
6206   // the DAG being transformed implies it is legal to take FP constant as
6207   // operand.
6208   //
6209   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6210   //
6211   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6212
6213   // If allow, fold (fadd (fneg x), x) -> 0.0
6214   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6215       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6216     return DAG.getConstantFP(0.0, VT);
6217
6218     // If allow, fold (fadd x, (fneg x)) -> 0.0
6219   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6220       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6221     return DAG.getConstantFP(0.0, VT);
6222
6223   // In unsafe math mode, we can fold chains of FADD's of the same value
6224   // into multiplications.  This transform is not safe in general because
6225   // we are reducing the number of rounding steps.
6226   if (DAG.getTarget().Options.UnsafeFPMath &&
6227       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6228       !N0CFP && !N1CFP) {
6229     if (N0.getOpcode() == ISD::FMUL) {
6230       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6231       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6232
6233       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6234       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6235         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6236                                      SDValue(CFP00, 0),
6237                                      DAG.getConstantFP(1.0, VT));
6238         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6239                            N1, NewCFP);
6240       }
6241
6242       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6243       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6244         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6245                                      SDValue(CFP01, 0),
6246                                      DAG.getConstantFP(1.0, VT));
6247         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6248                            N1, NewCFP);
6249       }
6250
6251       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6252       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6253           N1.getOperand(0) == N1.getOperand(1) &&
6254           N0.getOperand(1) == N1.getOperand(0)) {
6255         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6256                                      SDValue(CFP00, 0),
6257                                      DAG.getConstantFP(2.0, VT));
6258         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6259                            N0.getOperand(1), NewCFP);
6260       }
6261
6262       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6263       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6264           N1.getOperand(0) == N1.getOperand(1) &&
6265           N0.getOperand(0) == N1.getOperand(0)) {
6266         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6267                                      SDValue(CFP01, 0),
6268                                      DAG.getConstantFP(2.0, VT));
6269         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6270                            N0.getOperand(0), NewCFP);
6271       }
6272     }
6273
6274     if (N1.getOpcode() == ISD::FMUL) {
6275       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6276       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6277
6278       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6279       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6280         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6281                                      SDValue(CFP10, 0),
6282                                      DAG.getConstantFP(1.0, VT));
6283         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6284                            N0, NewCFP);
6285       }
6286
6287       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6288       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6289         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6290                                      SDValue(CFP11, 0),
6291                                      DAG.getConstantFP(1.0, VT));
6292         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6293                            N0, NewCFP);
6294       }
6295
6296
6297       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6298       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6299           N0.getOperand(0) == N0.getOperand(1) &&
6300           N1.getOperand(1) == N0.getOperand(0)) {
6301         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6302                                      SDValue(CFP10, 0),
6303                                      DAG.getConstantFP(2.0, VT));
6304         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6305                            N1.getOperand(1), NewCFP);
6306       }
6307
6308       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6309       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6310           N0.getOperand(0) == N0.getOperand(1) &&
6311           N1.getOperand(0) == N0.getOperand(0)) {
6312         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6313                                      SDValue(CFP11, 0),
6314                                      DAG.getConstantFP(2.0, VT));
6315         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6316                            N1.getOperand(0), NewCFP);
6317       }
6318     }
6319
6320     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6321       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6322       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6323       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6324           (N0.getOperand(0) == N1))
6325         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6326                            N1, DAG.getConstantFP(3.0, VT));
6327     }
6328
6329     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6330       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6331       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6332       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6333           N1.getOperand(0) == N0)
6334         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6335                            N0, DAG.getConstantFP(3.0, VT));
6336     }
6337
6338     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6339     if (AllowNewFpConst &&
6340         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6341         N0.getOperand(0) == N0.getOperand(1) &&
6342         N1.getOperand(0) == N1.getOperand(1) &&
6343         N0.getOperand(0) == N1.getOperand(0))
6344       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6345                          N0.getOperand(0),
6346                          DAG.getConstantFP(4.0, VT));
6347   }
6348
6349   // FADD -> FMA combines:
6350   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6351        DAG.getTarget().Options.UnsafeFPMath) &&
6352       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6353       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6354
6355     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6356     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6357       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6358                          N0.getOperand(0), N0.getOperand(1), N1);
6359
6360     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6361     // Note: Commutes FADD operands.
6362     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6363       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6364                          N1.getOperand(0), N1.getOperand(1), N0);
6365   }
6366
6367   return SDValue();
6368 }
6369
6370 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6371   SDValue N0 = N->getOperand(0);
6372   SDValue N1 = N->getOperand(1);
6373   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6374   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6375   EVT VT = N->getValueType(0);
6376   SDLoc dl(N);
6377
6378   // fold vector ops
6379   if (VT.isVector()) {
6380     SDValue FoldedVOp = SimplifyVBinOp(N);
6381     if (FoldedVOp.getNode()) return FoldedVOp;
6382   }
6383
6384   // fold (fsub c1, c2) -> c1-c2
6385   if (N0CFP && N1CFP)
6386     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6387   // fold (fsub A, 0) -> A
6388   if (DAG.getTarget().Options.UnsafeFPMath &&
6389       N1CFP && N1CFP->getValueAPF().isZero())
6390     return N0;
6391   // fold (fsub 0, B) -> -B
6392   if (DAG.getTarget().Options.UnsafeFPMath &&
6393       N0CFP && N0CFP->getValueAPF().isZero()) {
6394     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6395       return GetNegatedExpression(N1, DAG, LegalOperations);
6396     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6397       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6398   }
6399   // fold (fsub A, (fneg B)) -> (fadd A, B)
6400   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6401     return DAG.getNode(ISD::FADD, dl, VT, N0,
6402                        GetNegatedExpression(N1, DAG, LegalOperations));
6403
6404   // If 'unsafe math' is enabled, fold
6405   //    (fsub x, x) -> 0.0 &
6406   //    (fsub x, (fadd x, y)) -> (fneg y) &
6407   //    (fsub x, (fadd y, x)) -> (fneg y)
6408   if (DAG.getTarget().Options.UnsafeFPMath) {
6409     if (N0 == N1)
6410       return DAG.getConstantFP(0.0f, VT);
6411
6412     if (N1.getOpcode() == ISD::FADD) {
6413       SDValue N10 = N1->getOperand(0);
6414       SDValue N11 = N1->getOperand(1);
6415
6416       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6417                                           &DAG.getTarget().Options))
6418         return GetNegatedExpression(N11, DAG, LegalOperations);
6419
6420       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6421                                           &DAG.getTarget().Options))
6422         return GetNegatedExpression(N10, DAG, LegalOperations);
6423     }
6424   }
6425
6426   // FSUB -> FMA combines:
6427   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6428        DAG.getTarget().Options.UnsafeFPMath) &&
6429       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6430       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6431
6432     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6433     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6434       return DAG.getNode(ISD::FMA, dl, VT,
6435                          N0.getOperand(0), N0.getOperand(1),
6436                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6437
6438     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6439     // Note: Commutes FSUB operands.
6440     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6441       return DAG.getNode(ISD::FMA, dl, VT,
6442                          DAG.getNode(ISD::FNEG, dl, VT,
6443                          N1.getOperand(0)),
6444                          N1.getOperand(1), N0);
6445
6446     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6447     if (N0.getOpcode() == ISD::FNEG &&
6448         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6449         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6450       SDValue N00 = N0.getOperand(0).getOperand(0);
6451       SDValue N01 = N0.getOperand(0).getOperand(1);
6452       return DAG.getNode(ISD::FMA, dl, VT,
6453                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6454                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6455     }
6456   }
6457
6458   return SDValue();
6459 }
6460
6461 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6462   SDValue N0 = N->getOperand(0);
6463   SDValue N1 = N->getOperand(1);
6464   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6465   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6466   EVT VT = N->getValueType(0);
6467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6468
6469   // fold vector ops
6470   if (VT.isVector()) {
6471     SDValue FoldedVOp = SimplifyVBinOp(N);
6472     if (FoldedVOp.getNode()) return FoldedVOp;
6473   }
6474
6475   // fold (fmul c1, c2) -> c1*c2
6476   if (N0CFP && N1CFP)
6477     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6478   // canonicalize constant to RHS
6479   if (N0CFP && !N1CFP)
6480     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6481   // fold (fmul A, 0) -> 0
6482   if (DAG.getTarget().Options.UnsafeFPMath &&
6483       N1CFP && N1CFP->getValueAPF().isZero())
6484     return N1;
6485   // fold (fmul A, 0) -> 0, vector edition.
6486   if (DAG.getTarget().Options.UnsafeFPMath &&
6487       ISD::isBuildVectorAllZeros(N1.getNode()))
6488     return N1;
6489   // fold (fmul A, 1.0) -> A
6490   if (N1CFP && N1CFP->isExactlyValue(1.0))
6491     return N0;
6492   // fold (fmul X, 2.0) -> (fadd X, X)
6493   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6494     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6495   // fold (fmul X, -1.0) -> (fneg X)
6496   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6497     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6498       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6499
6500   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6501   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6502                                        &DAG.getTarget().Options)) {
6503     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6504                                          &DAG.getTarget().Options)) {
6505       // Both can be negated for free, check to see if at least one is cheaper
6506       // negated.
6507       if (LHSNeg == 2 || RHSNeg == 2)
6508         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6509                            GetNegatedExpression(N0, DAG, LegalOperations),
6510                            GetNegatedExpression(N1, DAG, LegalOperations));
6511     }
6512   }
6513
6514   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6515   if (DAG.getTarget().Options.UnsafeFPMath &&
6516       N1CFP && N0.getOpcode() == ISD::FMUL &&
6517       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6518     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6519                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6520                                    N0.getOperand(1), N1));
6521
6522   return SDValue();
6523 }
6524
6525 SDValue DAGCombiner::visitFMA(SDNode *N) {
6526   SDValue N0 = N->getOperand(0);
6527   SDValue N1 = N->getOperand(1);
6528   SDValue N2 = N->getOperand(2);
6529   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6530   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6531   EVT VT = N->getValueType(0);
6532   SDLoc dl(N);
6533
6534   if (DAG.getTarget().Options.UnsafeFPMath) {
6535     if (N0CFP && N0CFP->isZero())
6536       return N2;
6537     if (N1CFP && N1CFP->isZero())
6538       return N2;
6539   }
6540   if (N0CFP && N0CFP->isExactlyValue(1.0))
6541     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6542   if (N1CFP && N1CFP->isExactlyValue(1.0))
6543     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6544
6545   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6546   if (N0CFP && !N1CFP)
6547     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6548
6549   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6550   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6551       N2.getOpcode() == ISD::FMUL &&
6552       N0 == N2.getOperand(0) &&
6553       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6554     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6555                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6556   }
6557
6558
6559   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6560   if (DAG.getTarget().Options.UnsafeFPMath &&
6561       N0.getOpcode() == ISD::FMUL && N1CFP &&
6562       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6563     return DAG.getNode(ISD::FMA, dl, VT,
6564                        N0.getOperand(0),
6565                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6566                        N2);
6567   }
6568
6569   // (fma x, 1, y) -> (fadd x, y)
6570   // (fma x, -1, y) -> (fadd (fneg x), y)
6571   if (N1CFP) {
6572     if (N1CFP->isExactlyValue(1.0))
6573       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6574
6575     if (N1CFP->isExactlyValue(-1.0) &&
6576         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6577       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6578       AddToWorkList(RHSNeg.getNode());
6579       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6580     }
6581   }
6582
6583   // (fma x, c, x) -> (fmul x, (c+1))
6584   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6585     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6586                        DAG.getNode(ISD::FADD, dl, VT,
6587                                    N1, DAG.getConstantFP(1.0, VT)));
6588
6589   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6590   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6591       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6592     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6593                        DAG.getNode(ISD::FADD, dl, VT,
6594                                    N1, DAG.getConstantFP(-1.0, VT)));
6595
6596
6597   return SDValue();
6598 }
6599
6600 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6601   SDValue N0 = N->getOperand(0);
6602   SDValue N1 = N->getOperand(1);
6603   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6604   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6605   EVT VT = N->getValueType(0);
6606   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6607
6608   // fold vector ops
6609   if (VT.isVector()) {
6610     SDValue FoldedVOp = SimplifyVBinOp(N);
6611     if (FoldedVOp.getNode()) return FoldedVOp;
6612   }
6613
6614   // fold (fdiv c1, c2) -> c1/c2
6615   if (N0CFP && N1CFP)
6616     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6617
6618   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6619   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6620     // Compute the reciprocal 1.0 / c2.
6621     APFloat N1APF = N1CFP->getValueAPF();
6622     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6623     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6624     // Only do the transform if the reciprocal is a legal fp immediate that
6625     // isn't too nasty (eg NaN, denormal, ...).
6626     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6627         (!LegalOperations ||
6628          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6629          // backend)... we should handle this gracefully after Legalize.
6630          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6631          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6632          TLI.isFPImmLegal(Recip, VT)))
6633       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6634                          DAG.getConstantFP(Recip, VT));
6635   }
6636
6637   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6638   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6639                                        &DAG.getTarget().Options)) {
6640     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6641                                          &DAG.getTarget().Options)) {
6642       // Both can be negated for free, check to see if at least one is cheaper
6643       // negated.
6644       if (LHSNeg == 2 || RHSNeg == 2)
6645         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6646                            GetNegatedExpression(N0, DAG, LegalOperations),
6647                            GetNegatedExpression(N1, DAG, LegalOperations));
6648     }
6649   }
6650
6651   return SDValue();
6652 }
6653
6654 SDValue DAGCombiner::visitFREM(SDNode *N) {
6655   SDValue N0 = N->getOperand(0);
6656   SDValue N1 = N->getOperand(1);
6657   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6658   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6659   EVT VT = N->getValueType(0);
6660
6661   // fold (frem c1, c2) -> fmod(c1,c2)
6662   if (N0CFP && N1CFP)
6663     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6664
6665   return SDValue();
6666 }
6667
6668 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6669   SDValue N0 = N->getOperand(0);
6670   SDValue N1 = N->getOperand(1);
6671   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6672   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6673   EVT VT = N->getValueType(0);
6674
6675   if (N0CFP && N1CFP)  // Constant fold
6676     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6677
6678   if (N1CFP) {
6679     const APFloat& V = N1CFP->getValueAPF();
6680     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6681     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6682     if (!V.isNegative()) {
6683       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6684         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6685     } else {
6686       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6687         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6688                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6689     }
6690   }
6691
6692   // copysign(fabs(x), y) -> copysign(x, y)
6693   // copysign(fneg(x), y) -> copysign(x, y)
6694   // copysign(copysign(x,z), y) -> copysign(x, y)
6695   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6696       N0.getOpcode() == ISD::FCOPYSIGN)
6697     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6698                        N0.getOperand(0), N1);
6699
6700   // copysign(x, abs(y)) -> abs(x)
6701   if (N1.getOpcode() == ISD::FABS)
6702     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6703
6704   // copysign(x, copysign(y,z)) -> copysign(x, z)
6705   if (N1.getOpcode() == ISD::FCOPYSIGN)
6706     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6707                        N0, N1.getOperand(1));
6708
6709   // copysign(x, fp_extend(y)) -> copysign(x, y)
6710   // copysign(x, fp_round(y)) -> copysign(x, y)
6711   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6712     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6713                        N0, N1.getOperand(0));
6714
6715   return SDValue();
6716 }
6717
6718 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6719   SDValue N0 = N->getOperand(0);
6720   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6721   EVT VT = N->getValueType(0);
6722   EVT OpVT = N0.getValueType();
6723
6724   // fold (sint_to_fp c1) -> c1fp
6725   if (N0C &&
6726       // ...but only if the target supports immediate floating-point values
6727       (!LegalOperations ||
6728        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6729     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6730
6731   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6732   // but UINT_TO_FP is legal on this target, try to convert.
6733   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6734       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6735     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6736     if (DAG.SignBitIsZero(N0))
6737       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6738   }
6739
6740   // The next optimizations are desireable only if SELECT_CC can be lowered.
6741   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6742   // having to say they don't support SELECT_CC on every type the DAG knows
6743   // about, since there is no way to mark an opcode illegal at all value types
6744   // (See also visitSELECT)
6745   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6746     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6747     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6748         !VT.isVector() &&
6749         (!LegalOperations ||
6750          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6751       SDValue Ops[] =
6752         { N0.getOperand(0), N0.getOperand(1),
6753           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6754           N0.getOperand(2) };
6755       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6756     }
6757
6758     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6759     //      (select_cc x, y, 1.0, 0.0,, cc)
6760     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6761         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6762         (!LegalOperations ||
6763          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6764       SDValue Ops[] =
6765         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6766           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6767           N0.getOperand(0).getOperand(2) };
6768       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6769     }
6770   }
6771
6772   return SDValue();
6773 }
6774
6775 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6776   SDValue N0 = N->getOperand(0);
6777   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6778   EVT VT = N->getValueType(0);
6779   EVT OpVT = N0.getValueType();
6780
6781   // fold (uint_to_fp c1) -> c1fp
6782   if (N0C &&
6783       // ...but only if the target supports immediate floating-point values
6784       (!LegalOperations ||
6785        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6786     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6787
6788   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6789   // but SINT_TO_FP is legal on this target, try to convert.
6790   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6791       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6792     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6793     if (DAG.SignBitIsZero(N0))
6794       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6795   }
6796
6797   // The next optimizations are desireable only if SELECT_CC can be lowered.
6798   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6799   // having to say they don't support SELECT_CC on every type the DAG knows
6800   // about, since there is no way to mark an opcode illegal at all value types
6801   // (See also visitSELECT)
6802   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6803     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6804
6805     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6806         (!LegalOperations ||
6807          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6808       SDValue Ops[] =
6809         { N0.getOperand(0), N0.getOperand(1),
6810           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6811           N0.getOperand(2) };
6812       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6813     }
6814   }
6815
6816   return SDValue();
6817 }
6818
6819 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6820   SDValue N0 = N->getOperand(0);
6821   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6822   EVT VT = N->getValueType(0);
6823
6824   // fold (fp_to_sint c1fp) -> c1
6825   if (N0CFP)
6826     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6827
6828   return SDValue();
6829 }
6830
6831 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6832   SDValue N0 = N->getOperand(0);
6833   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6834   EVT VT = N->getValueType(0);
6835
6836   // fold (fp_to_uint c1fp) -> c1
6837   if (N0CFP)
6838     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6839
6840   return SDValue();
6841 }
6842
6843 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6844   SDValue N0 = N->getOperand(0);
6845   SDValue N1 = N->getOperand(1);
6846   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6847   EVT VT = N->getValueType(0);
6848
6849   // fold (fp_round c1fp) -> c1fp
6850   if (N0CFP)
6851     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6852
6853   // fold (fp_round (fp_extend x)) -> x
6854   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6855     return N0.getOperand(0);
6856
6857   // fold (fp_round (fp_round x)) -> (fp_round x)
6858   if (N0.getOpcode() == ISD::FP_ROUND) {
6859     // This is a value preserving truncation if both round's are.
6860     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6861                    N0.getNode()->getConstantOperandVal(1) == 1;
6862     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6863                        DAG.getIntPtrConstant(IsTrunc));
6864   }
6865
6866   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6867   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6868     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6869                               N0.getOperand(0), N1);
6870     AddToWorkList(Tmp.getNode());
6871     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6872                        Tmp, N0.getOperand(1));
6873   }
6874
6875   return SDValue();
6876 }
6877
6878 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6879   SDValue N0 = N->getOperand(0);
6880   EVT VT = N->getValueType(0);
6881   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6882   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6883
6884   // fold (fp_round_inreg c1fp) -> c1fp
6885   if (N0CFP && isTypeLegal(EVT)) {
6886     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6887     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6888   }
6889
6890   return SDValue();
6891 }
6892
6893 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6894   SDValue N0 = N->getOperand(0);
6895   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6896   EVT VT = N->getValueType(0);
6897
6898   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6899   if (N->hasOneUse() &&
6900       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6901     return SDValue();
6902
6903   // fold (fp_extend c1fp) -> c1fp
6904   if (N0CFP)
6905     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6906
6907   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6908   // value of X.
6909   if (N0.getOpcode() == ISD::FP_ROUND
6910       && N0.getNode()->getConstantOperandVal(1) == 1) {
6911     SDValue In = N0.getOperand(0);
6912     if (In.getValueType() == VT) return In;
6913     if (VT.bitsLT(In.getValueType()))
6914       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6915                          In, N0.getOperand(1));
6916     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6917   }
6918
6919   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6920   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6921       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6922        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6923     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6924     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6925                                      LN0->getChain(),
6926                                      LN0->getBasePtr(), N0.getValueType(),
6927                                      LN0->getMemOperand());
6928     CombineTo(N, ExtLoad);
6929     CombineTo(N0.getNode(),
6930               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6931                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6932               ExtLoad.getValue(1));
6933     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6934   }
6935
6936   return SDValue();
6937 }
6938
6939 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6940   SDValue N0 = N->getOperand(0);
6941   EVT VT = N->getValueType(0);
6942
6943   if (VT.isVector()) {
6944     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6945     if (FoldedVOp.getNode()) return FoldedVOp;
6946   }
6947
6948   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6949                          &DAG.getTarget().Options))
6950     return GetNegatedExpression(N0, DAG, LegalOperations);
6951
6952   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6953   // constant pool values.
6954   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6955       !VT.isVector() &&
6956       N0.getNode()->hasOneUse() &&
6957       N0.getOperand(0).getValueType().isInteger()) {
6958     SDValue Int = N0.getOperand(0);
6959     EVT IntVT = Int.getValueType();
6960     if (IntVT.isInteger() && !IntVT.isVector()) {
6961       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6962               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6963       AddToWorkList(Int.getNode());
6964       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6965                          VT, Int);
6966     }
6967   }
6968
6969   // (fneg (fmul c, x)) -> (fmul -c, x)
6970   if (N0.getOpcode() == ISD::FMUL) {
6971     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6972     if (CFP1)
6973       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6974                          N0.getOperand(0),
6975                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6976                                      N0.getOperand(1)));
6977   }
6978
6979   return SDValue();
6980 }
6981
6982 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6983   SDValue N0 = N->getOperand(0);
6984   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6985   EVT VT = N->getValueType(0);
6986
6987   // fold (fceil c1) -> fceil(c1)
6988   if (N0CFP)
6989     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6990
6991   return SDValue();
6992 }
6993
6994 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6995   SDValue N0 = N->getOperand(0);
6996   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6997   EVT VT = N->getValueType(0);
6998
6999   // fold (ftrunc c1) -> ftrunc(c1)
7000   if (N0CFP)
7001     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7002
7003   return SDValue();
7004 }
7005
7006 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7007   SDValue N0 = N->getOperand(0);
7008   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7009   EVT VT = N->getValueType(0);
7010
7011   // fold (ffloor c1) -> ffloor(c1)
7012   if (N0CFP)
7013     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7014
7015   return SDValue();
7016 }
7017
7018 SDValue DAGCombiner::visitFABS(SDNode *N) {
7019   SDValue N0 = N->getOperand(0);
7020   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7021   EVT VT = N->getValueType(0);
7022
7023   if (VT.isVector()) {
7024     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7025     if (FoldedVOp.getNode()) return FoldedVOp;
7026   }
7027
7028   // fold (fabs c1) -> fabs(c1)
7029   if (N0CFP)
7030     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7031   // fold (fabs (fabs x)) -> (fabs x)
7032   if (N0.getOpcode() == ISD::FABS)
7033     return N->getOperand(0);
7034   // fold (fabs (fneg x)) -> (fabs x)
7035   // fold (fabs (fcopysign x, y)) -> (fabs x)
7036   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7037     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7038
7039   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7040   // constant pool values.
7041   if (!TLI.isFAbsFree(VT) &&
7042       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7043       N0.getOperand(0).getValueType().isInteger() &&
7044       !N0.getOperand(0).getValueType().isVector()) {
7045     SDValue Int = N0.getOperand(0);
7046     EVT IntVT = Int.getValueType();
7047     if (IntVT.isInteger() && !IntVT.isVector()) {
7048       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7049              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7050       AddToWorkList(Int.getNode());
7051       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7052                          N->getValueType(0), Int);
7053     }
7054   }
7055
7056   return SDValue();
7057 }
7058
7059 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7060   SDValue Chain = N->getOperand(0);
7061   SDValue N1 = N->getOperand(1);
7062   SDValue N2 = N->getOperand(2);
7063
7064   // If N is a constant we could fold this into a fallthrough or unconditional
7065   // branch. However that doesn't happen very often in normal code, because
7066   // Instcombine/SimplifyCFG should have handled the available opportunities.
7067   // If we did this folding here, it would be necessary to update the
7068   // MachineBasicBlock CFG, which is awkward.
7069
7070   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7071   // on the target.
7072   if (N1.getOpcode() == ISD::SETCC &&
7073       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7074                                    N1.getOperand(0).getValueType())) {
7075     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7076                        Chain, N1.getOperand(2),
7077                        N1.getOperand(0), N1.getOperand(1), N2);
7078   }
7079
7080   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7081       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7082        (N1.getOperand(0).hasOneUse() &&
7083         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7084     SDNode *Trunc = 0;
7085     if (N1.getOpcode() == ISD::TRUNCATE) {
7086       // Look pass the truncate.
7087       Trunc = N1.getNode();
7088       N1 = N1.getOperand(0);
7089     }
7090
7091     // Match this pattern so that we can generate simpler code:
7092     //
7093     //   %a = ...
7094     //   %b = and i32 %a, 2
7095     //   %c = srl i32 %b, 1
7096     //   brcond i32 %c ...
7097     //
7098     // into
7099     //
7100     //   %a = ...
7101     //   %b = and i32 %a, 2
7102     //   %c = setcc eq %b, 0
7103     //   brcond %c ...
7104     //
7105     // This applies only when the AND constant value has one bit set and the
7106     // SRL constant is equal to the log2 of the AND constant. The back-end is
7107     // smart enough to convert the result into a TEST/JMP sequence.
7108     SDValue Op0 = N1.getOperand(0);
7109     SDValue Op1 = N1.getOperand(1);
7110
7111     if (Op0.getOpcode() == ISD::AND &&
7112         Op1.getOpcode() == ISD::Constant) {
7113       SDValue AndOp1 = Op0.getOperand(1);
7114
7115       if (AndOp1.getOpcode() == ISD::Constant) {
7116         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7117
7118         if (AndConst.isPowerOf2() &&
7119             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7120           SDValue SetCC =
7121             DAG.getSetCC(SDLoc(N),
7122                          getSetCCResultType(Op0.getValueType()),
7123                          Op0, DAG.getConstant(0, Op0.getValueType()),
7124                          ISD::SETNE);
7125
7126           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7127                                           MVT::Other, Chain, SetCC, N2);
7128           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7129           // will convert it back to (X & C1) >> C2.
7130           CombineTo(N, NewBRCond, false);
7131           // Truncate is dead.
7132           if (Trunc) {
7133             removeFromWorkList(Trunc);
7134             DAG.DeleteNode(Trunc);
7135           }
7136           // Replace the uses of SRL with SETCC
7137           WorkListRemover DeadNodes(*this);
7138           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7139           removeFromWorkList(N1.getNode());
7140           DAG.DeleteNode(N1.getNode());
7141           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7142         }
7143       }
7144     }
7145
7146     if (Trunc)
7147       // Restore N1 if the above transformation doesn't match.
7148       N1 = N->getOperand(1);
7149   }
7150
7151   // Transform br(xor(x, y)) -> br(x != y)
7152   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7153   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7154     SDNode *TheXor = N1.getNode();
7155     SDValue Op0 = TheXor->getOperand(0);
7156     SDValue Op1 = TheXor->getOperand(1);
7157     if (Op0.getOpcode() == Op1.getOpcode()) {
7158       // Avoid missing important xor optimizations.
7159       SDValue Tmp = visitXOR(TheXor);
7160       if (Tmp.getNode()) {
7161         if (Tmp.getNode() != TheXor) {
7162           DEBUG(dbgs() << "\nReplacing.8 ";
7163                 TheXor->dump(&DAG);
7164                 dbgs() << "\nWith: ";
7165                 Tmp.getNode()->dump(&DAG);
7166                 dbgs() << '\n');
7167           WorkListRemover DeadNodes(*this);
7168           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7169           removeFromWorkList(TheXor);
7170           DAG.DeleteNode(TheXor);
7171           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7172                              MVT::Other, Chain, Tmp, N2);
7173         }
7174
7175         // visitXOR has changed XOR's operands or replaced the XOR completely,
7176         // bail out.
7177         return SDValue(N, 0);
7178       }
7179     }
7180
7181     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7182       bool Equal = false;
7183       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7184         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7185             Op0.getOpcode() == ISD::XOR) {
7186           TheXor = Op0.getNode();
7187           Equal = true;
7188         }
7189
7190       EVT SetCCVT = N1.getValueType();
7191       if (LegalTypes)
7192         SetCCVT = getSetCCResultType(SetCCVT);
7193       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7194                                    SetCCVT,
7195                                    Op0, Op1,
7196                                    Equal ? ISD::SETEQ : ISD::SETNE);
7197       // Replace the uses of XOR with SETCC
7198       WorkListRemover DeadNodes(*this);
7199       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7200       removeFromWorkList(N1.getNode());
7201       DAG.DeleteNode(N1.getNode());
7202       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7203                          MVT::Other, Chain, SetCC, N2);
7204     }
7205   }
7206
7207   return SDValue();
7208 }
7209
7210 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7211 //
7212 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7213   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7214   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7215
7216   // If N is a constant we could fold this into a fallthrough or unconditional
7217   // branch. However that doesn't happen very often in normal code, because
7218   // Instcombine/SimplifyCFG should have handled the available opportunities.
7219   // If we did this folding here, it would be necessary to update the
7220   // MachineBasicBlock CFG, which is awkward.
7221
7222   // Use SimplifySetCC to simplify SETCC's.
7223   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7224                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7225                                false);
7226   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7227
7228   // fold to a simpler setcc
7229   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7230     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7231                        N->getOperand(0), Simp.getOperand(2),
7232                        Simp.getOperand(0), Simp.getOperand(1),
7233                        N->getOperand(4));
7234
7235   return SDValue();
7236 }
7237
7238 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7239 /// uses N as its base pointer and that N may be folded in the load / store
7240 /// addressing mode.
7241 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7242                                     SelectionDAG &DAG,
7243                                     const TargetLowering &TLI) {
7244   EVT VT;
7245   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7246     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7247       return false;
7248     VT = Use->getValueType(0);
7249   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7250     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7251       return false;
7252     VT = ST->getValue().getValueType();
7253   } else
7254     return false;
7255
7256   TargetLowering::AddrMode AM;
7257   if (N->getOpcode() == ISD::ADD) {
7258     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7259     if (Offset)
7260       // [reg +/- imm]
7261       AM.BaseOffs = Offset->getSExtValue();
7262     else
7263       // [reg +/- reg]
7264       AM.Scale = 1;
7265   } else if (N->getOpcode() == ISD::SUB) {
7266     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7267     if (Offset)
7268       // [reg +/- imm]
7269       AM.BaseOffs = -Offset->getSExtValue();
7270     else
7271       // [reg +/- reg]
7272       AM.Scale = 1;
7273   } else
7274     return false;
7275
7276   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7277 }
7278
7279 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7280 /// pre-indexed load / store when the base pointer is an add or subtract
7281 /// and it has other uses besides the load / store. After the
7282 /// transformation, the new indexed load / store has effectively folded
7283 /// the add / subtract in and all of its other uses are redirected to the
7284 /// new load / store.
7285 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7286   if (Level < AfterLegalizeDAG)
7287     return false;
7288
7289   bool isLoad = true;
7290   SDValue Ptr;
7291   EVT VT;
7292   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7293     if (LD->isIndexed())
7294       return false;
7295     VT = LD->getMemoryVT();
7296     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7297         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7298       return false;
7299     Ptr = LD->getBasePtr();
7300   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7301     if (ST->isIndexed())
7302       return false;
7303     VT = ST->getMemoryVT();
7304     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7305         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7306       return false;
7307     Ptr = ST->getBasePtr();
7308     isLoad = false;
7309   } else {
7310     return false;
7311   }
7312
7313   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7314   // out.  There is no reason to make this a preinc/predec.
7315   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7316       Ptr.getNode()->hasOneUse())
7317     return false;
7318
7319   // Ask the target to do addressing mode selection.
7320   SDValue BasePtr;
7321   SDValue Offset;
7322   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7323   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7324     return false;
7325
7326   // Backends without true r+i pre-indexed forms may need to pass a
7327   // constant base with a variable offset so that constant coercion
7328   // will work with the patterns in canonical form.
7329   bool Swapped = false;
7330   if (isa<ConstantSDNode>(BasePtr)) {
7331     std::swap(BasePtr, Offset);
7332     Swapped = true;
7333   }
7334
7335   // Don't create a indexed load / store with zero offset.
7336   if (isa<ConstantSDNode>(Offset) &&
7337       cast<ConstantSDNode>(Offset)->isNullValue())
7338     return false;
7339
7340   // Try turning it into a pre-indexed load / store except when:
7341   // 1) The new base ptr is a frame index.
7342   // 2) If N is a store and the new base ptr is either the same as or is a
7343   //    predecessor of the value being stored.
7344   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7345   //    that would create a cycle.
7346   // 4) All uses are load / store ops that use it as old base ptr.
7347
7348   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7349   // (plus the implicit offset) to a register to preinc anyway.
7350   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7351     return false;
7352
7353   // Check #2.
7354   if (!isLoad) {
7355     SDValue Val = cast<StoreSDNode>(N)->getValue();
7356     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7357       return false;
7358   }
7359
7360   // If the offset is a constant, there may be other adds of constants that
7361   // can be folded with this one. We should do this to avoid having to keep
7362   // a copy of the original base pointer.
7363   SmallVector<SDNode *, 16> OtherUses;
7364   if (isa<ConstantSDNode>(Offset))
7365     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7366          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7367       SDNode *Use = *I;
7368       if (Use == Ptr.getNode())
7369         continue;
7370
7371       if (Use->isPredecessorOf(N))
7372         continue;
7373
7374       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7375         OtherUses.clear();
7376         break;
7377       }
7378
7379       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7380       if (Op1.getNode() == BasePtr.getNode())
7381         std::swap(Op0, Op1);
7382       assert(Op0.getNode() == BasePtr.getNode() &&
7383              "Use of ADD/SUB but not an operand");
7384
7385       if (!isa<ConstantSDNode>(Op1)) {
7386         OtherUses.clear();
7387         break;
7388       }
7389
7390       // FIXME: In some cases, we can be smarter about this.
7391       if (Op1.getValueType() != Offset.getValueType()) {
7392         OtherUses.clear();
7393         break;
7394       }
7395
7396       OtherUses.push_back(Use);
7397     }
7398
7399   if (Swapped)
7400     std::swap(BasePtr, Offset);
7401
7402   // Now check for #3 and #4.
7403   bool RealUse = false;
7404
7405   // Caches for hasPredecessorHelper
7406   SmallPtrSet<const SDNode *, 32> Visited;
7407   SmallVector<const SDNode *, 16> Worklist;
7408
7409   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7410          E = Ptr.getNode()->use_end(); I != E; ++I) {
7411     SDNode *Use = *I;
7412     if (Use == N)
7413       continue;
7414     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7415       return false;
7416
7417     // If Ptr may be folded in addressing mode of other use, then it's
7418     // not profitable to do this transformation.
7419     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7420       RealUse = true;
7421   }
7422
7423   if (!RealUse)
7424     return false;
7425
7426   SDValue Result;
7427   if (isLoad)
7428     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7429                                 BasePtr, Offset, AM);
7430   else
7431     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7432                                  BasePtr, Offset, AM);
7433   ++PreIndexedNodes;
7434   ++NodesCombined;
7435   DEBUG(dbgs() << "\nReplacing.4 ";
7436         N->dump(&DAG);
7437         dbgs() << "\nWith: ";
7438         Result.getNode()->dump(&DAG);
7439         dbgs() << '\n');
7440   WorkListRemover DeadNodes(*this);
7441   if (isLoad) {
7442     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7443     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7444   } else {
7445     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7446   }
7447
7448   // Finally, since the node is now dead, remove it from the graph.
7449   DAG.DeleteNode(N);
7450
7451   if (Swapped)
7452     std::swap(BasePtr, Offset);
7453
7454   // Replace other uses of BasePtr that can be updated to use Ptr
7455   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7456     unsigned OffsetIdx = 1;
7457     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7458       OffsetIdx = 0;
7459     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7460            BasePtr.getNode() && "Expected BasePtr operand");
7461
7462     // We need to replace ptr0 in the following expression:
7463     //   x0 * offset0 + y0 * ptr0 = t0
7464     // knowing that
7465     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7466     //
7467     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7468     // indexed load/store and the expresion that needs to be re-written.
7469     //
7470     // Therefore, we have:
7471     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7472
7473     ConstantSDNode *CN =
7474       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7475     int X0, X1, Y0, Y1;
7476     APInt Offset0 = CN->getAPIntValue();
7477     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7478
7479     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7480     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7481     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7482     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7483
7484     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7485
7486     APInt CNV = Offset0;
7487     if (X0 < 0) CNV = -CNV;
7488     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7489     else CNV = CNV - Offset1;
7490
7491     // We can now generate the new expression.
7492     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7493     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7494
7495     SDValue NewUse = DAG.getNode(Opcode,
7496                                  SDLoc(OtherUses[i]),
7497                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7498     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7499     removeFromWorkList(OtherUses[i]);
7500     DAG.DeleteNode(OtherUses[i]);
7501   }
7502
7503   // Replace the uses of Ptr with uses of the updated base value.
7504   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7505   removeFromWorkList(Ptr.getNode());
7506   DAG.DeleteNode(Ptr.getNode());
7507
7508   return true;
7509 }
7510
7511 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7512 /// add / sub of the base pointer node into a post-indexed load / store.
7513 /// The transformation folded the add / subtract into the new indexed
7514 /// load / store effectively and all of its uses are redirected to the
7515 /// new load / store.
7516 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7517   if (Level < AfterLegalizeDAG)
7518     return false;
7519
7520   bool isLoad = true;
7521   SDValue Ptr;
7522   EVT VT;
7523   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7524     if (LD->isIndexed())
7525       return false;
7526     VT = LD->getMemoryVT();
7527     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7528         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7529       return false;
7530     Ptr = LD->getBasePtr();
7531   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7532     if (ST->isIndexed())
7533       return false;
7534     VT = ST->getMemoryVT();
7535     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7536         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7537       return false;
7538     Ptr = ST->getBasePtr();
7539     isLoad = false;
7540   } else {
7541     return false;
7542   }
7543
7544   if (Ptr.getNode()->hasOneUse())
7545     return false;
7546
7547   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7548          E = Ptr.getNode()->use_end(); I != E; ++I) {
7549     SDNode *Op = *I;
7550     if (Op == N ||
7551         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7552       continue;
7553
7554     SDValue BasePtr;
7555     SDValue Offset;
7556     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7557     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7558       // Don't create a indexed load / store with zero offset.
7559       if (isa<ConstantSDNode>(Offset) &&
7560           cast<ConstantSDNode>(Offset)->isNullValue())
7561         continue;
7562
7563       // Try turning it into a post-indexed load / store except when
7564       // 1) All uses are load / store ops that use it as base ptr (and
7565       //    it may be folded as addressing mmode).
7566       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7567       //    nor a successor of N. Otherwise, if Op is folded that would
7568       //    create a cycle.
7569
7570       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7571         continue;
7572
7573       // Check for #1.
7574       bool TryNext = false;
7575       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7576              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7577         SDNode *Use = *II;
7578         if (Use == Ptr.getNode())
7579           continue;
7580
7581         // If all the uses are load / store addresses, then don't do the
7582         // transformation.
7583         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7584           bool RealUse = false;
7585           for (SDNode::use_iterator III = Use->use_begin(),
7586                  EEE = Use->use_end(); III != EEE; ++III) {
7587             SDNode *UseUse = *III;
7588             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7589               RealUse = true;
7590           }
7591
7592           if (!RealUse) {
7593             TryNext = true;
7594             break;
7595           }
7596         }
7597       }
7598
7599       if (TryNext)
7600         continue;
7601
7602       // Check for #2
7603       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7604         SDValue Result = isLoad
7605           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7606                                BasePtr, Offset, AM)
7607           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7608                                 BasePtr, Offset, AM);
7609         ++PostIndexedNodes;
7610         ++NodesCombined;
7611         DEBUG(dbgs() << "\nReplacing.5 ";
7612               N->dump(&DAG);
7613               dbgs() << "\nWith: ";
7614               Result.getNode()->dump(&DAG);
7615               dbgs() << '\n');
7616         WorkListRemover DeadNodes(*this);
7617         if (isLoad) {
7618           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7619           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7620         } else {
7621           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7622         }
7623
7624         // Finally, since the node is now dead, remove it from the graph.
7625         DAG.DeleteNode(N);
7626
7627         // Replace the uses of Use with uses of the updated base value.
7628         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7629                                       Result.getValue(isLoad ? 1 : 0));
7630         removeFromWorkList(Op);
7631         DAG.DeleteNode(Op);
7632         return true;
7633       }
7634     }
7635   }
7636
7637   return false;
7638 }
7639
7640 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7641   LoadSDNode *LD  = cast<LoadSDNode>(N);
7642   SDValue Chain = LD->getChain();
7643   SDValue Ptr   = LD->getBasePtr();
7644
7645   // If load is not volatile and there are no uses of the loaded value (and
7646   // the updated indexed value in case of indexed loads), change uses of the
7647   // chain value into uses of the chain input (i.e. delete the dead load).
7648   if (!LD->isVolatile()) {
7649     if (N->getValueType(1) == MVT::Other) {
7650       // Unindexed loads.
7651       if (!N->hasAnyUseOfValue(0)) {
7652         // It's not safe to use the two value CombineTo variant here. e.g.
7653         // v1, chain2 = load chain1, loc
7654         // v2, chain3 = load chain2, loc
7655         // v3         = add v2, c
7656         // Now we replace use of chain2 with chain1.  This makes the second load
7657         // isomorphic to the one we are deleting, and thus makes this load live.
7658         DEBUG(dbgs() << "\nReplacing.6 ";
7659               N->dump(&DAG);
7660               dbgs() << "\nWith chain: ";
7661               Chain.getNode()->dump(&DAG);
7662               dbgs() << "\n");
7663         WorkListRemover DeadNodes(*this);
7664         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7665
7666         if (N->use_empty()) {
7667           removeFromWorkList(N);
7668           DAG.DeleteNode(N);
7669         }
7670
7671         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7672       }
7673     } else {
7674       // Indexed loads.
7675       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7676       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7677         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7678         DEBUG(dbgs() << "\nReplacing.7 ";
7679               N->dump(&DAG);
7680               dbgs() << "\nWith: ";
7681               Undef.getNode()->dump(&DAG);
7682               dbgs() << " and 2 other values\n");
7683         WorkListRemover DeadNodes(*this);
7684         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7685         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7686                                       DAG.getUNDEF(N->getValueType(1)));
7687         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7688         removeFromWorkList(N);
7689         DAG.DeleteNode(N);
7690         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7691       }
7692     }
7693   }
7694
7695   // If this load is directly stored, replace the load value with the stored
7696   // value.
7697   // TODO: Handle store large -> read small portion.
7698   // TODO: Handle TRUNCSTORE/LOADEXT
7699   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7700     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7701       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7702       if (PrevST->getBasePtr() == Ptr &&
7703           PrevST->getValue().getValueType() == N->getValueType(0))
7704       return CombineTo(N, Chain.getOperand(1), Chain);
7705     }
7706   }
7707
7708   // Try to infer better alignment information than the load already has.
7709   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7710     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7711       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7712         SDValue NewLoad =
7713                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7714                               LD->getValueType(0),
7715                               Chain, Ptr, LD->getPointerInfo(),
7716                               LD->getMemoryVT(),
7717                               LD->isVolatile(), LD->isNonTemporal(), Align,
7718                               LD->getTBAAInfo());
7719         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7720       }
7721     }
7722   }
7723
7724   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7725     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7726   if (UseAA) {
7727     // Walk up chain skipping non-aliasing memory nodes.
7728     SDValue BetterChain = FindBetterChain(N, Chain);
7729
7730     // If there is a better chain.
7731     if (Chain != BetterChain) {
7732       SDValue ReplLoad;
7733
7734       // Replace the chain to void dependency.
7735       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7736         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7737                                BetterChain, Ptr, LD->getMemOperand());
7738       } else {
7739         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7740                                   LD->getValueType(0),
7741                                   BetterChain, Ptr, LD->getMemoryVT(),
7742                                   LD->getMemOperand());
7743       }
7744
7745       // Create token factor to keep old chain connected.
7746       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7747                                   MVT::Other, Chain, ReplLoad.getValue(1));
7748
7749       // Make sure the new and old chains are cleaned up.
7750       AddToWorkList(Token.getNode());
7751
7752       // Replace uses with load result and token factor. Don't add users
7753       // to work list.
7754       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7755     }
7756   }
7757
7758   // Try transforming N to an indexed load.
7759   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7760     return SDValue(N, 0);
7761
7762   // Try to slice up N to more direct loads if the slices are mapped to
7763   // different register banks or pairing can take place.
7764   if (SliceUpLoad(N))
7765     return SDValue(N, 0);
7766
7767   return SDValue();
7768 }
7769
7770 namespace {
7771 /// \brief Helper structure used to slice a load in smaller loads.
7772 /// Basically a slice is obtained from the following sequence:
7773 /// Origin = load Ty1, Base
7774 /// Shift = srl Ty1 Origin, CstTy Amount
7775 /// Inst = trunc Shift to Ty2
7776 ///
7777 /// Then, it will be rewriten into:
7778 /// Slice = load SliceTy, Base + SliceOffset
7779 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7780 ///
7781 /// SliceTy is deduced from the number of bits that are actually used to
7782 /// build Inst.
7783 struct LoadedSlice {
7784   /// \brief Helper structure used to compute the cost of a slice.
7785   struct Cost {
7786     /// Are we optimizing for code size.
7787     bool ForCodeSize;
7788     /// Various cost.
7789     unsigned Loads;
7790     unsigned Truncates;
7791     unsigned CrossRegisterBanksCopies;
7792     unsigned ZExts;
7793     unsigned Shift;
7794
7795     Cost(bool ForCodeSize = false)
7796         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7797           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7798
7799     /// \brief Get the cost of one isolated slice.
7800     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7801         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7802           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7803       EVT TruncType = LS.Inst->getValueType(0);
7804       EVT LoadedType = LS.getLoadedType();
7805       if (TruncType != LoadedType &&
7806           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7807         ZExts = 1;
7808     }
7809
7810     /// \brief Account for slicing gain in the current cost.
7811     /// Slicing provide a few gains like removing a shift or a
7812     /// truncate. This method allows to grow the cost of the original
7813     /// load with the gain from this slice.
7814     void addSliceGain(const LoadedSlice &LS) {
7815       // Each slice saves a truncate.
7816       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7817       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7818                               LS.Inst->getOperand(0).getValueType()))
7819         ++Truncates;
7820       // If there is a shift amount, this slice gets rid of it.
7821       if (LS.Shift)
7822         ++Shift;
7823       // If this slice can merge a cross register bank copy, account for it.
7824       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7825         ++CrossRegisterBanksCopies;
7826     }
7827
7828     Cost &operator+=(const Cost &RHS) {
7829       Loads += RHS.Loads;
7830       Truncates += RHS.Truncates;
7831       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7832       ZExts += RHS.ZExts;
7833       Shift += RHS.Shift;
7834       return *this;
7835     }
7836
7837     bool operator==(const Cost &RHS) const {
7838       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7839              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7840              ZExts == RHS.ZExts && Shift == RHS.Shift;
7841     }
7842
7843     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7844
7845     bool operator<(const Cost &RHS) const {
7846       // Assume cross register banks copies are as expensive as loads.
7847       // FIXME: Do we want some more target hooks?
7848       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7849       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7850       // Unless we are optimizing for code size, consider the
7851       // expensive operation first.
7852       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7853         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7854       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7855              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7856     }
7857
7858     bool operator>(const Cost &RHS) const { return RHS < *this; }
7859
7860     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7861
7862     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7863   };
7864   // The last instruction that represent the slice. This should be a
7865   // truncate instruction.
7866   SDNode *Inst;
7867   // The original load instruction.
7868   LoadSDNode *Origin;
7869   // The right shift amount in bits from the original load.
7870   unsigned Shift;
7871   // The DAG from which Origin came from.
7872   // This is used to get some contextual information about legal types, etc.
7873   SelectionDAG *DAG;
7874
7875   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7876               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7877       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7878
7879   LoadedSlice(const LoadedSlice &LS)
7880       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7881
7882   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7883   /// \return Result is \p BitWidth and has used bits set to 1 and
7884   ///         not used bits set to 0.
7885   APInt getUsedBits() const {
7886     // Reproduce the trunc(lshr) sequence:
7887     // - Start from the truncated value.
7888     // - Zero extend to the desired bit width.
7889     // - Shift left.
7890     assert(Origin && "No original load to compare against.");
7891     unsigned BitWidth = Origin->getValueSizeInBits(0);
7892     assert(Inst && "This slice is not bound to an instruction");
7893     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7894            "Extracted slice is bigger than the whole type!");
7895     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7896     UsedBits.setAllBits();
7897     UsedBits = UsedBits.zext(BitWidth);
7898     UsedBits <<= Shift;
7899     return UsedBits;
7900   }
7901
7902   /// \brief Get the size of the slice to be loaded in bytes.
7903   unsigned getLoadedSize() const {
7904     unsigned SliceSize = getUsedBits().countPopulation();
7905     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7906     return SliceSize / 8;
7907   }
7908
7909   /// \brief Get the type that will be loaded for this slice.
7910   /// Note: This may not be the final type for the slice.
7911   EVT getLoadedType() const {
7912     assert(DAG && "Missing context");
7913     LLVMContext &Ctxt = *DAG->getContext();
7914     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7915   }
7916
7917   /// \brief Get the alignment of the load used for this slice.
7918   unsigned getAlignment() const {
7919     unsigned Alignment = Origin->getAlignment();
7920     unsigned Offset = getOffsetFromBase();
7921     if (Offset != 0)
7922       Alignment = MinAlign(Alignment, Alignment + Offset);
7923     return Alignment;
7924   }
7925
7926   /// \brief Check if this slice can be rewritten with legal operations.
7927   bool isLegal() const {
7928     // An invalid slice is not legal.
7929     if (!Origin || !Inst || !DAG)
7930       return false;
7931
7932     // Offsets are for indexed load only, we do not handle that.
7933     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7934       return false;
7935
7936     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7937
7938     // Check that the type is legal.
7939     EVT SliceType = getLoadedType();
7940     if (!TLI.isTypeLegal(SliceType))
7941       return false;
7942
7943     // Check that the load is legal for this type.
7944     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7945       return false;
7946
7947     // Check that the offset can be computed.
7948     // 1. Check its type.
7949     EVT PtrType = Origin->getBasePtr().getValueType();
7950     if (PtrType == MVT::Untyped || PtrType.isExtended())
7951       return false;
7952
7953     // 2. Check that it fits in the immediate.
7954     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7955       return false;
7956
7957     // 3. Check that the computation is legal.
7958     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7959       return false;
7960
7961     // Check that the zext is legal if it needs one.
7962     EVT TruncateType = Inst->getValueType(0);
7963     if (TruncateType != SliceType &&
7964         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7965       return false;
7966
7967     return true;
7968   }
7969
7970   /// \brief Get the offset in bytes of this slice in the original chunk of
7971   /// bits.
7972   /// \pre DAG != NULL.
7973   uint64_t getOffsetFromBase() const {
7974     assert(DAG && "Missing context.");
7975     bool IsBigEndian =
7976         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7977     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7978     uint64_t Offset = Shift / 8;
7979     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7980     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7981            "The size of the original loaded type is not a multiple of a"
7982            " byte.");
7983     // If Offset is bigger than TySizeInBytes, it means we are loading all
7984     // zeros. This should have been optimized before in the process.
7985     assert(TySizeInBytes > Offset &&
7986            "Invalid shift amount for given loaded size");
7987     if (IsBigEndian)
7988       Offset = TySizeInBytes - Offset - getLoadedSize();
7989     return Offset;
7990   }
7991
7992   /// \brief Generate the sequence of instructions to load the slice
7993   /// represented by this object and redirect the uses of this slice to
7994   /// this new sequence of instructions.
7995   /// \pre this->Inst && this->Origin are valid Instructions and this
7996   /// object passed the legal check: LoadedSlice::isLegal returned true.
7997   /// \return The last instruction of the sequence used to load the slice.
7998   SDValue loadSlice() const {
7999     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8000     const SDValue &OldBaseAddr = Origin->getBasePtr();
8001     SDValue BaseAddr = OldBaseAddr;
8002     // Get the offset in that chunk of bytes w.r.t. the endianess.
8003     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8004     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8005     if (Offset) {
8006       // BaseAddr = BaseAddr + Offset.
8007       EVT ArithType = BaseAddr.getValueType();
8008       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8009                               DAG->getConstant(Offset, ArithType));
8010     }
8011
8012     // Create the type of the loaded slice according to its size.
8013     EVT SliceType = getLoadedType();
8014
8015     // Create the load for the slice.
8016     SDValue LastInst = DAG->getLoad(
8017         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8018         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8019         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8020     // If the final type is not the same as the loaded type, this means that
8021     // we have to pad with zero. Create a zero extend for that.
8022     EVT FinalType = Inst->getValueType(0);
8023     if (SliceType != FinalType)
8024       LastInst =
8025           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8026     return LastInst;
8027   }
8028
8029   /// \brief Check if this slice can be merged with an expensive cross register
8030   /// bank copy. E.g.,
8031   /// i = load i32
8032   /// f = bitcast i32 i to float
8033   bool canMergeExpensiveCrossRegisterBankCopy() const {
8034     if (!Inst || !Inst->hasOneUse())
8035       return false;
8036     SDNode *Use = *Inst->use_begin();
8037     if (Use->getOpcode() != ISD::BITCAST)
8038       return false;
8039     assert(DAG && "Missing context");
8040     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8041     EVT ResVT = Use->getValueType(0);
8042     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8043     const TargetRegisterClass *ArgRC =
8044         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8045     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8046       return false;
8047
8048     // At this point, we know that we perform a cross-register-bank copy.
8049     // Check if it is expensive.
8050     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8051     // Assume bitcasts are cheap, unless both register classes do not
8052     // explicitly share a common sub class.
8053     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8054       return false;
8055
8056     // Check if it will be merged with the load.
8057     // 1. Check the alignment constraint.
8058     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8059         ResVT.getTypeForEVT(*DAG->getContext()));
8060
8061     if (RequiredAlignment > getAlignment())
8062       return false;
8063
8064     // 2. Check that the load is a legal operation for that type.
8065     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8066       return false;
8067
8068     // 3. Check that we do not have a zext in the way.
8069     if (Inst->getValueType(0) != getLoadedType())
8070       return false;
8071
8072     return true;
8073   }
8074 };
8075 }
8076
8077 /// \brief Sorts LoadedSlice according to their offset.
8078 struct LoadedSliceSorter {
8079   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8080     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8081     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8082   }
8083 };
8084
8085 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8086 /// \p UsedBits looks like 0..0 1..1 0..0.
8087 static bool areUsedBitsDense(const APInt &UsedBits) {
8088   // If all the bits are one, this is dense!
8089   if (UsedBits.isAllOnesValue())
8090     return true;
8091
8092   // Get rid of the unused bits on the right.
8093   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8094   // Get rid of the unused bits on the left.
8095   if (NarrowedUsedBits.countLeadingZeros())
8096     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8097   // Check that the chunk of bits is completely used.
8098   return NarrowedUsedBits.isAllOnesValue();
8099 }
8100
8101 /// \brief Check whether or not \p First and \p Second are next to each other
8102 /// in memory. This means that there is no hole between the bits loaded
8103 /// by \p First and the bits loaded by \p Second.
8104 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8105                                      const LoadedSlice &Second) {
8106   assert(First.Origin == Second.Origin && First.Origin &&
8107          "Unable to match different memory origins.");
8108   APInt UsedBits = First.getUsedBits();
8109   assert((UsedBits & Second.getUsedBits()) == 0 &&
8110          "Slices are not supposed to overlap.");
8111   UsedBits |= Second.getUsedBits();
8112   return areUsedBitsDense(UsedBits);
8113 }
8114
8115 /// \brief Adjust the \p GlobalLSCost according to the target
8116 /// paring capabilities and the layout of the slices.
8117 /// \pre \p GlobalLSCost should account for at least as many loads as
8118 /// there is in the slices in \p LoadedSlices.
8119 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8120                                  LoadedSlice::Cost &GlobalLSCost) {
8121   unsigned NumberOfSlices = LoadedSlices.size();
8122   // If there is less than 2 elements, no pairing is possible.
8123   if (NumberOfSlices < 2)
8124     return;
8125
8126   // Sort the slices so that elements that are likely to be next to each
8127   // other in memory are next to each other in the list.
8128   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8129   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8130   // First (resp. Second) is the first (resp. Second) potentially candidate
8131   // to be placed in a paired load.
8132   const LoadedSlice *First = NULL;
8133   const LoadedSlice *Second = NULL;
8134   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8135                 // Set the beginning of the pair.
8136                                                            First = Second) {
8137
8138     Second = &LoadedSlices[CurrSlice];
8139
8140     // If First is NULL, it means we start a new pair.
8141     // Get to the next slice.
8142     if (!First)
8143       continue;
8144
8145     EVT LoadedType = First->getLoadedType();
8146
8147     // If the types of the slices are different, we cannot pair them.
8148     if (LoadedType != Second->getLoadedType())
8149       continue;
8150
8151     // Check if the target supplies paired loads for this type.
8152     unsigned RequiredAlignment = 0;
8153     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8154       // move to the next pair, this type is hopeless.
8155       Second = NULL;
8156       continue;
8157     }
8158     // Check if we meet the alignment requirement.
8159     if (RequiredAlignment > First->getAlignment())
8160       continue;
8161
8162     // Check that both loads are next to each other in memory.
8163     if (!areSlicesNextToEachOther(*First, *Second))
8164       continue;
8165
8166     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8167     --GlobalLSCost.Loads;
8168     // Move to the next pair.
8169     Second = NULL;
8170   }
8171 }
8172
8173 /// \brief Check the profitability of all involved LoadedSlice.
8174 /// Currently, it is considered profitable if there is exactly two
8175 /// involved slices (1) which are (2) next to each other in memory, and
8176 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8177 ///
8178 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8179 /// the elements themselves.
8180 ///
8181 /// FIXME: When the cost model will be mature enough, we can relax
8182 /// constraints (1) and (2).
8183 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8184                                 const APInt &UsedBits, bool ForCodeSize) {
8185   unsigned NumberOfSlices = LoadedSlices.size();
8186   if (StressLoadSlicing)
8187     return NumberOfSlices > 1;
8188
8189   // Check (1).
8190   if (NumberOfSlices != 2)
8191     return false;
8192
8193   // Check (2).
8194   if (!areUsedBitsDense(UsedBits))
8195     return false;
8196
8197   // Check (3).
8198   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8199   // The original code has one big load.
8200   OrigCost.Loads = 1;
8201   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8202     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8203     // Accumulate the cost of all the slices.
8204     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8205     GlobalSlicingCost += SliceCost;
8206
8207     // Account as cost in the original configuration the gain obtained
8208     // with the current slices.
8209     OrigCost.addSliceGain(LS);
8210   }
8211
8212   // If the target supports paired load, adjust the cost accordingly.
8213   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8214   return OrigCost > GlobalSlicingCost;
8215 }
8216
8217 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8218 /// operations, split it in the various pieces being extracted.
8219 ///
8220 /// This sort of thing is introduced by SROA.
8221 /// This slicing takes care not to insert overlapping loads.
8222 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8223 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8224   if (Level < AfterLegalizeDAG)
8225     return false;
8226
8227   LoadSDNode *LD = cast<LoadSDNode>(N);
8228   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8229       !LD->getValueType(0).isInteger())
8230     return false;
8231
8232   // Keep track of already used bits to detect overlapping values.
8233   // In that case, we will just abort the transformation.
8234   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8235
8236   SmallVector<LoadedSlice, 4> LoadedSlices;
8237
8238   // Check if this load is used as several smaller chunks of bits.
8239   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8240   // of computation for each trunc.
8241   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8242        UI != UIEnd; ++UI) {
8243     // Skip the uses of the chain.
8244     if (UI.getUse().getResNo() != 0)
8245       continue;
8246
8247     SDNode *User = *UI;
8248     unsigned Shift = 0;
8249
8250     // Check if this is a trunc(lshr).
8251     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8252         isa<ConstantSDNode>(User->getOperand(1))) {
8253       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8254       User = *User->use_begin();
8255     }
8256
8257     // At this point, User is a Truncate, iff we encountered, trunc or
8258     // trunc(lshr).
8259     if (User->getOpcode() != ISD::TRUNCATE)
8260       return false;
8261
8262     // The width of the type must be a power of 2 and greater than 8-bits.
8263     // Otherwise the load cannot be represented in LLVM IR.
8264     // Moreover, if we shifted with a non-8-bits multiple, the slice
8265     // will be accross several bytes. We do not support that.
8266     unsigned Width = User->getValueSizeInBits(0);
8267     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8268       return 0;
8269
8270     // Build the slice for this chain of computations.
8271     LoadedSlice LS(User, LD, Shift, &DAG);
8272     APInt CurrentUsedBits = LS.getUsedBits();
8273
8274     // Check if this slice overlaps with another.
8275     if ((CurrentUsedBits & UsedBits) != 0)
8276       return false;
8277     // Update the bits used globally.
8278     UsedBits |= CurrentUsedBits;
8279
8280     // Check if the new slice would be legal.
8281     if (!LS.isLegal())
8282       return false;
8283
8284     // Record the slice.
8285     LoadedSlices.push_back(LS);
8286   }
8287
8288   // Abort slicing if it does not seem to be profitable.
8289   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8290     return false;
8291
8292   ++SlicedLoads;
8293
8294   // Rewrite each chain to use an independent load.
8295   // By construction, each chain can be represented by a unique load.
8296
8297   // Prepare the argument for the new token factor for all the slices.
8298   SmallVector<SDValue, 8> ArgChains;
8299   for (SmallVectorImpl<LoadedSlice>::const_iterator
8300            LSIt = LoadedSlices.begin(),
8301            LSItEnd = LoadedSlices.end();
8302        LSIt != LSItEnd; ++LSIt) {
8303     SDValue SliceInst = LSIt->loadSlice();
8304     CombineTo(LSIt->Inst, SliceInst, true);
8305     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8306       SliceInst = SliceInst.getOperand(0);
8307     assert(SliceInst->getOpcode() == ISD::LOAD &&
8308            "It takes more than a zext to get to the loaded slice!!");
8309     ArgChains.push_back(SliceInst.getValue(1));
8310   }
8311
8312   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8313                               &ArgChains[0], ArgChains.size());
8314   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8315   return true;
8316 }
8317
8318 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8319 /// load is having specific bytes cleared out.  If so, return the byte size
8320 /// being masked out and the shift amount.
8321 static std::pair<unsigned, unsigned>
8322 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8323   std::pair<unsigned, unsigned> Result(0, 0);
8324
8325   // Check for the structure we're looking for.
8326   if (V->getOpcode() != ISD::AND ||
8327       !isa<ConstantSDNode>(V->getOperand(1)) ||
8328       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8329     return Result;
8330
8331   // Check the chain and pointer.
8332   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8333   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8334
8335   // The store should be chained directly to the load or be an operand of a
8336   // tokenfactor.
8337   if (LD == Chain.getNode())
8338     ; // ok.
8339   else if (Chain->getOpcode() != ISD::TokenFactor)
8340     return Result; // Fail.
8341   else {
8342     bool isOk = false;
8343     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8344       if (Chain->getOperand(i).getNode() == LD) {
8345         isOk = true;
8346         break;
8347       }
8348     if (!isOk) return Result;
8349   }
8350
8351   // This only handles simple types.
8352   if (V.getValueType() != MVT::i16 &&
8353       V.getValueType() != MVT::i32 &&
8354       V.getValueType() != MVT::i64)
8355     return Result;
8356
8357   // Check the constant mask.  Invert it so that the bits being masked out are
8358   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8359   // follow the sign bit for uniformity.
8360   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8361   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8362   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8363   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8364   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8365   if (NotMaskLZ == 64) return Result;  // All zero mask.
8366
8367   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8368   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8369     return Result;
8370
8371   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8372   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8373     NotMaskLZ -= 64-V.getValueSizeInBits();
8374
8375   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8376   switch (MaskedBytes) {
8377   case 1:
8378   case 2:
8379   case 4: break;
8380   default: return Result; // All one mask, or 5-byte mask.
8381   }
8382
8383   // Verify that the first bit starts at a multiple of mask so that the access
8384   // is aligned the same as the access width.
8385   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8386
8387   Result.first = MaskedBytes;
8388   Result.second = NotMaskTZ/8;
8389   return Result;
8390 }
8391
8392
8393 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8394 /// provides a value as specified by MaskInfo.  If so, replace the specified
8395 /// store with a narrower store of truncated IVal.
8396 static SDNode *
8397 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8398                                 SDValue IVal, StoreSDNode *St,
8399                                 DAGCombiner *DC) {
8400   unsigned NumBytes = MaskInfo.first;
8401   unsigned ByteShift = MaskInfo.second;
8402   SelectionDAG &DAG = DC->getDAG();
8403
8404   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8405   // that uses this.  If not, this is not a replacement.
8406   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8407                                   ByteShift*8, (ByteShift+NumBytes)*8);
8408   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8409
8410   // Check that it is legal on the target to do this.  It is legal if the new
8411   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8412   // legalization.
8413   MVT VT = MVT::getIntegerVT(NumBytes*8);
8414   if (!DC->isTypeLegal(VT))
8415     return 0;
8416
8417   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8418   // shifted by ByteShift and truncated down to NumBytes.
8419   if (ByteShift)
8420     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8421                        DAG.getConstant(ByteShift*8,
8422                                     DC->getShiftAmountTy(IVal.getValueType())));
8423
8424   // Figure out the offset for the store and the alignment of the access.
8425   unsigned StOffset;
8426   unsigned NewAlign = St->getAlignment();
8427
8428   if (DAG.getTargetLoweringInfo().isLittleEndian())
8429     StOffset = ByteShift;
8430   else
8431     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8432
8433   SDValue Ptr = St->getBasePtr();
8434   if (StOffset) {
8435     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8436                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8437     NewAlign = MinAlign(NewAlign, StOffset);
8438   }
8439
8440   // Truncate down to the new size.
8441   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8442
8443   ++OpsNarrowed;
8444   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8445                       St->getPointerInfo().getWithOffset(StOffset),
8446                       false, false, NewAlign).getNode();
8447 }
8448
8449
8450 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8451 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8452 /// of the loaded bits, try narrowing the load and store if it would end up
8453 /// being a win for performance or code size.
8454 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8455   StoreSDNode *ST  = cast<StoreSDNode>(N);
8456   if (ST->isVolatile())
8457     return SDValue();
8458
8459   SDValue Chain = ST->getChain();
8460   SDValue Value = ST->getValue();
8461   SDValue Ptr   = ST->getBasePtr();
8462   EVT VT = Value.getValueType();
8463
8464   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8465     return SDValue();
8466
8467   unsigned Opc = Value.getOpcode();
8468
8469   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8470   // is a byte mask indicating a consecutive number of bytes, check to see if
8471   // Y is known to provide just those bytes.  If so, we try to replace the
8472   // load + replace + store sequence with a single (narrower) store, which makes
8473   // the load dead.
8474   if (Opc == ISD::OR) {
8475     std::pair<unsigned, unsigned> MaskedLoad;
8476     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8477     if (MaskedLoad.first)
8478       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8479                                                   Value.getOperand(1), ST,this))
8480         return SDValue(NewST, 0);
8481
8482     // Or is commutative, so try swapping X and Y.
8483     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8484     if (MaskedLoad.first)
8485       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8486                                                   Value.getOperand(0), ST,this))
8487         return SDValue(NewST, 0);
8488   }
8489
8490   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8491       Value.getOperand(1).getOpcode() != ISD::Constant)
8492     return SDValue();
8493
8494   SDValue N0 = Value.getOperand(0);
8495   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8496       Chain == SDValue(N0.getNode(), 1)) {
8497     LoadSDNode *LD = cast<LoadSDNode>(N0);
8498     if (LD->getBasePtr() != Ptr ||
8499         LD->getPointerInfo().getAddrSpace() !=
8500         ST->getPointerInfo().getAddrSpace())
8501       return SDValue();
8502
8503     // Find the type to narrow it the load / op / store to.
8504     SDValue N1 = Value.getOperand(1);
8505     unsigned BitWidth = N1.getValueSizeInBits();
8506     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8507     if (Opc == ISD::AND)
8508       Imm ^= APInt::getAllOnesValue(BitWidth);
8509     if (Imm == 0 || Imm.isAllOnesValue())
8510       return SDValue();
8511     unsigned ShAmt = Imm.countTrailingZeros();
8512     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8513     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8514     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8515     while (NewBW < BitWidth &&
8516            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8517              TLI.isNarrowingProfitable(VT, NewVT))) {
8518       NewBW = NextPowerOf2(NewBW);
8519       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8520     }
8521     if (NewBW >= BitWidth)
8522       return SDValue();
8523
8524     // If the lsb changed does not start at the type bitwidth boundary,
8525     // start at the previous one.
8526     if (ShAmt % NewBW)
8527       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8528     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8529                                    std::min(BitWidth, ShAmt + NewBW));
8530     if ((Imm & Mask) == Imm) {
8531       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8532       if (Opc == ISD::AND)
8533         NewImm ^= APInt::getAllOnesValue(NewBW);
8534       uint64_t PtrOff = ShAmt / 8;
8535       // For big endian targets, we need to adjust the offset to the pointer to
8536       // load the correct bytes.
8537       if (TLI.isBigEndian())
8538         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8539
8540       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8541       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8542       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8543         return SDValue();
8544
8545       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8546                                    Ptr.getValueType(), Ptr,
8547                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8548       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8549                                   LD->getChain(), NewPtr,
8550                                   LD->getPointerInfo().getWithOffset(PtrOff),
8551                                   LD->isVolatile(), LD->isNonTemporal(),
8552                                   LD->isInvariant(), NewAlign,
8553                                   LD->getTBAAInfo());
8554       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8555                                    DAG.getConstant(NewImm, NewVT));
8556       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8557                                    NewVal, NewPtr,
8558                                    ST->getPointerInfo().getWithOffset(PtrOff),
8559                                    false, false, NewAlign);
8560
8561       AddToWorkList(NewPtr.getNode());
8562       AddToWorkList(NewLD.getNode());
8563       AddToWorkList(NewVal.getNode());
8564       WorkListRemover DeadNodes(*this);
8565       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8566       ++OpsNarrowed;
8567       return NewST;
8568     }
8569   }
8570
8571   return SDValue();
8572 }
8573
8574 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8575 /// if the load value isn't used by any other operations, then consider
8576 /// transforming the pair to integer load / store operations if the target
8577 /// deems the transformation profitable.
8578 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8579   StoreSDNode *ST  = cast<StoreSDNode>(N);
8580   SDValue Chain = ST->getChain();
8581   SDValue Value = ST->getValue();
8582   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8583       Value.hasOneUse() &&
8584       Chain == SDValue(Value.getNode(), 1)) {
8585     LoadSDNode *LD = cast<LoadSDNode>(Value);
8586     EVT VT = LD->getMemoryVT();
8587     if (!VT.isFloatingPoint() ||
8588         VT != ST->getMemoryVT() ||
8589         LD->isNonTemporal() ||
8590         ST->isNonTemporal() ||
8591         LD->getPointerInfo().getAddrSpace() != 0 ||
8592         ST->getPointerInfo().getAddrSpace() != 0)
8593       return SDValue();
8594
8595     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8596     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8597         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8598         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8599         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8600       return SDValue();
8601
8602     unsigned LDAlign = LD->getAlignment();
8603     unsigned STAlign = ST->getAlignment();
8604     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8605     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8606     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8607       return SDValue();
8608
8609     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8610                                 LD->getChain(), LD->getBasePtr(),
8611                                 LD->getPointerInfo(),
8612                                 false, false, false, LDAlign);
8613
8614     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8615                                  NewLD, ST->getBasePtr(),
8616                                  ST->getPointerInfo(),
8617                                  false, false, STAlign);
8618
8619     AddToWorkList(NewLD.getNode());
8620     AddToWorkList(NewST.getNode());
8621     WorkListRemover DeadNodes(*this);
8622     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8623     ++LdStFP2Int;
8624     return NewST;
8625   }
8626
8627   return SDValue();
8628 }
8629
8630 /// Helper struct to parse and store a memory address as base + index + offset.
8631 /// We ignore sign extensions when it is safe to do so.
8632 /// The following two expressions are not equivalent. To differentiate we need
8633 /// to store whether there was a sign extension involved in the index
8634 /// computation.
8635 ///  (load (i64 add (i64 copyfromreg %c)
8636 ///                 (i64 signextend (add (i8 load %index)
8637 ///                                      (i8 1))))
8638 /// vs
8639 ///
8640 /// (load (i64 add (i64 copyfromreg %c)
8641 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8642 ///                                         (i32 1)))))
8643 struct BaseIndexOffset {
8644   SDValue Base;
8645   SDValue Index;
8646   int64_t Offset;
8647   bool IsIndexSignExt;
8648
8649   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8650
8651   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8652                   bool IsIndexSignExt) :
8653     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8654
8655   bool equalBaseIndex(const BaseIndexOffset &Other) {
8656     return Other.Base == Base && Other.Index == Index &&
8657       Other.IsIndexSignExt == IsIndexSignExt;
8658   }
8659
8660   /// Parses tree in Ptr for base, index, offset addresses.
8661   static BaseIndexOffset match(SDValue Ptr) {
8662     bool IsIndexSignExt = false;
8663
8664     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8665     // instruction, then it could be just the BASE or everything else we don't
8666     // know how to handle. Just use Ptr as BASE and give up.
8667     if (Ptr->getOpcode() != ISD::ADD)
8668       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8669
8670     // We know that we have at least an ADD instruction. Try to pattern match
8671     // the simple case of BASE + OFFSET.
8672     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8673       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8674       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8675                               IsIndexSignExt);
8676     }
8677
8678     // Inside a loop the current BASE pointer is calculated using an ADD and a
8679     // MUL instruction. In this case Ptr is the actual BASE pointer.
8680     // (i64 add (i64 %array_ptr)
8681     //          (i64 mul (i64 %induction_var)
8682     //                   (i64 %element_size)))
8683     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8684       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8685
8686     // Look at Base + Index + Offset cases.
8687     SDValue Base = Ptr->getOperand(0);
8688     SDValue IndexOffset = Ptr->getOperand(1);
8689
8690     // Skip signextends.
8691     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8692       IndexOffset = IndexOffset->getOperand(0);
8693       IsIndexSignExt = true;
8694     }
8695
8696     // Either the case of Base + Index (no offset) or something else.
8697     if (IndexOffset->getOpcode() != ISD::ADD)
8698       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8699
8700     // Now we have the case of Base + Index + offset.
8701     SDValue Index = IndexOffset->getOperand(0);
8702     SDValue Offset = IndexOffset->getOperand(1);
8703
8704     if (!isa<ConstantSDNode>(Offset))
8705       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8706
8707     // Ignore signextends.
8708     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8709       Index = Index->getOperand(0);
8710       IsIndexSignExt = true;
8711     } else IsIndexSignExt = false;
8712
8713     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8714     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8715   }
8716 };
8717
8718 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8719 /// is located in a sequence of memory operations connected by a chain.
8720 struct MemOpLink {
8721   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8722     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8723   // Ptr to the mem node.
8724   LSBaseSDNode *MemNode;
8725   // Offset from the base ptr.
8726   int64_t OffsetFromBase;
8727   // What is the sequence number of this mem node.
8728   // Lowest mem operand in the DAG starts at zero.
8729   unsigned SequenceNum;
8730 };
8731
8732 /// Sorts store nodes in a link according to their offset from a shared
8733 // base ptr.
8734 struct ConsecutiveMemoryChainSorter {
8735   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8736     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8737   }
8738 };
8739
8740 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8741   EVT MemVT = St->getMemoryVT();
8742   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8743   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8744     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8745
8746   // Don't merge vectors into wider inputs.
8747   if (MemVT.isVector() || !MemVT.isSimple())
8748     return false;
8749
8750   // Perform an early exit check. Do not bother looking at stored values that
8751   // are not constants or loads.
8752   SDValue StoredVal = St->getValue();
8753   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8754   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8755       !IsLoadSrc)
8756     return false;
8757
8758   // Only look at ends of store sequences.
8759   SDValue Chain = SDValue(St, 1);
8760   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8761     return false;
8762
8763   // This holds the base pointer, index, and the offset in bytes from the base
8764   // pointer.
8765   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8766
8767   // We must have a base and an offset.
8768   if (!BasePtr.Base.getNode())
8769     return false;
8770
8771   // Do not handle stores to undef base pointers.
8772   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8773     return false;
8774
8775   // Save the LoadSDNodes that we find in the chain.
8776   // We need to make sure that these nodes do not interfere with
8777   // any of the store nodes.
8778   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8779
8780   // Save the StoreSDNodes that we find in the chain.
8781   SmallVector<MemOpLink, 8> StoreNodes;
8782
8783   // Walk up the chain and look for nodes with offsets from the same
8784   // base pointer. Stop when reaching an instruction with a different kind
8785   // or instruction which has a different base pointer.
8786   unsigned Seq = 0;
8787   StoreSDNode *Index = St;
8788   while (Index) {
8789     // If the chain has more than one use, then we can't reorder the mem ops.
8790     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8791       break;
8792
8793     // Find the base pointer and offset for this memory node.
8794     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8795
8796     // Check that the base pointer is the same as the original one.
8797     if (!Ptr.equalBaseIndex(BasePtr))
8798       break;
8799
8800     // Check that the alignment is the same.
8801     if (Index->getAlignment() != St->getAlignment())
8802       break;
8803
8804     // The memory operands must not be volatile.
8805     if (Index->isVolatile() || Index->isIndexed())
8806       break;
8807
8808     // No truncation.
8809     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8810       if (St->isTruncatingStore())
8811         break;
8812
8813     // The stored memory type must be the same.
8814     if (Index->getMemoryVT() != MemVT)
8815       break;
8816
8817     // We do not allow unaligned stores because we want to prevent overriding
8818     // stores.
8819     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8820       break;
8821
8822     // We found a potential memory operand to merge.
8823     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8824
8825     // Find the next memory operand in the chain. If the next operand in the
8826     // chain is a store then move up and continue the scan with the next
8827     // memory operand. If the next operand is a load save it and use alias
8828     // information to check if it interferes with anything.
8829     SDNode *NextInChain = Index->getChain().getNode();
8830     while (1) {
8831       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8832         // We found a store node. Use it for the next iteration.
8833         Index = STn;
8834         break;
8835       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8836         if (Ldn->isVolatile()) {
8837           Index = NULL;
8838           break;
8839         }
8840
8841         // Save the load node for later. Continue the scan.
8842         AliasLoadNodes.push_back(Ldn);
8843         NextInChain = Ldn->getChain().getNode();
8844         continue;
8845       } else {
8846         Index = NULL;
8847         break;
8848       }
8849     }
8850   }
8851
8852   // Check if there is anything to merge.
8853   if (StoreNodes.size() < 2)
8854     return false;
8855
8856   // Sort the memory operands according to their distance from the base pointer.
8857   std::sort(StoreNodes.begin(), StoreNodes.end(),
8858             ConsecutiveMemoryChainSorter());
8859
8860   // Scan the memory operations on the chain and find the first non-consecutive
8861   // store memory address.
8862   unsigned LastConsecutiveStore = 0;
8863   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8864   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8865
8866     // Check that the addresses are consecutive starting from the second
8867     // element in the list of stores.
8868     if (i > 0) {
8869       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8870       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8871         break;
8872     }
8873
8874     bool Alias = false;
8875     // Check if this store interferes with any of the loads that we found.
8876     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8877       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8878         Alias = true;
8879         break;
8880       }
8881     // We found a load that alias with this store. Stop the sequence.
8882     if (Alias)
8883       break;
8884
8885     // Mark this node as useful.
8886     LastConsecutiveStore = i;
8887   }
8888
8889   // The node with the lowest store address.
8890   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8891
8892   // Store the constants into memory as one consecutive store.
8893   if (!IsLoadSrc) {
8894     unsigned LastLegalType = 0;
8895     unsigned LastLegalVectorType = 0;
8896     bool NonZero = false;
8897     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8898       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8899       SDValue StoredVal = St->getValue();
8900
8901       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8902         NonZero |= !C->isNullValue();
8903       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8904         NonZero |= !C->getConstantFPValue()->isNullValue();
8905       } else {
8906         // Non-constant.
8907         break;
8908       }
8909
8910       // Find a legal type for the constant store.
8911       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8912       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8913       if (TLI.isTypeLegal(StoreTy))
8914         LastLegalType = i+1;
8915       // Or check whether a truncstore is legal.
8916       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8917                TargetLowering::TypePromoteInteger) {
8918         EVT LegalizedStoredValueTy =
8919           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8920         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8921           LastLegalType = i+1;
8922       }
8923
8924       // Find a legal type for the vector store.
8925       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8926       if (TLI.isTypeLegal(Ty))
8927         LastLegalVectorType = i + 1;
8928     }
8929
8930     // We only use vectors if the constant is known to be zero and the
8931     // function is not marked with the noimplicitfloat attribute.
8932     if (NonZero || NoVectors)
8933       LastLegalVectorType = 0;
8934
8935     // Check if we found a legal integer type to store.
8936     if (LastLegalType == 0 && LastLegalVectorType == 0)
8937       return false;
8938
8939     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8940     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8941
8942     // Make sure we have something to merge.
8943     if (NumElem < 2)
8944       return false;
8945
8946     unsigned EarliestNodeUsed = 0;
8947     for (unsigned i=0; i < NumElem; ++i) {
8948       // Find a chain for the new wide-store operand. Notice that some
8949       // of the store nodes that we found may not be selected for inclusion
8950       // in the wide store. The chain we use needs to be the chain of the
8951       // earliest store node which is *used* and replaced by the wide store.
8952       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8953         EarliestNodeUsed = i;
8954     }
8955
8956     // The earliest Node in the DAG.
8957     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8958     SDLoc DL(StoreNodes[0].MemNode);
8959
8960     SDValue StoredVal;
8961     if (UseVector) {
8962       // Find a legal type for the vector store.
8963       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8964       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8965       StoredVal = DAG.getConstant(0, Ty);
8966     } else {
8967       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8968       APInt StoreInt(StoreBW, 0);
8969
8970       // Construct a single integer constant which is made of the smaller
8971       // constant inputs.
8972       bool IsLE = TLI.isLittleEndian();
8973       for (unsigned i = 0; i < NumElem ; ++i) {
8974         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8975         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8976         SDValue Val = St->getValue();
8977         StoreInt<<=ElementSizeBytes*8;
8978         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8979           StoreInt|=C->getAPIntValue().zext(StoreBW);
8980         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8981           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8982         } else {
8983           assert(false && "Invalid constant element type");
8984         }
8985       }
8986
8987       // Create the new Load and Store operations.
8988       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8989       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8990     }
8991
8992     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8993                                     FirstInChain->getBasePtr(),
8994                                     FirstInChain->getPointerInfo(),
8995                                     false, false,
8996                                     FirstInChain->getAlignment());
8997
8998     // Replace the first store with the new store
8999     CombineTo(EarliestOp, NewStore);
9000     // Erase all other stores.
9001     for (unsigned i = 0; i < NumElem ; ++i) {
9002       if (StoreNodes[i].MemNode == EarliestOp)
9003         continue;
9004       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9005       // ReplaceAllUsesWith will replace all uses that existed when it was
9006       // called, but graph optimizations may cause new ones to appear. For
9007       // example, the case in pr14333 looks like
9008       //
9009       //  St's chain -> St -> another store -> X
9010       //
9011       // And the only difference from St to the other store is the chain.
9012       // When we change it's chain to be St's chain they become identical,
9013       // get CSEed and the net result is that X is now a use of St.
9014       // Since we know that St is redundant, just iterate.
9015       while (!St->use_empty())
9016         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9017       removeFromWorkList(St);
9018       DAG.DeleteNode(St);
9019     }
9020
9021     return true;
9022   }
9023
9024   // Below we handle the case of multiple consecutive stores that
9025   // come from multiple consecutive loads. We merge them into a single
9026   // wide load and a single wide store.
9027
9028   // Look for load nodes which are used by the stored values.
9029   SmallVector<MemOpLink, 8> LoadNodes;
9030
9031   // Find acceptable loads. Loads need to have the same chain (token factor),
9032   // must not be zext, volatile, indexed, and they must be consecutive.
9033   BaseIndexOffset LdBasePtr;
9034   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9035     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9036     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9037     if (!Ld) break;
9038
9039     // Loads must only have one use.
9040     if (!Ld->hasNUsesOfValue(1, 0))
9041       break;
9042
9043     // Check that the alignment is the same as the stores.
9044     if (Ld->getAlignment() != St->getAlignment())
9045       break;
9046
9047     // The memory operands must not be volatile.
9048     if (Ld->isVolatile() || Ld->isIndexed())
9049       break;
9050
9051     // We do not accept ext loads.
9052     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9053       break;
9054
9055     // The stored memory type must be the same.
9056     if (Ld->getMemoryVT() != MemVT)
9057       break;
9058
9059     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9060     // If this is not the first ptr that we check.
9061     if (LdBasePtr.Base.getNode()) {
9062       // The base ptr must be the same.
9063       if (!LdPtr.equalBaseIndex(LdBasePtr))
9064         break;
9065     } else {
9066       // Check that all other base pointers are the same as this one.
9067       LdBasePtr = LdPtr;
9068     }
9069
9070     // We found a potential memory operand to merge.
9071     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9072   }
9073
9074   if (LoadNodes.size() < 2)
9075     return false;
9076
9077   // Scan the memory operations on the chain and find the first non-consecutive
9078   // load memory address. These variables hold the index in the store node
9079   // array.
9080   unsigned LastConsecutiveLoad = 0;
9081   // This variable refers to the size and not index in the array.
9082   unsigned LastLegalVectorType = 0;
9083   unsigned LastLegalIntegerType = 0;
9084   StartAddress = LoadNodes[0].OffsetFromBase;
9085   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9086   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9087     // All loads much share the same chain.
9088     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9089       break;
9090
9091     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9092     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9093       break;
9094     LastConsecutiveLoad = i;
9095
9096     // Find a legal type for the vector store.
9097     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9098     if (TLI.isTypeLegal(StoreTy))
9099       LastLegalVectorType = i + 1;
9100
9101     // Find a legal type for the integer store.
9102     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9103     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9104     if (TLI.isTypeLegal(StoreTy))
9105       LastLegalIntegerType = i + 1;
9106     // Or check whether a truncstore and extload is legal.
9107     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9108              TargetLowering::TypePromoteInteger) {
9109       EVT LegalizedStoredValueTy =
9110         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9111       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9112           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9113           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9114           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9115         LastLegalIntegerType = i+1;
9116     }
9117   }
9118
9119   // Only use vector types if the vector type is larger than the integer type.
9120   // If they are the same, use integers.
9121   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9122   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9123
9124   // We add +1 here because the LastXXX variables refer to location while
9125   // the NumElem refers to array/index size.
9126   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9127   NumElem = std::min(LastLegalType, NumElem);
9128
9129   if (NumElem < 2)
9130     return false;
9131
9132   // The earliest Node in the DAG.
9133   unsigned EarliestNodeUsed = 0;
9134   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9135   for (unsigned i=1; i<NumElem; ++i) {
9136     // Find a chain for the new wide-store operand. Notice that some
9137     // of the store nodes that we found may not be selected for inclusion
9138     // in the wide store. The chain we use needs to be the chain of the
9139     // earliest store node which is *used* and replaced by the wide store.
9140     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9141       EarliestNodeUsed = i;
9142   }
9143
9144   // Find if it is better to use vectors or integers to load and store
9145   // to memory.
9146   EVT JointMemOpVT;
9147   if (UseVectorTy) {
9148     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9149   } else {
9150     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9151     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9152   }
9153
9154   SDLoc LoadDL(LoadNodes[0].MemNode);
9155   SDLoc StoreDL(StoreNodes[0].MemNode);
9156
9157   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9158   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9159                                 FirstLoad->getChain(),
9160                                 FirstLoad->getBasePtr(),
9161                                 FirstLoad->getPointerInfo(),
9162                                 false, false, false,
9163                                 FirstLoad->getAlignment());
9164
9165   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9166                                   FirstInChain->getBasePtr(),
9167                                   FirstInChain->getPointerInfo(), false, false,
9168                                   FirstInChain->getAlignment());
9169
9170   // Replace one of the loads with the new load.
9171   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9172   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9173                                 SDValue(NewLoad.getNode(), 1));
9174
9175   // Remove the rest of the load chains.
9176   for (unsigned i = 1; i < NumElem ; ++i) {
9177     // Replace all chain users of the old load nodes with the chain of the new
9178     // load node.
9179     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9180     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9181   }
9182
9183   // Replace the first store with the new store.
9184   CombineTo(EarliestOp, NewStore);
9185   // Erase all other stores.
9186   for (unsigned i = 0; i < NumElem ; ++i) {
9187     // Remove all Store nodes.
9188     if (StoreNodes[i].MemNode == EarliestOp)
9189       continue;
9190     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9191     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9192     removeFromWorkList(St);
9193     DAG.DeleteNode(St);
9194   }
9195
9196   return true;
9197 }
9198
9199 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9200   StoreSDNode *ST  = cast<StoreSDNode>(N);
9201   SDValue Chain = ST->getChain();
9202   SDValue Value = ST->getValue();
9203   SDValue Ptr   = ST->getBasePtr();
9204
9205   // If this is a store of a bit convert, store the input value if the
9206   // resultant store does not need a higher alignment than the original.
9207   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9208       ST->isUnindexed()) {
9209     unsigned OrigAlign = ST->getAlignment();
9210     EVT SVT = Value.getOperand(0).getValueType();
9211     unsigned Align = TLI.getDataLayout()->
9212       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9213     if (Align <= OrigAlign &&
9214         ((!LegalOperations && !ST->isVolatile()) ||
9215          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9216       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9217                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9218                           ST->isNonTemporal(), OrigAlign,
9219                           ST->getTBAAInfo());
9220   }
9221
9222   // Turn 'store undef, Ptr' -> nothing.
9223   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9224     return Chain;
9225
9226   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9227   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9228     // NOTE: If the original store is volatile, this transform must not increase
9229     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9230     // processor operation but an i64 (which is not legal) requires two.  So the
9231     // transform should not be done in this case.
9232     if (Value.getOpcode() != ISD::TargetConstantFP) {
9233       SDValue Tmp;
9234       switch (CFP->getSimpleValueType(0).SimpleTy) {
9235       default: llvm_unreachable("Unknown FP type");
9236       case MVT::f16:    // We don't do this for these yet.
9237       case MVT::f80:
9238       case MVT::f128:
9239       case MVT::ppcf128:
9240         break;
9241       case MVT::f32:
9242         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9243             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9244           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9245                               bitcastToAPInt().getZExtValue(), MVT::i32);
9246           return DAG.getStore(Chain, SDLoc(N), Tmp,
9247                               Ptr, ST->getMemOperand());
9248         }
9249         break;
9250       case MVT::f64:
9251         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9252              !ST->isVolatile()) ||
9253             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9254           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9255                                 getZExtValue(), MVT::i64);
9256           return DAG.getStore(Chain, SDLoc(N), Tmp,
9257                               Ptr, ST->getMemOperand());
9258         }
9259
9260         if (!ST->isVolatile() &&
9261             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9262           // Many FP stores are not made apparent until after legalize, e.g. for
9263           // argument passing.  Since this is so common, custom legalize the
9264           // 64-bit integer store into two 32-bit stores.
9265           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9266           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9267           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9268           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9269
9270           unsigned Alignment = ST->getAlignment();
9271           bool isVolatile = ST->isVolatile();
9272           bool isNonTemporal = ST->isNonTemporal();
9273           const MDNode *TBAAInfo = ST->getTBAAInfo();
9274
9275           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9276                                      Ptr, ST->getPointerInfo(),
9277                                      isVolatile, isNonTemporal,
9278                                      ST->getAlignment(), TBAAInfo);
9279           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9280                             DAG.getConstant(4, Ptr.getValueType()));
9281           Alignment = MinAlign(Alignment, 4U);
9282           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9283                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9284                                      isVolatile, isNonTemporal,
9285                                      Alignment, TBAAInfo);
9286           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9287                              St0, St1);
9288         }
9289
9290         break;
9291       }
9292     }
9293   }
9294
9295   // Try to infer better alignment information than the store already has.
9296   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9297     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9298       if (Align > ST->getAlignment())
9299         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9300                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9301                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9302                                  ST->getTBAAInfo());
9303     }
9304   }
9305
9306   // Try transforming a pair floating point load / store ops to integer
9307   // load / store ops.
9308   SDValue NewST = TransformFPLoadStorePair(N);
9309   if (NewST.getNode())
9310     return NewST;
9311
9312   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9313     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9314   if (UseAA) {
9315     // Walk up chain skipping non-aliasing memory nodes.
9316     SDValue BetterChain = FindBetterChain(N, Chain);
9317
9318     // If there is a better chain.
9319     if (Chain != BetterChain) {
9320       SDValue ReplStore;
9321
9322       // Replace the chain to avoid dependency.
9323       if (ST->isTruncatingStore()) {
9324         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9325                                       ST->getMemoryVT(), ST->getMemOperand());
9326       } else {
9327         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9328                                  ST->getMemOperand());
9329       }
9330
9331       // Create token to keep both nodes around.
9332       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9333                                   MVT::Other, Chain, ReplStore);
9334
9335       // Make sure the new and old chains are cleaned up.
9336       AddToWorkList(Token.getNode());
9337
9338       // Don't add users to work list.
9339       return CombineTo(N, Token, false);
9340     }
9341   }
9342
9343   // Try transforming N to an indexed store.
9344   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9345     return SDValue(N, 0);
9346
9347   // FIXME: is there such a thing as a truncating indexed store?
9348   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9349       Value.getValueType().isInteger()) {
9350     // See if we can simplify the input to this truncstore with knowledge that
9351     // only the low bits are being used.  For example:
9352     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9353     SDValue Shorter =
9354       GetDemandedBits(Value,
9355                       APInt::getLowBitsSet(
9356                         Value.getValueType().getScalarType().getSizeInBits(),
9357                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9358     AddToWorkList(Value.getNode());
9359     if (Shorter.getNode())
9360       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9361                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9362
9363     // Otherwise, see if we can simplify the operation with
9364     // SimplifyDemandedBits, which only works if the value has a single use.
9365     if (SimplifyDemandedBits(Value,
9366                         APInt::getLowBitsSet(
9367                           Value.getValueType().getScalarType().getSizeInBits(),
9368                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9369       return SDValue(N, 0);
9370   }
9371
9372   // If this is a load followed by a store to the same location, then the store
9373   // is dead/noop.
9374   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9375     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9376         ST->isUnindexed() && !ST->isVolatile() &&
9377         // There can't be any side effects between the load and store, such as
9378         // a call or store.
9379         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9380       // The store is dead, remove it.
9381       return Chain;
9382     }
9383   }
9384
9385   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9386   // truncating store.  We can do this even if this is already a truncstore.
9387   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9388       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9389       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9390                             ST->getMemoryVT())) {
9391     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9392                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9393   }
9394
9395   // Only perform this optimization before the types are legal, because we
9396   // don't want to perform this optimization on every DAGCombine invocation.
9397   if (!LegalTypes) {
9398     bool EverChanged = false;
9399
9400     do {
9401       // There can be multiple store sequences on the same chain.
9402       // Keep trying to merge store sequences until we are unable to do so
9403       // or until we merge the last store on the chain.
9404       bool Changed = MergeConsecutiveStores(ST);
9405       EverChanged |= Changed;
9406       if (!Changed) break;
9407     } while (ST->getOpcode() != ISD::DELETED_NODE);
9408
9409     if (EverChanged)
9410       return SDValue(N, 0);
9411   }
9412
9413   return ReduceLoadOpStoreWidth(N);
9414 }
9415
9416 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9417   SDValue InVec = N->getOperand(0);
9418   SDValue InVal = N->getOperand(1);
9419   SDValue EltNo = N->getOperand(2);
9420   SDLoc dl(N);
9421
9422   // If the inserted element is an UNDEF, just use the input vector.
9423   if (InVal.getOpcode() == ISD::UNDEF)
9424     return InVec;
9425
9426   EVT VT = InVec.getValueType();
9427
9428   // If we can't generate a legal BUILD_VECTOR, exit
9429   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9430     return SDValue();
9431
9432   // Check that we know which element is being inserted
9433   if (!isa<ConstantSDNode>(EltNo))
9434     return SDValue();
9435   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9436
9437   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9438   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9439   // vector elements.
9440   SmallVector<SDValue, 8> Ops;
9441   // Do not combine these two vectors if the output vector will not replace
9442   // the input vector.
9443   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9444     Ops.append(InVec.getNode()->op_begin(),
9445                InVec.getNode()->op_end());
9446   } else if (InVec.getOpcode() == ISD::UNDEF) {
9447     unsigned NElts = VT.getVectorNumElements();
9448     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9449   } else {
9450     return SDValue();
9451   }
9452
9453   // Insert the element
9454   if (Elt < Ops.size()) {
9455     // All the operands of BUILD_VECTOR must have the same type;
9456     // we enforce that here.
9457     EVT OpVT = Ops[0].getValueType();
9458     if (InVal.getValueType() != OpVT)
9459       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9460                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9461                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9462     Ops[Elt] = InVal;
9463   }
9464
9465   // Return the new vector
9466   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9467                      VT, &Ops[0], Ops.size());
9468 }
9469
9470 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9471   // (vextract (scalar_to_vector val, 0) -> val
9472   SDValue InVec = N->getOperand(0);
9473   EVT VT = InVec.getValueType();
9474   EVT NVT = N->getValueType(0);
9475
9476   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9477     // Check if the result type doesn't match the inserted element type. A
9478     // SCALAR_TO_VECTOR may truncate the inserted element and the
9479     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9480     SDValue InOp = InVec.getOperand(0);
9481     if (InOp.getValueType() != NVT) {
9482       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9483       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9484     }
9485     return InOp;
9486   }
9487
9488   SDValue EltNo = N->getOperand(1);
9489   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9490
9491   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9492   // We only perform this optimization before the op legalization phase because
9493   // we may introduce new vector instructions which are not backed by TD
9494   // patterns. For example on AVX, extracting elements from a wide vector
9495   // without using extract_subvector.
9496   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9497       && ConstEltNo && !LegalOperations) {
9498     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9499     int NumElem = VT.getVectorNumElements();
9500     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9501     // Find the new index to extract from.
9502     int OrigElt = SVOp->getMaskElt(Elt);
9503
9504     // Extracting an undef index is undef.
9505     if (OrigElt == -1)
9506       return DAG.getUNDEF(NVT);
9507
9508     // Select the right vector half to extract from.
9509     if (OrigElt < NumElem) {
9510       InVec = InVec->getOperand(0);
9511     } else {
9512       InVec = InVec->getOperand(1);
9513       OrigElt -= NumElem;
9514     }
9515
9516     EVT IndexTy = TLI.getVectorIdxTy();
9517     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9518                        InVec, DAG.getConstant(OrigElt, IndexTy));
9519   }
9520
9521   // Perform only after legalization to ensure build_vector / vector_shuffle
9522   // optimizations have already been done.
9523   if (!LegalOperations) return SDValue();
9524
9525   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9526   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9527   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9528
9529   if (ConstEltNo) {
9530     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9531     bool NewLoad = false;
9532     bool BCNumEltsChanged = false;
9533     EVT ExtVT = VT.getVectorElementType();
9534     EVT LVT = ExtVT;
9535
9536     // If the result of load has to be truncated, then it's not necessarily
9537     // profitable.
9538     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9539       return SDValue();
9540
9541     if (InVec.getOpcode() == ISD::BITCAST) {
9542       // Don't duplicate a load with other uses.
9543       if (!InVec.hasOneUse())
9544         return SDValue();
9545
9546       EVT BCVT = InVec.getOperand(0).getValueType();
9547       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9548         return SDValue();
9549       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9550         BCNumEltsChanged = true;
9551       InVec = InVec.getOperand(0);
9552       ExtVT = BCVT.getVectorElementType();
9553       NewLoad = true;
9554     }
9555
9556     LoadSDNode *LN0 = NULL;
9557     const ShuffleVectorSDNode *SVN = NULL;
9558     if (ISD::isNormalLoad(InVec.getNode())) {
9559       LN0 = cast<LoadSDNode>(InVec);
9560     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9561                InVec.getOperand(0).getValueType() == ExtVT &&
9562                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9563       // Don't duplicate a load with other uses.
9564       if (!InVec.hasOneUse())
9565         return SDValue();
9566
9567       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9568     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9569       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9570       // =>
9571       // (load $addr+1*size)
9572
9573       // Don't duplicate a load with other uses.
9574       if (!InVec.hasOneUse())
9575         return SDValue();
9576
9577       // If the bit convert changed the number of elements, it is unsafe
9578       // to examine the mask.
9579       if (BCNumEltsChanged)
9580         return SDValue();
9581
9582       // Select the input vector, guarding against out of range extract vector.
9583       unsigned NumElems = VT.getVectorNumElements();
9584       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9585       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9586
9587       if (InVec.getOpcode() == ISD::BITCAST) {
9588         // Don't duplicate a load with other uses.
9589         if (!InVec.hasOneUse())
9590           return SDValue();
9591
9592         InVec = InVec.getOperand(0);
9593       }
9594       if (ISD::isNormalLoad(InVec.getNode())) {
9595         LN0 = cast<LoadSDNode>(InVec);
9596         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9597       }
9598     }
9599
9600     // Make sure we found a non-volatile load and the extractelement is
9601     // the only use.
9602     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9603       return SDValue();
9604
9605     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9606     if (Elt == -1)
9607       return DAG.getUNDEF(LVT);
9608
9609     unsigned Align = LN0->getAlignment();
9610     if (NewLoad) {
9611       // Check the resultant load doesn't need a higher alignment than the
9612       // original load.
9613       unsigned NewAlign =
9614         TLI.getDataLayout()
9615             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9616
9617       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9618         return SDValue();
9619
9620       Align = NewAlign;
9621     }
9622
9623     SDValue NewPtr = LN0->getBasePtr();
9624     unsigned PtrOff = 0;
9625
9626     if (Elt) {
9627       PtrOff = LVT.getSizeInBits() * Elt / 8;
9628       EVT PtrType = NewPtr.getValueType();
9629       if (TLI.isBigEndian())
9630         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9631       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9632                            DAG.getConstant(PtrOff, PtrType));
9633     }
9634
9635     // The replacement we need to do here is a little tricky: we need to
9636     // replace an extractelement of a load with a load.
9637     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9638     // Note that this replacement assumes that the extractvalue is the only
9639     // use of the load; that's okay because we don't want to perform this
9640     // transformation in other cases anyway.
9641     SDValue Load;
9642     SDValue Chain;
9643     if (NVT.bitsGT(LVT)) {
9644       // If the result type of vextract is wider than the load, then issue an
9645       // extending load instead.
9646       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9647         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9648       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9649                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9650                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9651                             Align, LN0->getTBAAInfo());
9652       Chain = Load.getValue(1);
9653     } else {
9654       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9655                          LN0->getPointerInfo().getWithOffset(PtrOff),
9656                          LN0->isVolatile(), LN0->isNonTemporal(),
9657                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9658       Chain = Load.getValue(1);
9659       if (NVT.bitsLT(LVT))
9660         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9661       else
9662         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9663     }
9664     WorkListRemover DeadNodes(*this);
9665     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9666     SDValue To[] = { Load, Chain };
9667     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9668     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9669     // worklist explicitly as well.
9670     AddToWorkList(Load.getNode());
9671     AddUsersToWorkList(Load.getNode()); // Add users too
9672     // Make sure to revisit this node to clean it up; it will usually be dead.
9673     AddToWorkList(N);
9674     return SDValue(N, 0);
9675   }
9676
9677   return SDValue();
9678 }
9679
9680 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9681 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9682   // We perform this optimization post type-legalization because
9683   // the type-legalizer often scalarizes integer-promoted vectors.
9684   // Performing this optimization before may create bit-casts which
9685   // will be type-legalized to complex code sequences.
9686   // We perform this optimization only before the operation legalizer because we
9687   // may introduce illegal operations.
9688   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9689     return SDValue();
9690
9691   unsigned NumInScalars = N->getNumOperands();
9692   SDLoc dl(N);
9693   EVT VT = N->getValueType(0);
9694
9695   // Check to see if this is a BUILD_VECTOR of a bunch of values
9696   // which come from any_extend or zero_extend nodes. If so, we can create
9697   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9698   // optimizations. We do not handle sign-extend because we can't fill the sign
9699   // using shuffles.
9700   EVT SourceType = MVT::Other;
9701   bool AllAnyExt = true;
9702
9703   for (unsigned i = 0; i != NumInScalars; ++i) {
9704     SDValue In = N->getOperand(i);
9705     // Ignore undef inputs.
9706     if (In.getOpcode() == ISD::UNDEF) continue;
9707
9708     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9709     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9710
9711     // Abort if the element is not an extension.
9712     if (!ZeroExt && !AnyExt) {
9713       SourceType = MVT::Other;
9714       break;
9715     }
9716
9717     // The input is a ZeroExt or AnyExt. Check the original type.
9718     EVT InTy = In.getOperand(0).getValueType();
9719
9720     // Check that all of the widened source types are the same.
9721     if (SourceType == MVT::Other)
9722       // First time.
9723       SourceType = InTy;
9724     else if (InTy != SourceType) {
9725       // Multiple income types. Abort.
9726       SourceType = MVT::Other;
9727       break;
9728     }
9729
9730     // Check if all of the extends are ANY_EXTENDs.
9731     AllAnyExt &= AnyExt;
9732   }
9733
9734   // In order to have valid types, all of the inputs must be extended from the
9735   // same source type and all of the inputs must be any or zero extend.
9736   // Scalar sizes must be a power of two.
9737   EVT OutScalarTy = VT.getScalarType();
9738   bool ValidTypes = SourceType != MVT::Other &&
9739                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9740                  isPowerOf2_32(SourceType.getSizeInBits());
9741
9742   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9743   // turn into a single shuffle instruction.
9744   if (!ValidTypes)
9745     return SDValue();
9746
9747   bool isLE = TLI.isLittleEndian();
9748   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9749   assert(ElemRatio > 1 && "Invalid element size ratio");
9750   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9751                                DAG.getConstant(0, SourceType);
9752
9753   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9754   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9755
9756   // Populate the new build_vector
9757   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9758     SDValue Cast = N->getOperand(i);
9759     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9760             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9761             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9762     SDValue In;
9763     if (Cast.getOpcode() == ISD::UNDEF)
9764       In = DAG.getUNDEF(SourceType);
9765     else
9766       In = Cast->getOperand(0);
9767     unsigned Index = isLE ? (i * ElemRatio) :
9768                             (i * ElemRatio + (ElemRatio - 1));
9769
9770     assert(Index < Ops.size() && "Invalid index");
9771     Ops[Index] = In;
9772   }
9773
9774   // The type of the new BUILD_VECTOR node.
9775   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9776   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9777          "Invalid vector size");
9778   // Check if the new vector type is legal.
9779   if (!isTypeLegal(VecVT)) return SDValue();
9780
9781   // Make the new BUILD_VECTOR.
9782   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9783
9784   // The new BUILD_VECTOR node has the potential to be further optimized.
9785   AddToWorkList(BV.getNode());
9786   // Bitcast to the desired type.
9787   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9788 }
9789
9790 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9791   EVT VT = N->getValueType(0);
9792
9793   unsigned NumInScalars = N->getNumOperands();
9794   SDLoc dl(N);
9795
9796   EVT SrcVT = MVT::Other;
9797   unsigned Opcode = ISD::DELETED_NODE;
9798   unsigned NumDefs = 0;
9799
9800   for (unsigned i = 0; i != NumInScalars; ++i) {
9801     SDValue In = N->getOperand(i);
9802     unsigned Opc = In.getOpcode();
9803
9804     if (Opc == ISD::UNDEF)
9805       continue;
9806
9807     // If all scalar values are floats and converted from integers.
9808     if (Opcode == ISD::DELETED_NODE &&
9809         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9810       Opcode = Opc;
9811     }
9812
9813     if (Opc != Opcode)
9814       return SDValue();
9815
9816     EVT InVT = In.getOperand(0).getValueType();
9817
9818     // If all scalar values are typed differently, bail out. It's chosen to
9819     // simplify BUILD_VECTOR of integer types.
9820     if (SrcVT == MVT::Other)
9821       SrcVT = InVT;
9822     if (SrcVT != InVT)
9823       return SDValue();
9824     NumDefs++;
9825   }
9826
9827   // If the vector has just one element defined, it's not worth to fold it into
9828   // a vectorized one.
9829   if (NumDefs < 2)
9830     return SDValue();
9831
9832   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9833          && "Should only handle conversion from integer to float.");
9834   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9835
9836   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9837
9838   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9839     return SDValue();
9840
9841   SmallVector<SDValue, 8> Opnds;
9842   for (unsigned i = 0; i != NumInScalars; ++i) {
9843     SDValue In = N->getOperand(i);
9844
9845     if (In.getOpcode() == ISD::UNDEF)
9846       Opnds.push_back(DAG.getUNDEF(SrcVT));
9847     else
9848       Opnds.push_back(In.getOperand(0));
9849   }
9850   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9851                            &Opnds[0], Opnds.size());
9852   AddToWorkList(BV.getNode());
9853
9854   return DAG.getNode(Opcode, dl, VT, BV);
9855 }
9856
9857 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9858   unsigned NumInScalars = N->getNumOperands();
9859   SDLoc dl(N);
9860   EVT VT = N->getValueType(0);
9861
9862   // A vector built entirely of undefs is undef.
9863   if (ISD::allOperandsUndef(N))
9864     return DAG.getUNDEF(VT);
9865
9866   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9867   if (V.getNode())
9868     return V;
9869
9870   V = reduceBuildVecConvertToConvertBuildVec(N);
9871   if (V.getNode())
9872     return V;
9873
9874   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9875   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9876   // at most two distinct vectors, turn this into a shuffle node.
9877
9878   // May only combine to shuffle after legalize if shuffle is legal.
9879   if (LegalOperations &&
9880       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9881     return SDValue();
9882
9883   SDValue VecIn1, VecIn2;
9884   for (unsigned i = 0; i != NumInScalars; ++i) {
9885     // Ignore undef inputs.
9886     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9887
9888     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9889     // constant index, bail out.
9890     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9891         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9892       VecIn1 = VecIn2 = SDValue(0, 0);
9893       break;
9894     }
9895
9896     // We allow up to two distinct input vectors.
9897     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9898     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9899       continue;
9900
9901     if (VecIn1.getNode() == 0) {
9902       VecIn1 = ExtractedFromVec;
9903     } else if (VecIn2.getNode() == 0) {
9904       VecIn2 = ExtractedFromVec;
9905     } else {
9906       // Too many inputs.
9907       VecIn1 = VecIn2 = SDValue(0, 0);
9908       break;
9909     }
9910   }
9911
9912     // If everything is good, we can make a shuffle operation.
9913   if (VecIn1.getNode()) {
9914     SmallVector<int, 8> Mask;
9915     for (unsigned i = 0; i != NumInScalars; ++i) {
9916       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9917         Mask.push_back(-1);
9918         continue;
9919       }
9920
9921       // If extracting from the first vector, just use the index directly.
9922       SDValue Extract = N->getOperand(i);
9923       SDValue ExtVal = Extract.getOperand(1);
9924       if (Extract.getOperand(0) == VecIn1) {
9925         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9926         if (ExtIndex > VT.getVectorNumElements())
9927           return SDValue();
9928
9929         Mask.push_back(ExtIndex);
9930         continue;
9931       }
9932
9933       // Otherwise, use InIdx + VecSize
9934       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9935       Mask.push_back(Idx+NumInScalars);
9936     }
9937
9938     // We can't generate a shuffle node with mismatched input and output types.
9939     // Attempt to transform a single input vector to the correct type.
9940     if ((VT != VecIn1.getValueType())) {
9941       // We don't support shuffeling between TWO values of different types.
9942       if (VecIn2.getNode() != 0)
9943         return SDValue();
9944
9945       // We only support widening of vectors which are half the size of the
9946       // output registers. For example XMM->YMM widening on X86 with AVX.
9947       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9948         return SDValue();
9949
9950       // If the input vector type has a different base type to the output
9951       // vector type, bail out.
9952       if (VecIn1.getValueType().getVectorElementType() !=
9953           VT.getVectorElementType())
9954         return SDValue();
9955
9956       // Widen the input vector by adding undef values.
9957       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9958                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9959     }
9960
9961     // If VecIn2 is unused then change it to undef.
9962     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9963
9964     // Check that we were able to transform all incoming values to the same
9965     // type.
9966     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9967         VecIn1.getValueType() != VT)
9968           return SDValue();
9969
9970     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9971     if (!isTypeLegal(VT))
9972       return SDValue();
9973
9974     // Return the new VECTOR_SHUFFLE node.
9975     SDValue Ops[2];
9976     Ops[0] = VecIn1;
9977     Ops[1] = VecIn2;
9978     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9979   }
9980
9981   return SDValue();
9982 }
9983
9984 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9985   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9986   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9987   // inputs come from at most two distinct vectors, turn this into a shuffle
9988   // node.
9989
9990   // If we only have one input vector, we don't need to do any concatenation.
9991   if (N->getNumOperands() == 1)
9992     return N->getOperand(0);
9993
9994   // Check if all of the operands are undefs.
9995   EVT VT = N->getValueType(0);
9996   if (ISD::allOperandsUndef(N))
9997     return DAG.getUNDEF(VT);
9998
9999   // Optimize concat_vectors where one of the vectors is undef.
10000   if (N->getNumOperands() == 2 &&
10001       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10002     SDValue In = N->getOperand(0);
10003     assert(In.getValueType().isVector() && "Must concat vectors");
10004
10005     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10006     if (In->getOpcode() == ISD::BITCAST &&
10007         !In->getOperand(0)->getValueType(0).isVector()) {
10008       SDValue Scalar = In->getOperand(0);
10009       EVT SclTy = Scalar->getValueType(0);
10010
10011       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10012         return SDValue();
10013
10014       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10015                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10016       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10017         return SDValue();
10018
10019       SDLoc dl = SDLoc(N);
10020       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10021       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10022     }
10023   }
10024
10025   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10026   // nodes often generate nop CONCAT_VECTOR nodes.
10027   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10028   // place the incoming vectors at the exact same location.
10029   SDValue SingleSource = SDValue();
10030   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10031
10032   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10033     SDValue Op = N->getOperand(i);
10034
10035     if (Op.getOpcode() == ISD::UNDEF)
10036       continue;
10037
10038     // Check if this is the identity extract:
10039     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10040       return SDValue();
10041
10042     // Find the single incoming vector for the extract_subvector.
10043     if (SingleSource.getNode()) {
10044       if (Op.getOperand(0) != SingleSource)
10045         return SDValue();
10046     } else {
10047       SingleSource = Op.getOperand(0);
10048
10049       // Check the source type is the same as the type of the result.
10050       // If not, this concat may extend the vector, so we can not
10051       // optimize it away.
10052       if (SingleSource.getValueType() != N->getValueType(0))
10053         return SDValue();
10054     }
10055
10056     unsigned IdentityIndex = i * PartNumElem;
10057     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10058     // The extract index must be constant.
10059     if (!CS)
10060       return SDValue();
10061
10062     // Check that we are reading from the identity index.
10063     if (CS->getZExtValue() != IdentityIndex)
10064       return SDValue();
10065   }
10066
10067   if (SingleSource.getNode())
10068     return SingleSource;
10069
10070   return SDValue();
10071 }
10072
10073 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10074   EVT NVT = N->getValueType(0);
10075   SDValue V = N->getOperand(0);
10076
10077   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10078     // Combine:
10079     //    (extract_subvec (concat V1, V2, ...), i)
10080     // Into:
10081     //    Vi if possible
10082     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10083     // type.
10084     if (V->getOperand(0).getValueType() != NVT)
10085       return SDValue();
10086     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10087     unsigned NumElems = NVT.getVectorNumElements();
10088     assert((Idx % NumElems) == 0 &&
10089            "IDX in concat is not a multiple of the result vector length.");
10090     return V->getOperand(Idx / NumElems);
10091   }
10092
10093   // Skip bitcasting
10094   if (V->getOpcode() == ISD::BITCAST)
10095     V = V.getOperand(0);
10096
10097   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10098     SDLoc dl(N);
10099     // Handle only simple case where vector being inserted and vector
10100     // being extracted are of same type, and are half size of larger vectors.
10101     EVT BigVT = V->getOperand(0).getValueType();
10102     EVT SmallVT = V->getOperand(1).getValueType();
10103     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10104       return SDValue();
10105
10106     // Only handle cases where both indexes are constants with the same type.
10107     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10108     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10109
10110     if (InsIdx && ExtIdx &&
10111         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10112         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10113       // Combine:
10114       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10115       // Into:
10116       //    indices are equal or bit offsets are equal => V1
10117       //    otherwise => (extract_subvec V1, ExtIdx)
10118       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10119           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10120         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10121       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10122                          DAG.getNode(ISD::BITCAST, dl,
10123                                      N->getOperand(0).getValueType(),
10124                                      V->getOperand(0)), N->getOperand(1));
10125     }
10126   }
10127
10128   return SDValue();
10129 }
10130
10131 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10132 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10133   EVT VT = N->getValueType(0);
10134   unsigned NumElts = VT.getVectorNumElements();
10135
10136   SDValue N0 = N->getOperand(0);
10137   SDValue N1 = N->getOperand(1);
10138   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10139
10140   SmallVector<SDValue, 4> Ops;
10141   EVT ConcatVT = N0.getOperand(0).getValueType();
10142   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10143   unsigned NumConcats = NumElts / NumElemsPerConcat;
10144
10145   // Look at every vector that's inserted. We're looking for exact
10146   // subvector-sized copies from a concatenated vector
10147   for (unsigned I = 0; I != NumConcats; ++I) {
10148     // Make sure we're dealing with a copy.
10149     unsigned Begin = I * NumElemsPerConcat;
10150     bool AllUndef = true, NoUndef = true;
10151     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10152       if (SVN->getMaskElt(J) >= 0)
10153         AllUndef = false;
10154       else
10155         NoUndef = false;
10156     }
10157
10158     if (NoUndef) {
10159       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10160         return SDValue();
10161
10162       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10163         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10164           return SDValue();
10165
10166       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10167       if (FirstElt < N0.getNumOperands())
10168         Ops.push_back(N0.getOperand(FirstElt));
10169       else
10170         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10171
10172     } else if (AllUndef) {
10173       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10174     } else { // Mixed with general masks and undefs, can't do optimization.
10175       return SDValue();
10176     }
10177   }
10178
10179   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10180                      Ops.size());
10181 }
10182
10183 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10184   EVT VT = N->getValueType(0);
10185   unsigned NumElts = VT.getVectorNumElements();
10186
10187   SDValue N0 = N->getOperand(0);
10188   SDValue N1 = N->getOperand(1);
10189
10190   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10191
10192   // Canonicalize shuffle undef, undef -> undef
10193   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10194     return DAG.getUNDEF(VT);
10195
10196   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10197
10198   // Canonicalize shuffle v, v -> v, undef
10199   if (N0 == N1) {
10200     SmallVector<int, 8> NewMask;
10201     for (unsigned i = 0; i != NumElts; ++i) {
10202       int Idx = SVN->getMaskElt(i);
10203       if (Idx >= (int)NumElts) Idx -= NumElts;
10204       NewMask.push_back(Idx);
10205     }
10206     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10207                                 &NewMask[0]);
10208   }
10209
10210   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10211   if (N0.getOpcode() == ISD::UNDEF) {
10212     SmallVector<int, 8> NewMask;
10213     for (unsigned i = 0; i != NumElts; ++i) {
10214       int Idx = SVN->getMaskElt(i);
10215       if (Idx >= 0) {
10216         if (Idx >= (int)NumElts)
10217           Idx -= NumElts;
10218         else
10219           Idx = -1; // remove reference to lhs
10220       }
10221       NewMask.push_back(Idx);
10222     }
10223     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10224                                 &NewMask[0]);
10225   }
10226
10227   // Remove references to rhs if it is undef
10228   if (N1.getOpcode() == ISD::UNDEF) {
10229     bool Changed = false;
10230     SmallVector<int, 8> NewMask;
10231     for (unsigned i = 0; i != NumElts; ++i) {
10232       int Idx = SVN->getMaskElt(i);
10233       if (Idx >= (int)NumElts) {
10234         Idx = -1;
10235         Changed = true;
10236       }
10237       NewMask.push_back(Idx);
10238     }
10239     if (Changed)
10240       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10241   }
10242
10243   // If it is a splat, check if the argument vector is another splat or a
10244   // build_vector with all scalar elements the same.
10245   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10246     SDNode *V = N0.getNode();
10247
10248     // If this is a bit convert that changes the element type of the vector but
10249     // not the number of vector elements, look through it.  Be careful not to
10250     // look though conversions that change things like v4f32 to v2f64.
10251     if (V->getOpcode() == ISD::BITCAST) {
10252       SDValue ConvInput = V->getOperand(0);
10253       if (ConvInput.getValueType().isVector() &&
10254           ConvInput.getValueType().getVectorNumElements() == NumElts)
10255         V = ConvInput.getNode();
10256     }
10257
10258     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10259       assert(V->getNumOperands() == NumElts &&
10260              "BUILD_VECTOR has wrong number of operands");
10261       SDValue Base;
10262       bool AllSame = true;
10263       for (unsigned i = 0; i != NumElts; ++i) {
10264         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10265           Base = V->getOperand(i);
10266           break;
10267         }
10268       }
10269       // Splat of <u, u, u, u>, return <u, u, u, u>
10270       if (!Base.getNode())
10271         return N0;
10272       for (unsigned i = 0; i != NumElts; ++i) {
10273         if (V->getOperand(i) != Base) {
10274           AllSame = false;
10275           break;
10276         }
10277       }
10278       // Splat of <x, x, x, x>, return <x, x, x, x>
10279       if (AllSame)
10280         return N0;
10281     }
10282   }
10283
10284   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10285       Level < AfterLegalizeVectorOps &&
10286       (N1.getOpcode() == ISD::UNDEF ||
10287       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10288        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10289     SDValue V = partitionShuffleOfConcats(N, DAG);
10290
10291     if (V.getNode())
10292       return V;
10293   }
10294
10295   // If this shuffle node is simply a swizzle of another shuffle node,
10296   // and it reverses the swizzle of the previous shuffle then we can
10297   // optimize shuffle(shuffle(x, undef), undef) -> x.
10298   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10299       N1.getOpcode() == ISD::UNDEF) {
10300
10301     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10302
10303     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10304     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10305       return SDValue();
10306
10307     // The incoming shuffle must be of the same type as the result of the
10308     // current shuffle.
10309     assert(OtherSV->getOperand(0).getValueType() == VT &&
10310            "Shuffle types don't match");
10311
10312     for (unsigned i = 0; i != NumElts; ++i) {
10313       int Idx = SVN->getMaskElt(i);
10314       assert(Idx < (int)NumElts && "Index references undef operand");
10315       // Next, this index comes from the first value, which is the incoming
10316       // shuffle. Adopt the incoming index.
10317       if (Idx >= 0)
10318         Idx = OtherSV->getMaskElt(Idx);
10319
10320       // The combined shuffle must map each index to itself.
10321       if (Idx >= 0 && (unsigned)Idx != i)
10322         return SDValue();
10323     }
10324
10325     return OtherSV->getOperand(0);
10326   }
10327
10328   return SDValue();
10329 }
10330
10331 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10332 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10333 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10334 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10335 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10336   EVT VT = N->getValueType(0);
10337   SDLoc dl(N);
10338   SDValue LHS = N->getOperand(0);
10339   SDValue RHS = N->getOperand(1);
10340   if (N->getOpcode() == ISD::AND) {
10341     if (RHS.getOpcode() == ISD::BITCAST)
10342       RHS = RHS.getOperand(0);
10343     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10344       SmallVector<int, 8> Indices;
10345       unsigned NumElts = RHS.getNumOperands();
10346       for (unsigned i = 0; i != NumElts; ++i) {
10347         SDValue Elt = RHS.getOperand(i);
10348         if (!isa<ConstantSDNode>(Elt))
10349           return SDValue();
10350
10351         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10352           Indices.push_back(i);
10353         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10354           Indices.push_back(NumElts);
10355         else
10356           return SDValue();
10357       }
10358
10359       // Let's see if the target supports this vector_shuffle.
10360       EVT RVT = RHS.getValueType();
10361       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10362         return SDValue();
10363
10364       // Return the new VECTOR_SHUFFLE node.
10365       EVT EltVT = RVT.getVectorElementType();
10366       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10367                                      DAG.getConstant(0, EltVT));
10368       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10369                                  RVT, &ZeroOps[0], ZeroOps.size());
10370       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10371       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10372       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10373     }
10374   }
10375
10376   return SDValue();
10377 }
10378
10379 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10380 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10381   assert(N->getValueType(0).isVector() &&
10382          "SimplifyVBinOp only works on vectors!");
10383
10384   SDValue LHS = N->getOperand(0);
10385   SDValue RHS = N->getOperand(1);
10386   SDValue Shuffle = XformToShuffleWithZero(N);
10387   if (Shuffle.getNode()) return Shuffle;
10388
10389   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10390   // this operation.
10391   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10392       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10393     // Check if both vectors are constants. If not bail out.
10394     if (!cast<BuildVectorSDNode>(LHS)->isConstant() &&
10395         !cast<BuildVectorSDNode>(RHS)->isConstant())
10396       return SDValue();
10397
10398     SmallVector<SDValue, 8> Ops;
10399     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10400       SDValue LHSOp = LHS.getOperand(i);
10401       SDValue RHSOp = RHS.getOperand(i);
10402
10403       // Can't fold divide by zero.
10404       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10405           N->getOpcode() == ISD::FDIV) {
10406         if ((RHSOp.getOpcode() == ISD::Constant &&
10407              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10408             (RHSOp.getOpcode() == ISD::ConstantFP &&
10409              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10410           break;
10411       }
10412
10413       EVT VT = LHSOp.getValueType();
10414       EVT RVT = RHSOp.getValueType();
10415       if (RVT != VT) {
10416         // Integer BUILD_VECTOR operands may have types larger than the element
10417         // size (e.g., when the element type is not legal).  Prior to type
10418         // legalization, the types may not match between the two BUILD_VECTORS.
10419         // Truncate one of the operands to make them match.
10420         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10421           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10422         } else {
10423           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10424           VT = RVT;
10425         }
10426       }
10427       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10428                                    LHSOp, RHSOp);
10429       if (FoldOp.getOpcode() != ISD::UNDEF &&
10430           FoldOp.getOpcode() != ISD::Constant &&
10431           FoldOp.getOpcode() != ISD::ConstantFP)
10432         break;
10433       Ops.push_back(FoldOp);
10434       AddToWorkList(FoldOp.getNode());
10435     }
10436
10437     if (Ops.size() == LHS.getNumOperands())
10438       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10439                          LHS.getValueType(), &Ops[0], Ops.size());
10440   }
10441
10442   return SDValue();
10443 }
10444
10445 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10446 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10447   assert(N->getValueType(0).isVector() &&
10448          "SimplifyVUnaryOp only works on vectors!");
10449
10450   SDValue N0 = N->getOperand(0);
10451
10452   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10453     return SDValue();
10454
10455   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10456   SmallVector<SDValue, 8> Ops;
10457   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10458     SDValue Op = N0.getOperand(i);
10459     if (Op.getOpcode() != ISD::UNDEF &&
10460         Op.getOpcode() != ISD::ConstantFP)
10461       break;
10462     EVT EltVT = Op.getValueType();
10463     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10464     if (FoldOp.getOpcode() != ISD::UNDEF &&
10465         FoldOp.getOpcode() != ISD::ConstantFP)
10466       break;
10467     Ops.push_back(FoldOp);
10468     AddToWorkList(FoldOp.getNode());
10469   }
10470
10471   if (Ops.size() != N0.getNumOperands())
10472     return SDValue();
10473
10474   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10475                      N0.getValueType(), &Ops[0], Ops.size());
10476 }
10477
10478 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10479                                     SDValue N1, SDValue N2){
10480   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10481
10482   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10483                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10484
10485   // If we got a simplified select_cc node back from SimplifySelectCC, then
10486   // break it down into a new SETCC node, and a new SELECT node, and then return
10487   // the SELECT node, since we were called with a SELECT node.
10488   if (SCC.getNode()) {
10489     // Check to see if we got a select_cc back (to turn into setcc/select).
10490     // Otherwise, just return whatever node we got back, like fabs.
10491     if (SCC.getOpcode() == ISD::SELECT_CC) {
10492       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10493                                   N0.getValueType(),
10494                                   SCC.getOperand(0), SCC.getOperand(1),
10495                                   SCC.getOperand(4));
10496       AddToWorkList(SETCC.getNode());
10497       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10498                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10499     }
10500
10501     return SCC;
10502   }
10503   return SDValue();
10504 }
10505
10506 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10507 /// are the two values being selected between, see if we can simplify the
10508 /// select.  Callers of this should assume that TheSelect is deleted if this
10509 /// returns true.  As such, they should return the appropriate thing (e.g. the
10510 /// node) back to the top-level of the DAG combiner loop to avoid it being
10511 /// looked at.
10512 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10513                                     SDValue RHS) {
10514
10515   // Cannot simplify select with vector condition
10516   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10517
10518   // If this is a select from two identical things, try to pull the operation
10519   // through the select.
10520   if (LHS.getOpcode() != RHS.getOpcode() ||
10521       !LHS.hasOneUse() || !RHS.hasOneUse())
10522     return false;
10523
10524   // If this is a load and the token chain is identical, replace the select
10525   // of two loads with a load through a select of the address to load from.
10526   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10527   // constants have been dropped into the constant pool.
10528   if (LHS.getOpcode() == ISD::LOAD) {
10529     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10530     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10531
10532     // Token chains must be identical.
10533     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10534         // Do not let this transformation reduce the number of volatile loads.
10535         LLD->isVolatile() || RLD->isVolatile() ||
10536         // If this is an EXTLOAD, the VT's must match.
10537         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10538         // If this is an EXTLOAD, the kind of extension must match.
10539         (LLD->getExtensionType() != RLD->getExtensionType() &&
10540          // The only exception is if one of the extensions is anyext.
10541          LLD->getExtensionType() != ISD::EXTLOAD &&
10542          RLD->getExtensionType() != ISD::EXTLOAD) ||
10543         // FIXME: this discards src value information.  This is
10544         // over-conservative. It would be beneficial to be able to remember
10545         // both potential memory locations.  Since we are discarding
10546         // src value info, don't do the transformation if the memory
10547         // locations are not in the default address space.
10548         LLD->getPointerInfo().getAddrSpace() != 0 ||
10549         RLD->getPointerInfo().getAddrSpace() != 0 ||
10550         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10551                                       LLD->getBasePtr().getValueType()))
10552       return false;
10553
10554     // Check that the select condition doesn't reach either load.  If so,
10555     // folding this will induce a cycle into the DAG.  If not, this is safe to
10556     // xform, so create a select of the addresses.
10557     SDValue Addr;
10558     if (TheSelect->getOpcode() == ISD::SELECT) {
10559       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10560       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10561           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10562         return false;
10563       // The loads must not depend on one another.
10564       if (LLD->isPredecessorOf(RLD) ||
10565           RLD->isPredecessorOf(LLD))
10566         return false;
10567       Addr = DAG.getSelect(SDLoc(TheSelect),
10568                            LLD->getBasePtr().getValueType(),
10569                            TheSelect->getOperand(0), LLD->getBasePtr(),
10570                            RLD->getBasePtr());
10571     } else {  // Otherwise SELECT_CC
10572       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10573       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10574
10575       if ((LLD->hasAnyUseOfValue(1) &&
10576            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10577           (RLD->hasAnyUseOfValue(1) &&
10578            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10579         return false;
10580
10581       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10582                          LLD->getBasePtr().getValueType(),
10583                          TheSelect->getOperand(0),
10584                          TheSelect->getOperand(1),
10585                          LLD->getBasePtr(), RLD->getBasePtr(),
10586                          TheSelect->getOperand(4));
10587     }
10588
10589     SDValue Load;
10590     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10591       Load = DAG.getLoad(TheSelect->getValueType(0),
10592                          SDLoc(TheSelect),
10593                          // FIXME: Discards pointer and TBAA info.
10594                          LLD->getChain(), Addr, MachinePointerInfo(),
10595                          LLD->isVolatile(), LLD->isNonTemporal(),
10596                          LLD->isInvariant(), LLD->getAlignment());
10597     } else {
10598       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10599                             RLD->getExtensionType() : LLD->getExtensionType(),
10600                             SDLoc(TheSelect),
10601                             TheSelect->getValueType(0),
10602                             // FIXME: Discards pointer and TBAA info.
10603                             LLD->getChain(), Addr, MachinePointerInfo(),
10604                             LLD->getMemoryVT(), LLD->isVolatile(),
10605                             LLD->isNonTemporal(), LLD->getAlignment());
10606     }
10607
10608     // Users of the select now use the result of the load.
10609     CombineTo(TheSelect, Load);
10610
10611     // Users of the old loads now use the new load's chain.  We know the
10612     // old-load value is dead now.
10613     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10614     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10615     return true;
10616   }
10617
10618   return false;
10619 }
10620
10621 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10622 /// where 'cond' is the comparison specified by CC.
10623 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10624                                       SDValue N2, SDValue N3,
10625                                       ISD::CondCode CC, bool NotExtCompare) {
10626   // (x ? y : y) -> y.
10627   if (N2 == N3) return N2;
10628
10629   EVT VT = N2.getValueType();
10630   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10631   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10632   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10633
10634   // Determine if the condition we're dealing with is constant
10635   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10636                               N0, N1, CC, DL, false);
10637   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10638   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10639
10640   // fold select_cc true, x, y -> x
10641   if (SCCC && !SCCC->isNullValue())
10642     return N2;
10643   // fold select_cc false, x, y -> y
10644   if (SCCC && SCCC->isNullValue())
10645     return N3;
10646
10647   // Check to see if we can simplify the select into an fabs node
10648   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10649     // Allow either -0.0 or 0.0
10650     if (CFP->getValueAPF().isZero()) {
10651       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10652       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10653           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10654           N2 == N3.getOperand(0))
10655         return DAG.getNode(ISD::FABS, DL, VT, N0);
10656
10657       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10658       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10659           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10660           N2.getOperand(0) == N3)
10661         return DAG.getNode(ISD::FABS, DL, VT, N3);
10662     }
10663   }
10664
10665   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10666   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10667   // in it.  This is a win when the constant is not otherwise available because
10668   // it replaces two constant pool loads with one.  We only do this if the FP
10669   // type is known to be legal, because if it isn't, then we are before legalize
10670   // types an we want the other legalization to happen first (e.g. to avoid
10671   // messing with soft float) and if the ConstantFP is not legal, because if
10672   // it is legal, we may not need to store the FP constant in a constant pool.
10673   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10674     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10675       if (TLI.isTypeLegal(N2.getValueType()) &&
10676           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10677            TargetLowering::Legal) &&
10678           // If both constants have multiple uses, then we won't need to do an
10679           // extra load, they are likely around in registers for other users.
10680           (TV->hasOneUse() || FV->hasOneUse())) {
10681         Constant *Elts[] = {
10682           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10683           const_cast<ConstantFP*>(TV->getConstantFPValue())
10684         };
10685         Type *FPTy = Elts[0]->getType();
10686         const DataLayout &TD = *TLI.getDataLayout();
10687
10688         // Create a ConstantArray of the two constants.
10689         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10690         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10691                                             TD.getPrefTypeAlignment(FPTy));
10692         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10693
10694         // Get the offsets to the 0 and 1 element of the array so that we can
10695         // select between them.
10696         SDValue Zero = DAG.getIntPtrConstant(0);
10697         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10698         SDValue One = DAG.getIntPtrConstant(EltSize);
10699
10700         SDValue Cond = DAG.getSetCC(DL,
10701                                     getSetCCResultType(N0.getValueType()),
10702                                     N0, N1, CC);
10703         AddToWorkList(Cond.getNode());
10704         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10705                                           Cond, One, Zero);
10706         AddToWorkList(CstOffset.getNode());
10707         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10708                             CstOffset);
10709         AddToWorkList(CPIdx.getNode());
10710         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10711                            MachinePointerInfo::getConstantPool(), false,
10712                            false, false, Alignment);
10713
10714       }
10715     }
10716
10717   // Check to see if we can perform the "gzip trick", transforming
10718   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10719   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10720       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10721        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10722     EVT XType = N0.getValueType();
10723     EVT AType = N2.getValueType();
10724     if (XType.bitsGE(AType)) {
10725       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10726       // single-bit constant.
10727       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10728         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10729         ShCtV = XType.getSizeInBits()-ShCtV-1;
10730         SDValue ShCt = DAG.getConstant(ShCtV,
10731                                        getShiftAmountTy(N0.getValueType()));
10732         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10733                                     XType, N0, ShCt);
10734         AddToWorkList(Shift.getNode());
10735
10736         if (XType.bitsGT(AType)) {
10737           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10738           AddToWorkList(Shift.getNode());
10739         }
10740
10741         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10742       }
10743
10744       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10745                                   XType, N0,
10746                                   DAG.getConstant(XType.getSizeInBits()-1,
10747                                          getShiftAmountTy(N0.getValueType())));
10748       AddToWorkList(Shift.getNode());
10749
10750       if (XType.bitsGT(AType)) {
10751         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10752         AddToWorkList(Shift.getNode());
10753       }
10754
10755       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10756     }
10757   }
10758
10759   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10760   // where y is has a single bit set.
10761   // A plaintext description would be, we can turn the SELECT_CC into an AND
10762   // when the condition can be materialized as an all-ones register.  Any
10763   // single bit-test can be materialized as an all-ones register with
10764   // shift-left and shift-right-arith.
10765   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10766       N0->getValueType(0) == VT &&
10767       N1C && N1C->isNullValue() &&
10768       N2C && N2C->isNullValue()) {
10769     SDValue AndLHS = N0->getOperand(0);
10770     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10771     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10772       // Shift the tested bit over the sign bit.
10773       APInt AndMask = ConstAndRHS->getAPIntValue();
10774       SDValue ShlAmt =
10775         DAG.getConstant(AndMask.countLeadingZeros(),
10776                         getShiftAmountTy(AndLHS.getValueType()));
10777       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10778
10779       // Now arithmetic right shift it all the way over, so the result is either
10780       // all-ones, or zero.
10781       SDValue ShrAmt =
10782         DAG.getConstant(AndMask.getBitWidth()-1,
10783                         getShiftAmountTy(Shl.getValueType()));
10784       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10785
10786       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10787     }
10788   }
10789
10790   // fold select C, 16, 0 -> shl C, 4
10791   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10792     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10793       TargetLowering::ZeroOrOneBooleanContent) {
10794
10795     // If the caller doesn't want us to simplify this into a zext of a compare,
10796     // don't do it.
10797     if (NotExtCompare && N2C->getAPIntValue() == 1)
10798       return SDValue();
10799
10800     // Get a SetCC of the condition
10801     // NOTE: Don't create a SETCC if it's not legal on this target.
10802     if (!LegalOperations ||
10803         TLI.isOperationLegal(ISD::SETCC,
10804           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10805       SDValue Temp, SCC;
10806       // cast from setcc result type to select result type
10807       if (LegalTypes) {
10808         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10809                             N0, N1, CC);
10810         if (N2.getValueType().bitsLT(SCC.getValueType()))
10811           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10812                                         N2.getValueType());
10813         else
10814           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10815                              N2.getValueType(), SCC);
10816       } else {
10817         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10818         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10819                            N2.getValueType(), SCC);
10820       }
10821
10822       AddToWorkList(SCC.getNode());
10823       AddToWorkList(Temp.getNode());
10824
10825       if (N2C->getAPIntValue() == 1)
10826         return Temp;
10827
10828       // shl setcc result by log2 n2c
10829       return DAG.getNode(
10830           ISD::SHL, DL, N2.getValueType(), Temp,
10831           DAG.getConstant(N2C->getAPIntValue().logBase2(),
10832                           getShiftAmountTy(Temp.getValueType())));
10833     }
10834   }
10835
10836   // Check to see if this is the equivalent of setcc
10837   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10838   // otherwise, go ahead with the folds.
10839   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10840     EVT XType = N0.getValueType();
10841     if (!LegalOperations ||
10842         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10843       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10844       if (Res.getValueType() != VT)
10845         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10846       return Res;
10847     }
10848
10849     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10850     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10851         (!LegalOperations ||
10852          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10853       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10854       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10855                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10856                                        getShiftAmountTy(Ctlz.getValueType())));
10857     }
10858     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10859     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10860       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10861                                   XType, DAG.getConstant(0, XType), N0);
10862       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10863       return DAG.getNode(ISD::SRL, DL, XType,
10864                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10865                          DAG.getConstant(XType.getSizeInBits()-1,
10866                                          getShiftAmountTy(XType)));
10867     }
10868     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10869     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10870       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10871                                  DAG.getConstant(XType.getSizeInBits()-1,
10872                                          getShiftAmountTy(N0.getValueType())));
10873       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10874     }
10875   }
10876
10877   // Check to see if this is an integer abs.
10878   // select_cc setg[te] X,  0,  X, -X ->
10879   // select_cc setgt    X, -1,  X, -X ->
10880   // select_cc setl[te] X,  0, -X,  X ->
10881   // select_cc setlt    X,  1, -X,  X ->
10882   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10883   if (N1C) {
10884     ConstantSDNode *SubC = NULL;
10885     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10886          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10887         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10888       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10889     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10890               (N1C->isOne() && CC == ISD::SETLT)) &&
10891              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10892       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10893
10894     EVT XType = N0.getValueType();
10895     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10896       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10897                                   N0,
10898                                   DAG.getConstant(XType.getSizeInBits()-1,
10899                                          getShiftAmountTy(N0.getValueType())));
10900       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10901                                 XType, N0, Shift);
10902       AddToWorkList(Shift.getNode());
10903       AddToWorkList(Add.getNode());
10904       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10905     }
10906   }
10907
10908   return SDValue();
10909 }
10910
10911 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10912 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10913                                    SDValue N1, ISD::CondCode Cond,
10914                                    SDLoc DL, bool foldBooleans) {
10915   TargetLowering::DAGCombinerInfo
10916     DagCombineInfo(DAG, Level, false, this);
10917   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10918 }
10919
10920 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10921 /// return a DAG expression to select that will generate the same value by
10922 /// multiplying by a magic number.  See:
10923 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10924 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10925   std::vector<SDNode*> Built;
10926   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10927
10928   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10929        ii != ee; ++ii)
10930     AddToWorkList(*ii);
10931   return S;
10932 }
10933
10934 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10935 /// return a DAG expression to select that will generate the same value by
10936 /// multiplying by a magic number.  See:
10937 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10938 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10939   std::vector<SDNode*> Built;
10940   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10941
10942   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10943        ii != ee; ++ii)
10944     AddToWorkList(*ii);
10945   return S;
10946 }
10947
10948 /// FindBaseOffset - Return true if base is a frame index, which is known not
10949 // to alias with anything but itself.  Provides base object and offset as
10950 // results.
10951 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10952                            const GlobalValue *&GV, const void *&CV) {
10953   // Assume it is a primitive operation.
10954   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10955
10956   // If it's an adding a simple constant then integrate the offset.
10957   if (Base.getOpcode() == ISD::ADD) {
10958     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10959       Base = Base.getOperand(0);
10960       Offset += C->getZExtValue();
10961     }
10962   }
10963
10964   // Return the underlying GlobalValue, and update the Offset.  Return false
10965   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10966   // by multiple nodes with different offsets.
10967   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10968     GV = G->getGlobal();
10969     Offset += G->getOffset();
10970     return false;
10971   }
10972
10973   // Return the underlying Constant value, and update the Offset.  Return false
10974   // for ConstantSDNodes since the same constant pool entry may be represented
10975   // by multiple nodes with different offsets.
10976   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10977     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10978                                          : (const void *)C->getConstVal();
10979     Offset += C->getOffset();
10980     return false;
10981   }
10982   // If it's any of the following then it can't alias with anything but itself.
10983   return isa<FrameIndexSDNode>(Base);
10984 }
10985
10986 /// isAlias - Return true if there is any possibility that the two addresses
10987 /// overlap.
10988 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10989                           const Value *SrcValue1, int SrcValueOffset1,
10990                           unsigned SrcValueAlign1,
10991                           const MDNode *TBAAInfo1,
10992                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10993                           const Value *SrcValue2, int SrcValueOffset2,
10994                           unsigned SrcValueAlign2,
10995                           const MDNode *TBAAInfo2) const {
10996   // If they are the same then they must be aliases.
10997   if (Ptr1 == Ptr2) return true;
10998
10999   // If they are both volatile then they cannot be reordered.
11000   if (IsVolatile1 && IsVolatile2) return true;
11001
11002   // Gather base node and offset information.
11003   SDValue Base1, Base2;
11004   int64_t Offset1, Offset2;
11005   const GlobalValue *GV1, *GV2;
11006   const void *CV1, *CV2;
11007   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11008   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11009
11010   // If they have a same base address then check to see if they overlap.
11011   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11012     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11013
11014   // It is possible for different frame indices to alias each other, mostly
11015   // when tail call optimization reuses return address slots for arguments.
11016   // To catch this case, look up the actual index of frame indices to compute
11017   // the real alias relationship.
11018   if (isFrameIndex1 && isFrameIndex2) {
11019     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11020     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11021     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11022     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11023   }
11024
11025   // Otherwise, if we know what the bases are, and they aren't identical, then
11026   // we know they cannot alias.
11027   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11028     return false;
11029
11030   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11031   // compared to the size and offset of the access, we may be able to prove they
11032   // do not alias.  This check is conservative for now to catch cases created by
11033   // splitting vector types.
11034   if ((SrcValueAlign1 == SrcValueAlign2) &&
11035       (SrcValueOffset1 != SrcValueOffset2) &&
11036       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11037     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11038     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11039
11040     // There is no overlap between these relatively aligned accesses of similar
11041     // size, return no alias.
11042     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11043       return false;
11044   }
11045
11046   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11047     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11048   if (UseAA && SrcValue1 && SrcValue2) {
11049     // Use alias analysis information.
11050     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11051     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11052     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11053     AliasAnalysis::AliasResult AAResult =
11054       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11055                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
11056     if (AAResult == AliasAnalysis::NoAlias)
11057       return false;
11058   }
11059
11060   // Otherwise we have to assume they alias.
11061   return true;
11062 }
11063
11064 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11065   SDValue Ptr0, Ptr1;
11066   int64_t Size0, Size1;
11067   bool IsVolatile0, IsVolatile1;
11068   const Value *SrcValue0, *SrcValue1;
11069   int SrcValueOffset0, SrcValueOffset1;
11070   unsigned SrcValueAlign0, SrcValueAlign1;
11071   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11072   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11073                 SrcValueAlign0, SrcTBAAInfo0);
11074   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11075                 SrcValueAlign1, SrcTBAAInfo1);
11076   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11077                  SrcValueAlign0, SrcTBAAInfo0,
11078                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11079                  SrcValueAlign1, SrcTBAAInfo1);
11080 }
11081
11082 /// FindAliasInfo - Extracts the relevant alias information from the memory
11083 /// node.  Returns true if the operand was a nonvolatile load.
11084 bool DAGCombiner::FindAliasInfo(SDNode *N,
11085                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11086                                 const Value *&SrcValue,
11087                                 int &SrcValueOffset,
11088                                 unsigned &SrcValueAlign,
11089                                 const MDNode *&TBAAInfo) const {
11090   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11091
11092   Ptr = LS->getBasePtr();
11093   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11094   IsVolatile = LS->isVolatile();
11095   SrcValue = LS->getSrcValue();
11096   SrcValueOffset = LS->getSrcValueOffset();
11097   SrcValueAlign = LS->getOriginalAlignment();
11098   TBAAInfo = LS->getTBAAInfo();
11099   return isa<LoadSDNode>(LS) && !IsVolatile;
11100 }
11101
11102 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11103 /// looking for aliasing nodes and adding them to the Aliases vector.
11104 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11105                                    SmallVectorImpl<SDValue> &Aliases) {
11106   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11107   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11108
11109   // Get alias information for node.
11110   SDValue Ptr;
11111   int64_t Size;
11112   bool IsVolatile;
11113   const Value *SrcValue;
11114   int SrcValueOffset;
11115   unsigned SrcValueAlign;
11116   const MDNode *SrcTBAAInfo;
11117   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11118                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11119
11120   // Starting off.
11121   Chains.push_back(OriginalChain);
11122   unsigned Depth = 0;
11123
11124   // Look at each chain and determine if it is an alias.  If so, add it to the
11125   // aliases list.  If not, then continue up the chain looking for the next
11126   // candidate.
11127   while (!Chains.empty()) {
11128     SDValue Chain = Chains.back();
11129     Chains.pop_back();
11130
11131     // For TokenFactor nodes, look at each operand and only continue up the
11132     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11133     // find more and revert to original chain since the xform is unlikely to be
11134     // profitable.
11135     //
11136     // FIXME: The depth check could be made to return the last non-aliasing
11137     // chain we found before we hit a tokenfactor rather than the original
11138     // chain.
11139     if (Depth > 6 || Aliases.size() == 2) {
11140       Aliases.clear();
11141       Aliases.push_back(OriginalChain);
11142       break;
11143     }
11144
11145     // Don't bother if we've been before.
11146     if (!Visited.insert(Chain.getNode()))
11147       continue;
11148
11149     switch (Chain.getOpcode()) {
11150     case ISD::EntryToken:
11151       // Entry token is ideal chain operand, but handled in FindBetterChain.
11152       break;
11153
11154     case ISD::LOAD:
11155     case ISD::STORE: {
11156       // Get alias information for Chain.
11157       SDValue OpPtr;
11158       int64_t OpSize;
11159       bool OpIsVolatile;
11160       const Value *OpSrcValue;
11161       int OpSrcValueOffset;
11162       unsigned OpSrcValueAlign;
11163       const MDNode *OpSrcTBAAInfo;
11164       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11165                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11166                                     OpSrcValueAlign,
11167                                     OpSrcTBAAInfo);
11168
11169       // If chain is alias then stop here.
11170       if (!(IsLoad && IsOpLoad) &&
11171           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11172                   SrcValueAlign, SrcTBAAInfo,
11173                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11174                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11175         Aliases.push_back(Chain);
11176       } else {
11177         // Look further up the chain.
11178         Chains.push_back(Chain.getOperand(0));
11179         ++Depth;
11180       }
11181       break;
11182     }
11183
11184     case ISD::TokenFactor:
11185       // We have to check each of the operands of the token factor for "small"
11186       // token factors, so we queue them up.  Adding the operands to the queue
11187       // (stack) in reverse order maintains the original order and increases the
11188       // likelihood that getNode will find a matching token factor (CSE.)
11189       if (Chain.getNumOperands() > 16) {
11190         Aliases.push_back(Chain);
11191         break;
11192       }
11193       for (unsigned n = Chain.getNumOperands(); n;)
11194         Chains.push_back(Chain.getOperand(--n));
11195       ++Depth;
11196       break;
11197
11198     default:
11199       // For all other instructions we will just have to take what we can get.
11200       Aliases.push_back(Chain);
11201       break;
11202     }
11203   }
11204 }
11205
11206 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11207 /// for a better chain (aliasing node.)
11208 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11209   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11210
11211   // Accumulate all the aliases to this node.
11212   GatherAllAliases(N, OldChain, Aliases);
11213
11214   // If no operands then chain to entry token.
11215   if (Aliases.size() == 0)
11216     return DAG.getEntryNode();
11217
11218   // If a single operand then chain to it.  We don't need to revisit it.
11219   if (Aliases.size() == 1)
11220     return Aliases[0];
11221
11222   // Construct a custom tailored token factor.
11223   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11224                      &Aliases[0], Aliases.size());
11225 }
11226
11227 // SelectionDAG::Combine - This is the entry point for the file.
11228 //
11229 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11230                            CodeGenOpt::Level OptLevel) {
11231   /// run - This is the main entry point to this class.
11232   ///
11233   DAGCombiner(*this, AA, OptLevel).Run(Level);
11234 }