69e2ce198e0c8f4c75d4ef4c109ecbe73be57239
[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.isOperationLegalOrCustom(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       EVT N0VT = N0.getOperand(0).getValueType();
5086       if (getSetCCResultType(N0VT) == N0.getValueType())
5087         return SDValue();
5088
5089       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5090       // Only do this before legalize for now.
5091       EVT EltVT = VT.getVectorElementType();
5092       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5093                                     DAG.getConstant(1, EltVT));
5094       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5095         // We know that the # elements of the results is the same as the
5096         // # elements of the compare (and the # elements of the compare result
5097         // for that matter).  Check to see that they are the same size.  If so,
5098         // we know that the element size of the sext'd result matches the
5099         // element size of the compare operands.
5100         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5101                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5102                                          N0.getOperand(1),
5103                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5104                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5105                                        &OneOps[0], OneOps.size()));
5106
5107       // If the desired elements are smaller or larger than the source
5108       // elements we can use a matching integer vector type and then
5109       // truncate/sign extend
5110       EVT MatchingElementType =
5111         EVT::getIntegerVT(*DAG.getContext(),
5112                           N0VT.getScalarType().getSizeInBits());
5113       EVT MatchingVectorType =
5114         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5115                          N0VT.getVectorNumElements());
5116       SDValue VsetCC =
5117         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5118                       N0.getOperand(1),
5119                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5120       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5121                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5122                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5123                                      &OneOps[0], OneOps.size()));
5124     }
5125
5126     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5127     SDValue SCC =
5128       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5129                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5130                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5131     if (SCC.getNode()) return SCC;
5132   }
5133
5134   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5135   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5136       isa<ConstantSDNode>(N0.getOperand(1)) &&
5137       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5138       N0.hasOneUse()) {
5139     SDValue ShAmt = N0.getOperand(1);
5140     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5141     if (N0.getOpcode() == ISD::SHL) {
5142       SDValue InnerZExt = N0.getOperand(0);
5143       // If the original shl may be shifting out bits, do not perform this
5144       // transformation.
5145       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5146         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5147       if (ShAmtVal > KnownZeroBits)
5148         return SDValue();
5149     }
5150
5151     SDLoc DL(N);
5152
5153     // Ensure that the shift amount is wide enough for the shifted value.
5154     if (VT.getSizeInBits() >= 256)
5155       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5156
5157     return DAG.getNode(N0.getOpcode(), DL, VT,
5158                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5159                        ShAmt);
5160   }
5161
5162   return SDValue();
5163 }
5164
5165 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5166   SDValue N0 = N->getOperand(0);
5167   EVT VT = N->getValueType(0);
5168
5169   // fold (aext c1) -> c1
5170   if (isa<ConstantSDNode>(N0))
5171     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5172   // fold (aext (aext x)) -> (aext x)
5173   // fold (aext (zext x)) -> (zext x)
5174   // fold (aext (sext x)) -> (sext x)
5175   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5176       N0.getOpcode() == ISD::ZERO_EXTEND ||
5177       N0.getOpcode() == ISD::SIGN_EXTEND)
5178     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5179
5180   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5181   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5182   if (N0.getOpcode() == ISD::TRUNCATE) {
5183     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5184     if (NarrowLoad.getNode()) {
5185       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5186       if (NarrowLoad.getNode() != N0.getNode()) {
5187         CombineTo(N0.getNode(), NarrowLoad);
5188         // CombineTo deleted the truncate, if needed, but not what's under it.
5189         AddToWorkList(oye);
5190       }
5191       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5192     }
5193   }
5194
5195   // fold (aext (truncate x))
5196   if (N0.getOpcode() == ISD::TRUNCATE) {
5197     SDValue TruncOp = N0.getOperand(0);
5198     if (TruncOp.getValueType() == VT)
5199       return TruncOp; // x iff x size == zext size.
5200     if (TruncOp.getValueType().bitsGT(VT))
5201       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5202     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5203   }
5204
5205   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5206   // if the trunc is not free.
5207   if (N0.getOpcode() == ISD::AND &&
5208       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5209       N0.getOperand(1).getOpcode() == ISD::Constant &&
5210       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5211                           N0.getValueType())) {
5212     SDValue X = N0.getOperand(0).getOperand(0);
5213     if (X.getValueType().bitsLT(VT)) {
5214       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5215     } else if (X.getValueType().bitsGT(VT)) {
5216       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5217     }
5218     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5219     Mask = Mask.zext(VT.getSizeInBits());
5220     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5221                        X, DAG.getConstant(Mask, VT));
5222   }
5223
5224   // fold (aext (load x)) -> (aext (truncate (extload x)))
5225   // None of the supported targets knows how to perform load and any_ext
5226   // on vectors in one instruction.  We only perform this transformation on
5227   // scalars.
5228   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5229       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5230        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5231     bool DoXform = true;
5232     SmallVector<SDNode*, 4> SetCCs;
5233     if (!N0.hasOneUse())
5234       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5235     if (DoXform) {
5236       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5237       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5238                                        LN0->getChain(),
5239                                        LN0->getBasePtr(), N0.getValueType(),
5240                                        LN0->getMemOperand());
5241       CombineTo(N, ExtLoad);
5242       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5243                                   N0.getValueType(), ExtLoad);
5244       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5245       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5246                       ISD::ANY_EXTEND);
5247       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5248     }
5249   }
5250
5251   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5252   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5253   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5254   if (N0.getOpcode() == ISD::LOAD &&
5255       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5256       N0.hasOneUse()) {
5257     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5258     EVT MemVT = LN0->getMemoryVT();
5259     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5260                                      VT, LN0->getChain(), LN0->getBasePtr(),
5261                                      MemVT, LN0->getMemOperand());
5262     CombineTo(N, ExtLoad);
5263     CombineTo(N0.getNode(),
5264               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5265                           N0.getValueType(), ExtLoad),
5266               ExtLoad.getValue(1));
5267     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5268   }
5269
5270   if (N0.getOpcode() == ISD::SETCC) {
5271     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5272     // Only do this before legalize for now.
5273     if (VT.isVector() && !LegalOperations) {
5274       EVT N0VT = N0.getOperand(0).getValueType();
5275         // We know that the # elements of the results is the same as the
5276         // # elements of the compare (and the # elements of the compare result
5277         // for that matter).  Check to see that they are the same size.  If so,
5278         // we know that the element size of the sext'd result matches the
5279         // element size of the compare operands.
5280       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5281         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5282                              N0.getOperand(1),
5283                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5284       // If the desired elements are smaller or larger than the source
5285       // elements we can use a matching integer vector type and then
5286       // truncate/sign extend
5287       else {
5288         EVT MatchingElementType =
5289           EVT::getIntegerVT(*DAG.getContext(),
5290                             N0VT.getScalarType().getSizeInBits());
5291         EVT MatchingVectorType =
5292           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5293                            N0VT.getVectorNumElements());
5294         SDValue VsetCC =
5295           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5296                         N0.getOperand(1),
5297                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5298         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5299       }
5300     }
5301
5302     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5303     SDValue SCC =
5304       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5305                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5306                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5307     if (SCC.getNode())
5308       return SCC;
5309   }
5310
5311   return SDValue();
5312 }
5313
5314 /// GetDemandedBits - See if the specified operand can be simplified with the
5315 /// knowledge that only the bits specified by Mask are used.  If so, return the
5316 /// simpler operand, otherwise return a null SDValue.
5317 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5318   switch (V.getOpcode()) {
5319   default: break;
5320   case ISD::Constant: {
5321     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5322     assert(CV != 0 && "Const value should be ConstSDNode.");
5323     const APInt &CVal = CV->getAPIntValue();
5324     APInt NewVal = CVal & Mask;
5325     if (NewVal != CVal)
5326       return DAG.getConstant(NewVal, V.getValueType());
5327     break;
5328   }
5329   case ISD::OR:
5330   case ISD::XOR:
5331     // If the LHS or RHS don't contribute bits to the or, drop them.
5332     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5333       return V.getOperand(1);
5334     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5335       return V.getOperand(0);
5336     break;
5337   case ISD::SRL:
5338     // Only look at single-use SRLs.
5339     if (!V.getNode()->hasOneUse())
5340       break;
5341     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5342       // See if we can recursively simplify the LHS.
5343       unsigned Amt = RHSC->getZExtValue();
5344
5345       // Watch out for shift count overflow though.
5346       if (Amt >= Mask.getBitWidth()) break;
5347       APInt NewMask = Mask << Amt;
5348       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5349       if (SimplifyLHS.getNode())
5350         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5351                            SimplifyLHS, V.getOperand(1));
5352     }
5353   }
5354   return SDValue();
5355 }
5356
5357 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5358 /// bits and then truncated to a narrower type and where N is a multiple
5359 /// of number of bits of the narrower type, transform it to a narrower load
5360 /// from address + N / num of bits of new type. If the result is to be
5361 /// extended, also fold the extension to form a extending load.
5362 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5363   unsigned Opc = N->getOpcode();
5364
5365   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5366   SDValue N0 = N->getOperand(0);
5367   EVT VT = N->getValueType(0);
5368   EVT ExtVT = VT;
5369
5370   // This transformation isn't valid for vector loads.
5371   if (VT.isVector())
5372     return SDValue();
5373
5374   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5375   // extended to VT.
5376   if (Opc == ISD::SIGN_EXTEND_INREG) {
5377     ExtType = ISD::SEXTLOAD;
5378     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5379   } else if (Opc == ISD::SRL) {
5380     // Another special-case: SRL is basically zero-extending a narrower value.
5381     ExtType = ISD::ZEXTLOAD;
5382     N0 = SDValue(N, 0);
5383     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5384     if (!N01) return SDValue();
5385     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5386                               VT.getSizeInBits() - N01->getZExtValue());
5387   }
5388   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5389     return SDValue();
5390
5391   unsigned EVTBits = ExtVT.getSizeInBits();
5392
5393   // Do not generate loads of non-round integer types since these can
5394   // be expensive (and would be wrong if the type is not byte sized).
5395   if (!ExtVT.isRound())
5396     return SDValue();
5397
5398   unsigned ShAmt = 0;
5399   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5400     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5401       ShAmt = N01->getZExtValue();
5402       // Is the shift amount a multiple of size of VT?
5403       if ((ShAmt & (EVTBits-1)) == 0) {
5404         N0 = N0.getOperand(0);
5405         // Is the load width a multiple of size of VT?
5406         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5407           return SDValue();
5408       }
5409
5410       // At this point, we must have a load or else we can't do the transform.
5411       if (!isa<LoadSDNode>(N0)) return SDValue();
5412
5413       // Because a SRL must be assumed to *need* to zero-extend the high bits
5414       // (as opposed to anyext the high bits), we can't combine the zextload
5415       // lowering of SRL and an sextload.
5416       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5417         return SDValue();
5418
5419       // If the shift amount is larger than the input type then we're not
5420       // accessing any of the loaded bytes.  If the load was a zextload/extload
5421       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5422       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5423         return SDValue();
5424     }
5425   }
5426
5427   // If the load is shifted left (and the result isn't shifted back right),
5428   // we can fold the truncate through the shift.
5429   unsigned ShLeftAmt = 0;
5430   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5431       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5432     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5433       ShLeftAmt = N01->getZExtValue();
5434       N0 = N0.getOperand(0);
5435     }
5436   }
5437
5438   // If we haven't found a load, we can't narrow it.  Don't transform one with
5439   // multiple uses, this would require adding a new load.
5440   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5441     return SDValue();
5442
5443   // Don't change the width of a volatile load.
5444   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445   if (LN0->isVolatile())
5446     return SDValue();
5447
5448   // Verify that we are actually reducing a load width here.
5449   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5450     return SDValue();
5451
5452   // For the transform to be legal, the load must produce only two values
5453   // (the value loaded and the chain).  Don't transform a pre-increment
5454   // load, for example, which produces an extra value.  Otherwise the
5455   // transformation is not equivalent, and the downstream logic to replace
5456   // uses gets things wrong.
5457   if (LN0->getNumValues() > 2)
5458     return SDValue();
5459
5460   // If the load that we're shrinking is an extload and we're not just
5461   // discarding the extension we can't simply shrink the load. Bail.
5462   // TODO: It would be possible to merge the extensions in some cases.
5463   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5464       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5465     return SDValue();
5466
5467   EVT PtrType = N0.getOperand(1).getValueType();
5468
5469   if (PtrType == MVT::Untyped || PtrType.isExtended())
5470     // It's not possible to generate a constant of extended or untyped type.
5471     return SDValue();
5472
5473   // For big endian targets, we need to adjust the offset to the pointer to
5474   // load the correct bytes.
5475   if (TLI.isBigEndian()) {
5476     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5477     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5478     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5479   }
5480
5481   uint64_t PtrOff = ShAmt / 8;
5482   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5483   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5484                                PtrType, LN0->getBasePtr(),
5485                                DAG.getConstant(PtrOff, PtrType));
5486   AddToWorkList(NewPtr.getNode());
5487
5488   SDValue Load;
5489   if (ExtType == ISD::NON_EXTLOAD)
5490     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5491                         LN0->getPointerInfo().getWithOffset(PtrOff),
5492                         LN0->isVolatile(), LN0->isNonTemporal(),
5493                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5494   else
5495     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5496                           LN0->getPointerInfo().getWithOffset(PtrOff),
5497                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5498                           NewAlign, LN0->getTBAAInfo());
5499
5500   // Replace the old load's chain with the new load's chain.
5501   WorkListRemover DeadNodes(*this);
5502   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5503
5504   // Shift the result left, if we've swallowed a left shift.
5505   SDValue Result = Load;
5506   if (ShLeftAmt != 0) {
5507     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5508     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5509       ShImmTy = VT;
5510     // If the shift amount is as large as the result size (but, presumably,
5511     // no larger than the source) then the useful bits of the result are
5512     // zero; we can't simply return the shortened shift, because the result
5513     // of that operation is undefined.
5514     if (ShLeftAmt >= VT.getSizeInBits())
5515       Result = DAG.getConstant(0, VT);
5516     else
5517       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5518                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5519   }
5520
5521   // Return the new loaded value.
5522   return Result;
5523 }
5524
5525 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5526   SDValue N0 = N->getOperand(0);
5527   SDValue N1 = N->getOperand(1);
5528   EVT VT = N->getValueType(0);
5529   EVT EVT = cast<VTSDNode>(N1)->getVT();
5530   unsigned VTBits = VT.getScalarType().getSizeInBits();
5531   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5532
5533   // fold (sext_in_reg c1) -> c1
5534   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5535     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5536
5537   // If the input is already sign extended, just drop the extension.
5538   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5539     return N0;
5540
5541   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5542   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5543       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5544     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5545                        N0.getOperand(0), N1);
5546
5547   // fold (sext_in_reg (sext x)) -> (sext x)
5548   // fold (sext_in_reg (aext x)) -> (sext x)
5549   // if x is small enough.
5550   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5551     SDValue N00 = N0.getOperand(0);
5552     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5553         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5554       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5555   }
5556
5557   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5558   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5559     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5560
5561   // fold operands of sext_in_reg based on knowledge that the top bits are not
5562   // demanded.
5563   if (SimplifyDemandedBits(SDValue(N, 0)))
5564     return SDValue(N, 0);
5565
5566   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5567   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5568   SDValue NarrowLoad = ReduceLoadWidth(N);
5569   if (NarrowLoad.getNode())
5570     return NarrowLoad;
5571
5572   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5573   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5574   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5575   if (N0.getOpcode() == ISD::SRL) {
5576     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5577       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5578         // We can turn this into an SRA iff the input to the SRL is already sign
5579         // extended enough.
5580         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5581         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5582           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5583                              N0.getOperand(0), N0.getOperand(1));
5584       }
5585   }
5586
5587   // fold (sext_inreg (extload x)) -> (sextload x)
5588   if (ISD::isEXTLoad(N0.getNode()) &&
5589       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5590       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5591       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5592        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5593     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5594     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5595                                      LN0->getChain(),
5596                                      LN0->getBasePtr(), EVT,
5597                                      LN0->getMemOperand());
5598     CombineTo(N, ExtLoad);
5599     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5600     AddToWorkList(ExtLoad.getNode());
5601     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5602   }
5603   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5604   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5605       N0.hasOneUse() &&
5606       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5607       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5608        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5609     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5610     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5611                                      LN0->getChain(),
5612                                      LN0->getBasePtr(), EVT,
5613                                      LN0->getMemOperand());
5614     CombineTo(N, ExtLoad);
5615     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5616     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5617   }
5618
5619   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5620   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5621     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5622                                        N0.getOperand(1), false);
5623     if (BSwap.getNode() != 0)
5624       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5625                          BSwap, N1);
5626   }
5627
5628   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5629   // into a build_vector.
5630   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5631     SmallVector<SDValue, 8> Elts;
5632     unsigned NumElts = N0->getNumOperands();
5633     unsigned ShAmt = VTBits - EVTBits;
5634
5635     for (unsigned i = 0; i != NumElts; ++i) {
5636       SDValue Op = N0->getOperand(i);
5637       if (Op->getOpcode() == ISD::UNDEF) {
5638         Elts.push_back(Op);
5639         continue;
5640       }
5641
5642       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5643       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5644       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5645                                      Op.getValueType()));
5646     }
5647
5648     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5649   }
5650
5651   return SDValue();
5652 }
5653
5654 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5655   SDValue N0 = N->getOperand(0);
5656   EVT VT = N->getValueType(0);
5657   bool isLE = TLI.isLittleEndian();
5658
5659   // noop truncate
5660   if (N0.getValueType() == N->getValueType(0))
5661     return N0;
5662   // fold (truncate c1) -> c1
5663   if (isa<ConstantSDNode>(N0))
5664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5665   // fold (truncate (truncate x)) -> (truncate x)
5666   if (N0.getOpcode() == ISD::TRUNCATE)
5667     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5668   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5669   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5670       N0.getOpcode() == ISD::SIGN_EXTEND ||
5671       N0.getOpcode() == ISD::ANY_EXTEND) {
5672     if (N0.getOperand(0).getValueType().bitsLT(VT))
5673       // if the source is smaller than the dest, we still need an extend
5674       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5675                          N0.getOperand(0));
5676     if (N0.getOperand(0).getValueType().bitsGT(VT))
5677       // if the source is larger than the dest, than we just need the truncate
5678       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5679     // if the source and dest are the same type, we can drop both the extend
5680     // and the truncate.
5681     return N0.getOperand(0);
5682   }
5683
5684   // Fold extract-and-trunc into a narrow extract. For example:
5685   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5686   //   i32 y = TRUNCATE(i64 x)
5687   //        -- becomes --
5688   //   v16i8 b = BITCAST (v2i64 val)
5689   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5690   //
5691   // Note: We only run this optimization after type legalization (which often
5692   // creates this pattern) and before operation legalization after which
5693   // we need to be more careful about the vector instructions that we generate.
5694   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5695       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5696
5697     EVT VecTy = N0.getOperand(0).getValueType();
5698     EVT ExTy = N0.getValueType();
5699     EVT TrTy = N->getValueType(0);
5700
5701     unsigned NumElem = VecTy.getVectorNumElements();
5702     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5703
5704     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5705     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5706
5707     SDValue EltNo = N0->getOperand(1);
5708     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5709       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5710       EVT IndexTy = TLI.getVectorIdxTy();
5711       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5712
5713       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5714                               NVT, N0.getOperand(0));
5715
5716       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5717                          SDLoc(N), TrTy, V,
5718                          DAG.getConstant(Index, IndexTy));
5719     }
5720   }
5721
5722   // Fold a series of buildvector, bitcast, and truncate if possible.
5723   // For example fold
5724   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5725   //   (2xi32 (buildvector x, y)).
5726   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5727       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5728       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5729       N0.getOperand(0).hasOneUse()) {
5730
5731     SDValue BuildVect = N0.getOperand(0);
5732     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5733     EVT TruncVecEltTy = VT.getVectorElementType();
5734
5735     // Check that the element types match.
5736     if (BuildVectEltTy == TruncVecEltTy) {
5737       // Now we only need to compute the offset of the truncated elements.
5738       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5739       unsigned TruncVecNumElts = VT.getVectorNumElements();
5740       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5741
5742       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5743              "Invalid number of elements");
5744
5745       SmallVector<SDValue, 8> Opnds;
5746       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5747         Opnds.push_back(BuildVect.getOperand(i));
5748
5749       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5750                          Opnds.size());
5751     }
5752   }
5753
5754   // See if we can simplify the input to this truncate through knowledge that
5755   // only the low bits are being used.
5756   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5757   // Currently we only perform this optimization on scalars because vectors
5758   // may have different active low bits.
5759   if (!VT.isVector()) {
5760     SDValue Shorter =
5761       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5762                                                VT.getSizeInBits()));
5763     if (Shorter.getNode())
5764       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5765   }
5766   // fold (truncate (load x)) -> (smaller load x)
5767   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5768   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5769     SDValue Reduced = ReduceLoadWidth(N);
5770     if (Reduced.getNode())
5771       return Reduced;
5772     // Handle the case where the load remains an extending load even
5773     // after truncation.
5774     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5775       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5776       if (!LN0->isVolatile() &&
5777           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5778         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5779                                          VT, LN0->getChain(), LN0->getBasePtr(),
5780                                          LN0->getMemoryVT(),
5781                                          LN0->getMemOperand());
5782         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5783         return NewLoad;
5784       }
5785     }
5786   }
5787   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5788   // where ... are all 'undef'.
5789   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5790     SmallVector<EVT, 8> VTs;
5791     SDValue V;
5792     unsigned Idx = 0;
5793     unsigned NumDefs = 0;
5794
5795     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5796       SDValue X = N0.getOperand(i);
5797       if (X.getOpcode() != ISD::UNDEF) {
5798         V = X;
5799         Idx = i;
5800         NumDefs++;
5801       }
5802       // Stop if more than one members are non-undef.
5803       if (NumDefs > 1)
5804         break;
5805       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5806                                      VT.getVectorElementType(),
5807                                      X.getValueType().getVectorNumElements()));
5808     }
5809
5810     if (NumDefs == 0)
5811       return DAG.getUNDEF(VT);
5812
5813     if (NumDefs == 1) {
5814       assert(V.getNode() && "The single defined operand is empty!");
5815       SmallVector<SDValue, 8> Opnds;
5816       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5817         if (i != Idx) {
5818           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5819           continue;
5820         }
5821         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5822         AddToWorkList(NV.getNode());
5823         Opnds.push_back(NV);
5824       }
5825       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5826                          &Opnds[0], Opnds.size());
5827     }
5828   }
5829
5830   // Simplify the operands using demanded-bits information.
5831   if (!VT.isVector() &&
5832       SimplifyDemandedBits(SDValue(N, 0)))
5833     return SDValue(N, 0);
5834
5835   return SDValue();
5836 }
5837
5838 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5839   SDValue Elt = N->getOperand(i);
5840   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5841     return Elt.getNode();
5842   return Elt.getOperand(Elt.getResNo()).getNode();
5843 }
5844
5845 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5846 /// if load locations are consecutive.
5847 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5848   assert(N->getOpcode() == ISD::BUILD_PAIR);
5849
5850   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5851   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5852   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5853       LD1->getPointerInfo().getAddrSpace() !=
5854          LD2->getPointerInfo().getAddrSpace())
5855     return SDValue();
5856   EVT LD1VT = LD1->getValueType(0);
5857
5858   if (ISD::isNON_EXTLoad(LD2) &&
5859       LD2->hasOneUse() &&
5860       // If both are volatile this would reduce the number of volatile loads.
5861       // If one is volatile it might be ok, but play conservative and bail out.
5862       !LD1->isVolatile() &&
5863       !LD2->isVolatile() &&
5864       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5865     unsigned Align = LD1->getAlignment();
5866     unsigned NewAlign = TLI.getDataLayout()->
5867       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5868
5869     if (NewAlign <= Align &&
5870         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5871       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5872                          LD1->getBasePtr(), LD1->getPointerInfo(),
5873                          false, false, false, Align);
5874   }
5875
5876   return SDValue();
5877 }
5878
5879 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5880   SDValue N0 = N->getOperand(0);
5881   EVT VT = N->getValueType(0);
5882
5883   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5884   // Only do this before legalize, since afterward the target may be depending
5885   // on the bitconvert.
5886   // First check to see if this is all constant.
5887   if (!LegalTypes &&
5888       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5889       VT.isVector()) {
5890     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5891
5892     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5893     assert(!DestEltVT.isVector() &&
5894            "Element type of vector ValueType must not be vector!");
5895     if (isSimple)
5896       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5897   }
5898
5899   // If the input is a constant, let getNode fold it.
5900   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5901     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5902     if (Res.getNode() != N) {
5903       if (!LegalOperations ||
5904           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5905         return Res;
5906
5907       // Folding it resulted in an illegal node, and it's too late to
5908       // do that. Clean up the old node and forego the transformation.
5909       // Ideally this won't happen very often, because instcombine
5910       // and the earlier dagcombine runs (where illegal nodes are
5911       // permitted) should have folded most of them already.
5912       DAG.DeleteNode(Res.getNode());
5913     }
5914   }
5915
5916   // (conv (conv x, t1), t2) -> (conv x, t2)
5917   if (N0.getOpcode() == ISD::BITCAST)
5918     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5919                        N0.getOperand(0));
5920
5921   // fold (conv (load x)) -> (load (conv*)x)
5922   // If the resultant load doesn't need a higher alignment than the original!
5923   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5924       // Do not change the width of a volatile load.
5925       !cast<LoadSDNode>(N0)->isVolatile() &&
5926       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5927       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5928     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5929     unsigned Align = TLI.getDataLayout()->
5930       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5931     unsigned OrigAlign = LN0->getAlignment();
5932
5933     if (Align <= OrigAlign) {
5934       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5935                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5936                                  LN0->isVolatile(), LN0->isNonTemporal(),
5937                                  LN0->isInvariant(), OrigAlign,
5938                                  LN0->getTBAAInfo());
5939       AddToWorkList(N);
5940       CombineTo(N0.getNode(),
5941                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5942                             N0.getValueType(), Load),
5943                 Load.getValue(1));
5944       return Load;
5945     }
5946   }
5947
5948   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5949   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5950   // This often reduces constant pool loads.
5951   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5952        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5953       N0.getNode()->hasOneUse() && VT.isInteger() &&
5954       !VT.isVector() && !N0.getValueType().isVector()) {
5955     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5956                                   N0.getOperand(0));
5957     AddToWorkList(NewConv.getNode());
5958
5959     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5960     if (N0.getOpcode() == ISD::FNEG)
5961       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5962                          NewConv, DAG.getConstant(SignBit, VT));
5963     assert(N0.getOpcode() == ISD::FABS);
5964     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5965                        NewConv, DAG.getConstant(~SignBit, VT));
5966   }
5967
5968   // fold (bitconvert (fcopysign cst, x)) ->
5969   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5970   // Note that we don't handle (copysign x, cst) because this can always be
5971   // folded to an fneg or fabs.
5972   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5973       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5974       VT.isInteger() && !VT.isVector()) {
5975     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5976     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5977     if (isTypeLegal(IntXVT)) {
5978       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5979                               IntXVT, N0.getOperand(1));
5980       AddToWorkList(X.getNode());
5981
5982       // If X has a different width than the result/lhs, sext it or truncate it.
5983       unsigned VTWidth = VT.getSizeInBits();
5984       if (OrigXWidth < VTWidth) {
5985         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5986         AddToWorkList(X.getNode());
5987       } else if (OrigXWidth > VTWidth) {
5988         // To get the sign bit in the right place, we have to shift it right
5989         // before truncating.
5990         X = DAG.getNode(ISD::SRL, SDLoc(X),
5991                         X.getValueType(), X,
5992                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5993         AddToWorkList(X.getNode());
5994         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5995         AddToWorkList(X.getNode());
5996       }
5997
5998       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5999       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6000                       X, DAG.getConstant(SignBit, VT));
6001       AddToWorkList(X.getNode());
6002
6003       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6004                                 VT, N0.getOperand(0));
6005       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6006                         Cst, DAG.getConstant(~SignBit, VT));
6007       AddToWorkList(Cst.getNode());
6008
6009       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6010     }
6011   }
6012
6013   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6014   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6015     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6016     if (CombineLD.getNode())
6017       return CombineLD;
6018   }
6019
6020   return SDValue();
6021 }
6022
6023 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6024   EVT VT = N->getValueType(0);
6025   return CombineConsecutiveLoads(N, VT);
6026 }
6027
6028 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6029 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6030 /// destination element value type.
6031 SDValue DAGCombiner::
6032 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6033   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6034
6035   // If this is already the right type, we're done.
6036   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6037
6038   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6039   unsigned DstBitSize = DstEltVT.getSizeInBits();
6040
6041   // If this is a conversion of N elements of one type to N elements of another
6042   // type, convert each element.  This handles FP<->INT cases.
6043   if (SrcBitSize == DstBitSize) {
6044     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6045                               BV->getValueType(0).getVectorNumElements());
6046
6047     // Due to the FP element handling below calling this routine recursively,
6048     // we can end up with a scalar-to-vector node here.
6049     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6050       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6051                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6052                                      DstEltVT, BV->getOperand(0)));
6053
6054     SmallVector<SDValue, 8> Ops;
6055     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6056       SDValue Op = BV->getOperand(i);
6057       // If the vector element type is not legal, the BUILD_VECTOR operands
6058       // are promoted and implicitly truncated.  Make that explicit here.
6059       if (Op.getValueType() != SrcEltVT)
6060         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6061       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6062                                 DstEltVT, Op));
6063       AddToWorkList(Ops.back().getNode());
6064     }
6065     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6066                        &Ops[0], Ops.size());
6067   }
6068
6069   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6070   // handle annoying details of growing/shrinking FP values, we convert them to
6071   // int first.
6072   if (SrcEltVT.isFloatingPoint()) {
6073     // Convert the input float vector to a int vector where the elements are the
6074     // same sizes.
6075     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6076     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6077     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6078     SrcEltVT = IntVT;
6079   }
6080
6081   // Now we know the input is an integer vector.  If the output is a FP type,
6082   // convert to integer first, then to FP of the right size.
6083   if (DstEltVT.isFloatingPoint()) {
6084     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6085     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6086     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6087
6088     // Next, convert to FP elements of the same size.
6089     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6090   }
6091
6092   // Okay, we know the src/dst types are both integers of differing types.
6093   // Handling growing first.
6094   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6095   if (SrcBitSize < DstBitSize) {
6096     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6097
6098     SmallVector<SDValue, 8> Ops;
6099     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6100          i += NumInputsPerOutput) {
6101       bool isLE = TLI.isLittleEndian();
6102       APInt NewBits = APInt(DstBitSize, 0);
6103       bool EltIsUndef = true;
6104       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6105         // Shift the previously computed bits over.
6106         NewBits <<= SrcBitSize;
6107         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6108         if (Op.getOpcode() == ISD::UNDEF) continue;
6109         EltIsUndef = false;
6110
6111         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6112                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6113       }
6114
6115       if (EltIsUndef)
6116         Ops.push_back(DAG.getUNDEF(DstEltVT));
6117       else
6118         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6119     }
6120
6121     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6122     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6123                        &Ops[0], Ops.size());
6124   }
6125
6126   // Finally, this must be the case where we are shrinking elements: each input
6127   // turns into multiple outputs.
6128   bool isS2V = ISD::isScalarToVector(BV);
6129   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6130   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6131                             NumOutputsPerInput*BV->getNumOperands());
6132   SmallVector<SDValue, 8> Ops;
6133
6134   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6135     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6136       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6137         Ops.push_back(DAG.getUNDEF(DstEltVT));
6138       continue;
6139     }
6140
6141     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6142                   getAPIntValue().zextOrTrunc(SrcBitSize);
6143
6144     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6145       APInt ThisVal = OpVal.trunc(DstBitSize);
6146       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6147       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6148         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6149         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6150                            Ops[0]);
6151       OpVal = OpVal.lshr(DstBitSize);
6152     }
6153
6154     // For big endian targets, swap the order of the pieces of each element.
6155     if (TLI.isBigEndian())
6156       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6157   }
6158
6159   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6160                      &Ops[0], Ops.size());
6161 }
6162
6163 SDValue DAGCombiner::visitFADD(SDNode *N) {
6164   SDValue N0 = N->getOperand(0);
6165   SDValue N1 = N->getOperand(1);
6166   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6167   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6168   EVT VT = N->getValueType(0);
6169
6170   // fold vector ops
6171   if (VT.isVector()) {
6172     SDValue FoldedVOp = SimplifyVBinOp(N);
6173     if (FoldedVOp.getNode()) return FoldedVOp;
6174   }
6175
6176   // fold (fadd c1, c2) -> c1 + c2
6177   if (N0CFP && N1CFP)
6178     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6179   // canonicalize constant to RHS
6180   if (N0CFP && !N1CFP)
6181     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6182   // fold (fadd A, 0) -> A
6183   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6184       N1CFP->getValueAPF().isZero())
6185     return N0;
6186   // fold (fadd A, (fneg B)) -> (fsub A, B)
6187   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6188     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6189     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6190                        GetNegatedExpression(N1, DAG, LegalOperations));
6191   // fold (fadd (fneg A), B) -> (fsub B, A)
6192   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6193     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6194     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6195                        GetNegatedExpression(N0, DAG, LegalOperations));
6196
6197   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6198   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6199       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6200       isa<ConstantFPSDNode>(N0.getOperand(1)))
6201     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6202                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6203                                    N0.getOperand(1), N1));
6204
6205   // No FP constant should be created after legalization as Instruction
6206   // Selection pass has hard time in dealing with FP constant.
6207   //
6208   // We don't need test this condition for transformation like following, as
6209   // the DAG being transformed implies it is legal to take FP constant as
6210   // operand.
6211   //
6212   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6213   //
6214   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6215
6216   // If allow, fold (fadd (fneg x), x) -> 0.0
6217   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6218       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6219     return DAG.getConstantFP(0.0, VT);
6220
6221     // If allow, fold (fadd x, (fneg x)) -> 0.0
6222   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6223       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6224     return DAG.getConstantFP(0.0, VT);
6225
6226   // In unsafe math mode, we can fold chains of FADD's of the same value
6227   // into multiplications.  This transform is not safe in general because
6228   // we are reducing the number of rounding steps.
6229   if (DAG.getTarget().Options.UnsafeFPMath &&
6230       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6231       !N0CFP && !N1CFP) {
6232     if (N0.getOpcode() == ISD::FMUL) {
6233       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6234       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6235
6236       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6237       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6238         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6239                                      SDValue(CFP00, 0),
6240                                      DAG.getConstantFP(1.0, VT));
6241         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6242                            N1, NewCFP);
6243       }
6244
6245       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6246       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6247         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6248                                      SDValue(CFP01, 0),
6249                                      DAG.getConstantFP(1.0, VT));
6250         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6251                            N1, NewCFP);
6252       }
6253
6254       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6255       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6256           N1.getOperand(0) == N1.getOperand(1) &&
6257           N0.getOperand(1) == N1.getOperand(0)) {
6258         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6259                                      SDValue(CFP00, 0),
6260                                      DAG.getConstantFP(2.0, VT));
6261         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6262                            N0.getOperand(1), NewCFP);
6263       }
6264
6265       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6266       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6267           N1.getOperand(0) == N1.getOperand(1) &&
6268           N0.getOperand(0) == N1.getOperand(0)) {
6269         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6270                                      SDValue(CFP01, 0),
6271                                      DAG.getConstantFP(2.0, VT));
6272         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6273                            N0.getOperand(0), NewCFP);
6274       }
6275     }
6276
6277     if (N1.getOpcode() == ISD::FMUL) {
6278       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6279       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6280
6281       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6282       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6283         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6284                                      SDValue(CFP10, 0),
6285                                      DAG.getConstantFP(1.0, VT));
6286         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6287                            N0, NewCFP);
6288       }
6289
6290       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6291       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6292         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6293                                      SDValue(CFP11, 0),
6294                                      DAG.getConstantFP(1.0, VT));
6295         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6296                            N0, NewCFP);
6297       }
6298
6299
6300       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6301       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6302           N0.getOperand(0) == N0.getOperand(1) &&
6303           N1.getOperand(1) == N0.getOperand(0)) {
6304         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6305                                      SDValue(CFP10, 0),
6306                                      DAG.getConstantFP(2.0, VT));
6307         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6308                            N1.getOperand(1), NewCFP);
6309       }
6310
6311       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6312       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6313           N0.getOperand(0) == N0.getOperand(1) &&
6314           N1.getOperand(0) == N0.getOperand(0)) {
6315         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6316                                      SDValue(CFP11, 0),
6317                                      DAG.getConstantFP(2.0, VT));
6318         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6319                            N1.getOperand(0), NewCFP);
6320       }
6321     }
6322
6323     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6324       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6325       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6326       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6327           (N0.getOperand(0) == N1))
6328         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6329                            N1, DAG.getConstantFP(3.0, VT));
6330     }
6331
6332     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6333       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6334       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6335       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6336           N1.getOperand(0) == N0)
6337         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6338                            N0, DAG.getConstantFP(3.0, VT));
6339     }
6340
6341     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6342     if (AllowNewFpConst &&
6343         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6344         N0.getOperand(0) == N0.getOperand(1) &&
6345         N1.getOperand(0) == N1.getOperand(1) &&
6346         N0.getOperand(0) == N1.getOperand(0))
6347       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6348                          N0.getOperand(0),
6349                          DAG.getConstantFP(4.0, VT));
6350   }
6351
6352   // FADD -> FMA combines:
6353   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6354        DAG.getTarget().Options.UnsafeFPMath) &&
6355       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6356       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6357
6358     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6359     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6360       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6361                          N0.getOperand(0), N0.getOperand(1), N1);
6362
6363     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6364     // Note: Commutes FADD operands.
6365     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6366       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6367                          N1.getOperand(0), N1.getOperand(1), N0);
6368   }
6369
6370   return SDValue();
6371 }
6372
6373 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6374   SDValue N0 = N->getOperand(0);
6375   SDValue N1 = N->getOperand(1);
6376   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6377   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6378   EVT VT = N->getValueType(0);
6379   SDLoc dl(N);
6380
6381   // fold vector ops
6382   if (VT.isVector()) {
6383     SDValue FoldedVOp = SimplifyVBinOp(N);
6384     if (FoldedVOp.getNode()) return FoldedVOp;
6385   }
6386
6387   // fold (fsub c1, c2) -> c1-c2
6388   if (N0CFP && N1CFP)
6389     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6390   // fold (fsub A, 0) -> A
6391   if (DAG.getTarget().Options.UnsafeFPMath &&
6392       N1CFP && N1CFP->getValueAPF().isZero())
6393     return N0;
6394   // fold (fsub 0, B) -> -B
6395   if (DAG.getTarget().Options.UnsafeFPMath &&
6396       N0CFP && N0CFP->getValueAPF().isZero()) {
6397     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6398       return GetNegatedExpression(N1, DAG, LegalOperations);
6399     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6400       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6401   }
6402   // fold (fsub A, (fneg B)) -> (fadd A, B)
6403   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6404     return DAG.getNode(ISD::FADD, dl, VT, N0,
6405                        GetNegatedExpression(N1, DAG, LegalOperations));
6406
6407   // If 'unsafe math' is enabled, fold
6408   //    (fsub x, x) -> 0.0 &
6409   //    (fsub x, (fadd x, y)) -> (fneg y) &
6410   //    (fsub x, (fadd y, x)) -> (fneg y)
6411   if (DAG.getTarget().Options.UnsafeFPMath) {
6412     if (N0 == N1)
6413       return DAG.getConstantFP(0.0f, VT);
6414
6415     if (N1.getOpcode() == ISD::FADD) {
6416       SDValue N10 = N1->getOperand(0);
6417       SDValue N11 = N1->getOperand(1);
6418
6419       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6420                                           &DAG.getTarget().Options))
6421         return GetNegatedExpression(N11, DAG, LegalOperations);
6422
6423       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6424                                           &DAG.getTarget().Options))
6425         return GetNegatedExpression(N10, DAG, LegalOperations);
6426     }
6427   }
6428
6429   // FSUB -> FMA combines:
6430   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6431        DAG.getTarget().Options.UnsafeFPMath) &&
6432       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6433       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6434
6435     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6436     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6437       return DAG.getNode(ISD::FMA, dl, VT,
6438                          N0.getOperand(0), N0.getOperand(1),
6439                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6440
6441     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6442     // Note: Commutes FSUB operands.
6443     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6444       return DAG.getNode(ISD::FMA, dl, VT,
6445                          DAG.getNode(ISD::FNEG, dl, VT,
6446                          N1.getOperand(0)),
6447                          N1.getOperand(1), N0);
6448
6449     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6450     if (N0.getOpcode() == ISD::FNEG &&
6451         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6452         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6453       SDValue N00 = N0.getOperand(0).getOperand(0);
6454       SDValue N01 = N0.getOperand(0).getOperand(1);
6455       return DAG.getNode(ISD::FMA, dl, VT,
6456                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6457                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6458     }
6459   }
6460
6461   return SDValue();
6462 }
6463
6464 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6465   SDValue N0 = N->getOperand(0);
6466   SDValue N1 = N->getOperand(1);
6467   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6468   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6469   EVT VT = N->getValueType(0);
6470   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6471
6472   // fold vector ops
6473   if (VT.isVector()) {
6474     SDValue FoldedVOp = SimplifyVBinOp(N);
6475     if (FoldedVOp.getNode()) return FoldedVOp;
6476   }
6477
6478   // fold (fmul c1, c2) -> c1*c2
6479   if (N0CFP && N1CFP)
6480     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6481   // canonicalize constant to RHS
6482   if (N0CFP && !N1CFP)
6483     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6484   // fold (fmul A, 0) -> 0
6485   if (DAG.getTarget().Options.UnsafeFPMath &&
6486       N1CFP && N1CFP->getValueAPF().isZero())
6487     return N1;
6488   // fold (fmul A, 0) -> 0, vector edition.
6489   if (DAG.getTarget().Options.UnsafeFPMath &&
6490       ISD::isBuildVectorAllZeros(N1.getNode()))
6491     return N1;
6492   // fold (fmul A, 1.0) -> A
6493   if (N1CFP && N1CFP->isExactlyValue(1.0))
6494     return N0;
6495   // fold (fmul X, 2.0) -> (fadd X, X)
6496   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6497     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6498   // fold (fmul X, -1.0) -> (fneg X)
6499   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6500     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6501       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6502
6503   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6504   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6505                                        &DAG.getTarget().Options)) {
6506     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6507                                          &DAG.getTarget().Options)) {
6508       // Both can be negated for free, check to see if at least one is cheaper
6509       // negated.
6510       if (LHSNeg == 2 || RHSNeg == 2)
6511         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6512                            GetNegatedExpression(N0, DAG, LegalOperations),
6513                            GetNegatedExpression(N1, DAG, LegalOperations));
6514     }
6515   }
6516
6517   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6518   if (DAG.getTarget().Options.UnsafeFPMath &&
6519       N1CFP && N0.getOpcode() == ISD::FMUL &&
6520       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6521     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6522                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6523                                    N0.getOperand(1), N1));
6524
6525   return SDValue();
6526 }
6527
6528 SDValue DAGCombiner::visitFMA(SDNode *N) {
6529   SDValue N0 = N->getOperand(0);
6530   SDValue N1 = N->getOperand(1);
6531   SDValue N2 = N->getOperand(2);
6532   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6533   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6534   EVT VT = N->getValueType(0);
6535   SDLoc dl(N);
6536
6537   if (DAG.getTarget().Options.UnsafeFPMath) {
6538     if (N0CFP && N0CFP->isZero())
6539       return N2;
6540     if (N1CFP && N1CFP->isZero())
6541       return N2;
6542   }
6543   if (N0CFP && N0CFP->isExactlyValue(1.0))
6544     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6545   if (N1CFP && N1CFP->isExactlyValue(1.0))
6546     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6547
6548   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6549   if (N0CFP && !N1CFP)
6550     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6551
6552   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6553   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6554       N2.getOpcode() == ISD::FMUL &&
6555       N0 == N2.getOperand(0) &&
6556       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6557     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6558                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6559   }
6560
6561
6562   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6563   if (DAG.getTarget().Options.UnsafeFPMath &&
6564       N0.getOpcode() == ISD::FMUL && N1CFP &&
6565       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6566     return DAG.getNode(ISD::FMA, dl, VT,
6567                        N0.getOperand(0),
6568                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6569                        N2);
6570   }
6571
6572   // (fma x, 1, y) -> (fadd x, y)
6573   // (fma x, -1, y) -> (fadd (fneg x), y)
6574   if (N1CFP) {
6575     if (N1CFP->isExactlyValue(1.0))
6576       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6577
6578     if (N1CFP->isExactlyValue(-1.0) &&
6579         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6580       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6581       AddToWorkList(RHSNeg.getNode());
6582       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6583     }
6584   }
6585
6586   // (fma x, c, x) -> (fmul x, (c+1))
6587   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6588     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6589                        DAG.getNode(ISD::FADD, dl, VT,
6590                                    N1, DAG.getConstantFP(1.0, VT)));
6591
6592   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6593   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6594       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6595     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6596                        DAG.getNode(ISD::FADD, dl, VT,
6597                                    N1, DAG.getConstantFP(-1.0, VT)));
6598
6599
6600   return SDValue();
6601 }
6602
6603 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6604   SDValue N0 = N->getOperand(0);
6605   SDValue N1 = N->getOperand(1);
6606   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6608   EVT VT = N->getValueType(0);
6609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6610
6611   // fold vector ops
6612   if (VT.isVector()) {
6613     SDValue FoldedVOp = SimplifyVBinOp(N);
6614     if (FoldedVOp.getNode()) return FoldedVOp;
6615   }
6616
6617   // fold (fdiv c1, c2) -> c1/c2
6618   if (N0CFP && N1CFP)
6619     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6620
6621   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6622   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6623     // Compute the reciprocal 1.0 / c2.
6624     APFloat N1APF = N1CFP->getValueAPF();
6625     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6626     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6627     // Only do the transform if the reciprocal is a legal fp immediate that
6628     // isn't too nasty (eg NaN, denormal, ...).
6629     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6630         (!LegalOperations ||
6631          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6632          // backend)... we should handle this gracefully after Legalize.
6633          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6634          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6635          TLI.isFPImmLegal(Recip, VT)))
6636       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6637                          DAG.getConstantFP(Recip, VT));
6638   }
6639
6640   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6641   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6642                                        &DAG.getTarget().Options)) {
6643     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6644                                          &DAG.getTarget().Options)) {
6645       // Both can be negated for free, check to see if at least one is cheaper
6646       // negated.
6647       if (LHSNeg == 2 || RHSNeg == 2)
6648         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6649                            GetNegatedExpression(N0, DAG, LegalOperations),
6650                            GetNegatedExpression(N1, DAG, LegalOperations));
6651     }
6652   }
6653
6654   return SDValue();
6655 }
6656
6657 SDValue DAGCombiner::visitFREM(SDNode *N) {
6658   SDValue N0 = N->getOperand(0);
6659   SDValue N1 = N->getOperand(1);
6660   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6661   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6662   EVT VT = N->getValueType(0);
6663
6664   // fold (frem c1, c2) -> fmod(c1,c2)
6665   if (N0CFP && N1CFP)
6666     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6667
6668   return SDValue();
6669 }
6670
6671 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6672   SDValue N0 = N->getOperand(0);
6673   SDValue N1 = N->getOperand(1);
6674   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6675   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6676   EVT VT = N->getValueType(0);
6677
6678   if (N0CFP && N1CFP)  // Constant fold
6679     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6680
6681   if (N1CFP) {
6682     const APFloat& V = N1CFP->getValueAPF();
6683     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6684     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6685     if (!V.isNegative()) {
6686       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6687         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6688     } else {
6689       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6690         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6691                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6692     }
6693   }
6694
6695   // copysign(fabs(x), y) -> copysign(x, y)
6696   // copysign(fneg(x), y) -> copysign(x, y)
6697   // copysign(copysign(x,z), y) -> copysign(x, y)
6698   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6699       N0.getOpcode() == ISD::FCOPYSIGN)
6700     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6701                        N0.getOperand(0), N1);
6702
6703   // copysign(x, abs(y)) -> abs(x)
6704   if (N1.getOpcode() == ISD::FABS)
6705     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6706
6707   // copysign(x, copysign(y,z)) -> copysign(x, z)
6708   if (N1.getOpcode() == ISD::FCOPYSIGN)
6709     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6710                        N0, N1.getOperand(1));
6711
6712   // copysign(x, fp_extend(y)) -> copysign(x, y)
6713   // copysign(x, fp_round(y)) -> copysign(x, y)
6714   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6715     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6716                        N0, N1.getOperand(0));
6717
6718   return SDValue();
6719 }
6720
6721 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6722   SDValue N0 = N->getOperand(0);
6723   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6724   EVT VT = N->getValueType(0);
6725   EVT OpVT = N0.getValueType();
6726
6727   // fold (sint_to_fp c1) -> c1fp
6728   if (N0C &&
6729       // ...but only if the target supports immediate floating-point values
6730       (!LegalOperations ||
6731        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6732     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6733
6734   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6735   // but UINT_TO_FP is legal on this target, try to convert.
6736   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6737       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6738     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6739     if (DAG.SignBitIsZero(N0))
6740       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6741   }
6742
6743   // The next optimizations are desirable only if SELECT_CC can be lowered.
6744   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6745   // having to say they don't support SELECT_CC on every type the DAG knows
6746   // about, since there is no way to mark an opcode illegal at all value types
6747   // (See also visitSELECT)
6748   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6749     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6750     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6751         !VT.isVector() &&
6752         (!LegalOperations ||
6753          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6754       SDValue Ops[] =
6755         { N0.getOperand(0), N0.getOperand(1),
6756           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6757           N0.getOperand(2) };
6758       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6759     }
6760
6761     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6762     //      (select_cc x, y, 1.0, 0.0,, cc)
6763     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6764         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6765         (!LegalOperations ||
6766          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6767       SDValue Ops[] =
6768         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6769           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6770           N0.getOperand(0).getOperand(2) };
6771       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6772     }
6773   }
6774
6775   return SDValue();
6776 }
6777
6778 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6779   SDValue N0 = N->getOperand(0);
6780   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6781   EVT VT = N->getValueType(0);
6782   EVT OpVT = N0.getValueType();
6783
6784   // fold (uint_to_fp c1) -> c1fp
6785   if (N0C &&
6786       // ...but only if the target supports immediate floating-point values
6787       (!LegalOperations ||
6788        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6789     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6790
6791   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6792   // but SINT_TO_FP is legal on this target, try to convert.
6793   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6794       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6795     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6796     if (DAG.SignBitIsZero(N0))
6797       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6798   }
6799
6800   // The next optimizations are desirable only if SELECT_CC can be lowered.
6801   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6802   // having to say they don't support SELECT_CC on every type the DAG knows
6803   // about, since there is no way to mark an opcode illegal at all value types
6804   // (See also visitSELECT)
6805   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6806     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6807
6808     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6809         (!LegalOperations ||
6810          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6811       SDValue Ops[] =
6812         { N0.getOperand(0), N0.getOperand(1),
6813           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6814           N0.getOperand(2) };
6815       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6816     }
6817   }
6818
6819   return SDValue();
6820 }
6821
6822 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6823   SDValue N0 = N->getOperand(0);
6824   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825   EVT VT = N->getValueType(0);
6826
6827   // fold (fp_to_sint c1fp) -> c1
6828   if (N0CFP)
6829     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6830
6831   return SDValue();
6832 }
6833
6834 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6835   SDValue N0 = N->getOperand(0);
6836   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837   EVT VT = N->getValueType(0);
6838
6839   // fold (fp_to_uint c1fp) -> c1
6840   if (N0CFP)
6841     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6842
6843   return SDValue();
6844 }
6845
6846 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6847   SDValue N0 = N->getOperand(0);
6848   SDValue N1 = N->getOperand(1);
6849   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6850   EVT VT = N->getValueType(0);
6851
6852   // fold (fp_round c1fp) -> c1fp
6853   if (N0CFP)
6854     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6855
6856   // fold (fp_round (fp_extend x)) -> x
6857   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6858     return N0.getOperand(0);
6859
6860   // fold (fp_round (fp_round x)) -> (fp_round x)
6861   if (N0.getOpcode() == ISD::FP_ROUND) {
6862     // This is a value preserving truncation if both round's are.
6863     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6864                    N0.getNode()->getConstantOperandVal(1) == 1;
6865     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6866                        DAG.getIntPtrConstant(IsTrunc));
6867   }
6868
6869   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6870   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6871     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6872                               N0.getOperand(0), N1);
6873     AddToWorkList(Tmp.getNode());
6874     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6875                        Tmp, N0.getOperand(1));
6876   }
6877
6878   return SDValue();
6879 }
6880
6881 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6882   SDValue N0 = N->getOperand(0);
6883   EVT VT = N->getValueType(0);
6884   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6885   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6886
6887   // fold (fp_round_inreg c1fp) -> c1fp
6888   if (N0CFP && isTypeLegal(EVT)) {
6889     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6890     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6891   }
6892
6893   return SDValue();
6894 }
6895
6896 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6897   SDValue N0 = N->getOperand(0);
6898   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6899   EVT VT = N->getValueType(0);
6900
6901   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6902   if (N->hasOneUse() &&
6903       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6904     return SDValue();
6905
6906   // fold (fp_extend c1fp) -> c1fp
6907   if (N0CFP)
6908     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6909
6910   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6911   // value of X.
6912   if (N0.getOpcode() == ISD::FP_ROUND
6913       && N0.getNode()->getConstantOperandVal(1) == 1) {
6914     SDValue In = N0.getOperand(0);
6915     if (In.getValueType() == VT) return In;
6916     if (VT.bitsLT(In.getValueType()))
6917       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6918                          In, N0.getOperand(1));
6919     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6920   }
6921
6922   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6923   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6924       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6925        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6926     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6927     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6928                                      LN0->getChain(),
6929                                      LN0->getBasePtr(), N0.getValueType(),
6930                                      LN0->getMemOperand());
6931     CombineTo(N, ExtLoad);
6932     CombineTo(N0.getNode(),
6933               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6934                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6935               ExtLoad.getValue(1));
6936     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6937   }
6938
6939   return SDValue();
6940 }
6941
6942 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6943   SDValue N0 = N->getOperand(0);
6944   EVT VT = N->getValueType(0);
6945
6946   if (VT.isVector()) {
6947     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6948     if (FoldedVOp.getNode()) return FoldedVOp;
6949   }
6950
6951   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6952                          &DAG.getTarget().Options))
6953     return GetNegatedExpression(N0, DAG, LegalOperations);
6954
6955   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6956   // constant pool values.
6957   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6958       !VT.isVector() &&
6959       N0.getNode()->hasOneUse() &&
6960       N0.getOperand(0).getValueType().isInteger()) {
6961     SDValue Int = N0.getOperand(0);
6962     EVT IntVT = Int.getValueType();
6963     if (IntVT.isInteger() && !IntVT.isVector()) {
6964       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6965               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6966       AddToWorkList(Int.getNode());
6967       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6968                          VT, Int);
6969     }
6970   }
6971
6972   // (fneg (fmul c, x)) -> (fmul -c, x)
6973   if (N0.getOpcode() == ISD::FMUL) {
6974     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6975     if (CFP1)
6976       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6977                          N0.getOperand(0),
6978                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6979                                      N0.getOperand(1)));
6980   }
6981
6982   return SDValue();
6983 }
6984
6985 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6986   SDValue N0 = N->getOperand(0);
6987   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6988   EVT VT = N->getValueType(0);
6989
6990   // fold (fceil c1) -> fceil(c1)
6991   if (N0CFP)
6992     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6993
6994   return SDValue();
6995 }
6996
6997 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6998   SDValue N0 = N->getOperand(0);
6999   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7000   EVT VT = N->getValueType(0);
7001
7002   // fold (ftrunc c1) -> ftrunc(c1)
7003   if (N0CFP)
7004     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7005
7006   return SDValue();
7007 }
7008
7009 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7010   SDValue N0 = N->getOperand(0);
7011   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7012   EVT VT = N->getValueType(0);
7013
7014   // fold (ffloor c1) -> ffloor(c1)
7015   if (N0CFP)
7016     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7017
7018   return SDValue();
7019 }
7020
7021 SDValue DAGCombiner::visitFABS(SDNode *N) {
7022   SDValue N0 = N->getOperand(0);
7023   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7024   EVT VT = N->getValueType(0);
7025
7026   if (VT.isVector()) {
7027     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7028     if (FoldedVOp.getNode()) return FoldedVOp;
7029   }
7030
7031   // fold (fabs c1) -> fabs(c1)
7032   if (N0CFP)
7033     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7034   // fold (fabs (fabs x)) -> (fabs x)
7035   if (N0.getOpcode() == ISD::FABS)
7036     return N->getOperand(0);
7037   // fold (fabs (fneg x)) -> (fabs x)
7038   // fold (fabs (fcopysign x, y)) -> (fabs x)
7039   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7040     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7041
7042   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7043   // constant pool values.
7044   if (!TLI.isFAbsFree(VT) &&
7045       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7046       N0.getOperand(0).getValueType().isInteger() &&
7047       !N0.getOperand(0).getValueType().isVector()) {
7048     SDValue Int = N0.getOperand(0);
7049     EVT IntVT = Int.getValueType();
7050     if (IntVT.isInteger() && !IntVT.isVector()) {
7051       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7052              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7053       AddToWorkList(Int.getNode());
7054       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7055                          N->getValueType(0), Int);
7056     }
7057   }
7058
7059   return SDValue();
7060 }
7061
7062 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7063   SDValue Chain = N->getOperand(0);
7064   SDValue N1 = N->getOperand(1);
7065   SDValue N2 = N->getOperand(2);
7066
7067   // If N is a constant we could fold this into a fallthrough or unconditional
7068   // branch. However that doesn't happen very often in normal code, because
7069   // Instcombine/SimplifyCFG should have handled the available opportunities.
7070   // If we did this folding here, it would be necessary to update the
7071   // MachineBasicBlock CFG, which is awkward.
7072
7073   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7074   // on the target.
7075   if (N1.getOpcode() == ISD::SETCC &&
7076       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7077                                    N1.getOperand(0).getValueType())) {
7078     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7079                        Chain, N1.getOperand(2),
7080                        N1.getOperand(0), N1.getOperand(1), N2);
7081   }
7082
7083   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7084       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7085        (N1.getOperand(0).hasOneUse() &&
7086         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7087     SDNode *Trunc = 0;
7088     if (N1.getOpcode() == ISD::TRUNCATE) {
7089       // Look pass the truncate.
7090       Trunc = N1.getNode();
7091       N1 = N1.getOperand(0);
7092     }
7093
7094     // Match this pattern so that we can generate simpler code:
7095     //
7096     //   %a = ...
7097     //   %b = and i32 %a, 2
7098     //   %c = srl i32 %b, 1
7099     //   brcond i32 %c ...
7100     //
7101     // into
7102     //
7103     //   %a = ...
7104     //   %b = and i32 %a, 2
7105     //   %c = setcc eq %b, 0
7106     //   brcond %c ...
7107     //
7108     // This applies only when the AND constant value has one bit set and the
7109     // SRL constant is equal to the log2 of the AND constant. The back-end is
7110     // smart enough to convert the result into a TEST/JMP sequence.
7111     SDValue Op0 = N1.getOperand(0);
7112     SDValue Op1 = N1.getOperand(1);
7113
7114     if (Op0.getOpcode() == ISD::AND &&
7115         Op1.getOpcode() == ISD::Constant) {
7116       SDValue AndOp1 = Op0.getOperand(1);
7117
7118       if (AndOp1.getOpcode() == ISD::Constant) {
7119         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7120
7121         if (AndConst.isPowerOf2() &&
7122             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7123           SDValue SetCC =
7124             DAG.getSetCC(SDLoc(N),
7125                          getSetCCResultType(Op0.getValueType()),
7126                          Op0, DAG.getConstant(0, Op0.getValueType()),
7127                          ISD::SETNE);
7128
7129           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7130                                           MVT::Other, Chain, SetCC, N2);
7131           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7132           // will convert it back to (X & C1) >> C2.
7133           CombineTo(N, NewBRCond, false);
7134           // Truncate is dead.
7135           if (Trunc) {
7136             removeFromWorkList(Trunc);
7137             DAG.DeleteNode(Trunc);
7138           }
7139           // Replace the uses of SRL with SETCC
7140           WorkListRemover DeadNodes(*this);
7141           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7142           removeFromWorkList(N1.getNode());
7143           DAG.DeleteNode(N1.getNode());
7144           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7145         }
7146       }
7147     }
7148
7149     if (Trunc)
7150       // Restore N1 if the above transformation doesn't match.
7151       N1 = N->getOperand(1);
7152   }
7153
7154   // Transform br(xor(x, y)) -> br(x != y)
7155   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7156   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7157     SDNode *TheXor = N1.getNode();
7158     SDValue Op0 = TheXor->getOperand(0);
7159     SDValue Op1 = TheXor->getOperand(1);
7160     if (Op0.getOpcode() == Op1.getOpcode()) {
7161       // Avoid missing important xor optimizations.
7162       SDValue Tmp = visitXOR(TheXor);
7163       if (Tmp.getNode()) {
7164         if (Tmp.getNode() != TheXor) {
7165           DEBUG(dbgs() << "\nReplacing.8 ";
7166                 TheXor->dump(&DAG);
7167                 dbgs() << "\nWith: ";
7168                 Tmp.getNode()->dump(&DAG);
7169                 dbgs() << '\n');
7170           WorkListRemover DeadNodes(*this);
7171           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7172           removeFromWorkList(TheXor);
7173           DAG.DeleteNode(TheXor);
7174           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7175                              MVT::Other, Chain, Tmp, N2);
7176         }
7177
7178         // visitXOR has changed XOR's operands or replaced the XOR completely,
7179         // bail out.
7180         return SDValue(N, 0);
7181       }
7182     }
7183
7184     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7185       bool Equal = false;
7186       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7187         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7188             Op0.getOpcode() == ISD::XOR) {
7189           TheXor = Op0.getNode();
7190           Equal = true;
7191         }
7192
7193       EVT SetCCVT = N1.getValueType();
7194       if (LegalTypes)
7195         SetCCVT = getSetCCResultType(SetCCVT);
7196       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7197                                    SetCCVT,
7198                                    Op0, Op1,
7199                                    Equal ? ISD::SETEQ : ISD::SETNE);
7200       // Replace the uses of XOR with SETCC
7201       WorkListRemover DeadNodes(*this);
7202       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7203       removeFromWorkList(N1.getNode());
7204       DAG.DeleteNode(N1.getNode());
7205       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7206                          MVT::Other, Chain, SetCC, N2);
7207     }
7208   }
7209
7210   return SDValue();
7211 }
7212
7213 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7214 //
7215 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7216   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7217   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7218
7219   // If N is a constant we could fold this into a fallthrough or unconditional
7220   // branch. However that doesn't happen very often in normal code, because
7221   // Instcombine/SimplifyCFG should have handled the available opportunities.
7222   // If we did this folding here, it would be necessary to update the
7223   // MachineBasicBlock CFG, which is awkward.
7224
7225   // Use SimplifySetCC to simplify SETCC's.
7226   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7227                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7228                                false);
7229   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7230
7231   // fold to a simpler setcc
7232   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7233     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7234                        N->getOperand(0), Simp.getOperand(2),
7235                        Simp.getOperand(0), Simp.getOperand(1),
7236                        N->getOperand(4));
7237
7238   return SDValue();
7239 }
7240
7241 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7242 /// uses N as its base pointer and that N may be folded in the load / store
7243 /// addressing mode.
7244 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7245                                     SelectionDAG &DAG,
7246                                     const TargetLowering &TLI) {
7247   EVT VT;
7248   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7249     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7250       return false;
7251     VT = Use->getValueType(0);
7252   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7253     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7254       return false;
7255     VT = ST->getValue().getValueType();
7256   } else
7257     return false;
7258
7259   TargetLowering::AddrMode AM;
7260   if (N->getOpcode() == ISD::ADD) {
7261     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7262     if (Offset)
7263       // [reg +/- imm]
7264       AM.BaseOffs = Offset->getSExtValue();
7265     else
7266       // [reg +/- reg]
7267       AM.Scale = 1;
7268   } else if (N->getOpcode() == ISD::SUB) {
7269     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7270     if (Offset)
7271       // [reg +/- imm]
7272       AM.BaseOffs = -Offset->getSExtValue();
7273     else
7274       // [reg +/- reg]
7275       AM.Scale = 1;
7276   } else
7277     return false;
7278
7279   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7280 }
7281
7282 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7283 /// pre-indexed load / store when the base pointer is an add or subtract
7284 /// and it has other uses besides the load / store. After the
7285 /// transformation, the new indexed load / store has effectively folded
7286 /// the add / subtract in and all of its other uses are redirected to the
7287 /// new load / store.
7288 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7289   if (Level < AfterLegalizeDAG)
7290     return false;
7291
7292   bool isLoad = true;
7293   SDValue Ptr;
7294   EVT VT;
7295   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7296     if (LD->isIndexed())
7297       return false;
7298     VT = LD->getMemoryVT();
7299     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7300         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7301       return false;
7302     Ptr = LD->getBasePtr();
7303   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7304     if (ST->isIndexed())
7305       return false;
7306     VT = ST->getMemoryVT();
7307     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7308         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7309       return false;
7310     Ptr = ST->getBasePtr();
7311     isLoad = false;
7312   } else {
7313     return false;
7314   }
7315
7316   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7317   // out.  There is no reason to make this a preinc/predec.
7318   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7319       Ptr.getNode()->hasOneUse())
7320     return false;
7321
7322   // Ask the target to do addressing mode selection.
7323   SDValue BasePtr;
7324   SDValue Offset;
7325   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7326   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7327     return false;
7328
7329   // Backends without true r+i pre-indexed forms may need to pass a
7330   // constant base with a variable offset so that constant coercion
7331   // will work with the patterns in canonical form.
7332   bool Swapped = false;
7333   if (isa<ConstantSDNode>(BasePtr)) {
7334     std::swap(BasePtr, Offset);
7335     Swapped = true;
7336   }
7337
7338   // Don't create a indexed load / store with zero offset.
7339   if (isa<ConstantSDNode>(Offset) &&
7340       cast<ConstantSDNode>(Offset)->isNullValue())
7341     return false;
7342
7343   // Try turning it into a pre-indexed load / store except when:
7344   // 1) The new base ptr is a frame index.
7345   // 2) If N is a store and the new base ptr is either the same as or is a
7346   //    predecessor of the value being stored.
7347   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7348   //    that would create a cycle.
7349   // 4) All uses are load / store ops that use it as old base ptr.
7350
7351   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7352   // (plus the implicit offset) to a register to preinc anyway.
7353   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7354     return false;
7355
7356   // Check #2.
7357   if (!isLoad) {
7358     SDValue Val = cast<StoreSDNode>(N)->getValue();
7359     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7360       return false;
7361   }
7362
7363   // If the offset is a constant, there may be other adds of constants that
7364   // can be folded with this one. We should do this to avoid having to keep
7365   // a copy of the original base pointer.
7366   SmallVector<SDNode *, 16> OtherUses;
7367   if (isa<ConstantSDNode>(Offset))
7368     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7369          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7370       SDNode *Use = *I;
7371       if (Use == Ptr.getNode())
7372         continue;
7373
7374       if (Use->isPredecessorOf(N))
7375         continue;
7376
7377       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7378         OtherUses.clear();
7379         break;
7380       }
7381
7382       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7383       if (Op1.getNode() == BasePtr.getNode())
7384         std::swap(Op0, Op1);
7385       assert(Op0.getNode() == BasePtr.getNode() &&
7386              "Use of ADD/SUB but not an operand");
7387
7388       if (!isa<ConstantSDNode>(Op1)) {
7389         OtherUses.clear();
7390         break;
7391       }
7392
7393       // FIXME: In some cases, we can be smarter about this.
7394       if (Op1.getValueType() != Offset.getValueType()) {
7395         OtherUses.clear();
7396         break;
7397       }
7398
7399       OtherUses.push_back(Use);
7400     }
7401
7402   if (Swapped)
7403     std::swap(BasePtr, Offset);
7404
7405   // Now check for #3 and #4.
7406   bool RealUse = false;
7407
7408   // Caches for hasPredecessorHelper
7409   SmallPtrSet<const SDNode *, 32> Visited;
7410   SmallVector<const SDNode *, 16> Worklist;
7411
7412   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7413          E = Ptr.getNode()->use_end(); I != E; ++I) {
7414     SDNode *Use = *I;
7415     if (Use == N)
7416       continue;
7417     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7418       return false;
7419
7420     // If Ptr may be folded in addressing mode of other use, then it's
7421     // not profitable to do this transformation.
7422     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7423       RealUse = true;
7424   }
7425
7426   if (!RealUse)
7427     return false;
7428
7429   SDValue Result;
7430   if (isLoad)
7431     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7432                                 BasePtr, Offset, AM);
7433   else
7434     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7435                                  BasePtr, Offset, AM);
7436   ++PreIndexedNodes;
7437   ++NodesCombined;
7438   DEBUG(dbgs() << "\nReplacing.4 ";
7439         N->dump(&DAG);
7440         dbgs() << "\nWith: ";
7441         Result.getNode()->dump(&DAG);
7442         dbgs() << '\n');
7443   WorkListRemover DeadNodes(*this);
7444   if (isLoad) {
7445     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7446     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7447   } else {
7448     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7449   }
7450
7451   // Finally, since the node is now dead, remove it from the graph.
7452   DAG.DeleteNode(N);
7453
7454   if (Swapped)
7455     std::swap(BasePtr, Offset);
7456
7457   // Replace other uses of BasePtr that can be updated to use Ptr
7458   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7459     unsigned OffsetIdx = 1;
7460     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7461       OffsetIdx = 0;
7462     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7463            BasePtr.getNode() && "Expected BasePtr operand");
7464
7465     // We need to replace ptr0 in the following expression:
7466     //   x0 * offset0 + y0 * ptr0 = t0
7467     // knowing that
7468     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7469     //
7470     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7471     // indexed load/store and the expresion that needs to be re-written.
7472     //
7473     // Therefore, we have:
7474     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7475
7476     ConstantSDNode *CN =
7477       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7478     int X0, X1, Y0, Y1;
7479     APInt Offset0 = CN->getAPIntValue();
7480     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7481
7482     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7483     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7484     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7485     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7486
7487     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7488
7489     APInt CNV = Offset0;
7490     if (X0 < 0) CNV = -CNV;
7491     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7492     else CNV = CNV - Offset1;
7493
7494     // We can now generate the new expression.
7495     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7496     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7497
7498     SDValue NewUse = DAG.getNode(Opcode,
7499                                  SDLoc(OtherUses[i]),
7500                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7501     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7502     removeFromWorkList(OtherUses[i]);
7503     DAG.DeleteNode(OtherUses[i]);
7504   }
7505
7506   // Replace the uses of Ptr with uses of the updated base value.
7507   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7508   removeFromWorkList(Ptr.getNode());
7509   DAG.DeleteNode(Ptr.getNode());
7510
7511   return true;
7512 }
7513
7514 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7515 /// add / sub of the base pointer node into a post-indexed load / store.
7516 /// The transformation folded the add / subtract into the new indexed
7517 /// load / store effectively and all of its uses are redirected to the
7518 /// new load / store.
7519 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7520   if (Level < AfterLegalizeDAG)
7521     return false;
7522
7523   bool isLoad = true;
7524   SDValue Ptr;
7525   EVT VT;
7526   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7527     if (LD->isIndexed())
7528       return false;
7529     VT = LD->getMemoryVT();
7530     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7531         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7532       return false;
7533     Ptr = LD->getBasePtr();
7534   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7535     if (ST->isIndexed())
7536       return false;
7537     VT = ST->getMemoryVT();
7538     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7539         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7540       return false;
7541     Ptr = ST->getBasePtr();
7542     isLoad = false;
7543   } else {
7544     return false;
7545   }
7546
7547   if (Ptr.getNode()->hasOneUse())
7548     return false;
7549
7550   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7551          E = Ptr.getNode()->use_end(); I != E; ++I) {
7552     SDNode *Op = *I;
7553     if (Op == N ||
7554         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7555       continue;
7556
7557     SDValue BasePtr;
7558     SDValue Offset;
7559     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7560     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7561       // Don't create a indexed load / store with zero offset.
7562       if (isa<ConstantSDNode>(Offset) &&
7563           cast<ConstantSDNode>(Offset)->isNullValue())
7564         continue;
7565
7566       // Try turning it into a post-indexed load / store except when
7567       // 1) All uses are load / store ops that use it as base ptr (and
7568       //    it may be folded as addressing mmode).
7569       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7570       //    nor a successor of N. Otherwise, if Op is folded that would
7571       //    create a cycle.
7572
7573       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7574         continue;
7575
7576       // Check for #1.
7577       bool TryNext = false;
7578       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7579              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7580         SDNode *Use = *II;
7581         if (Use == Ptr.getNode())
7582           continue;
7583
7584         // If all the uses are load / store addresses, then don't do the
7585         // transformation.
7586         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7587           bool RealUse = false;
7588           for (SDNode::use_iterator III = Use->use_begin(),
7589                  EEE = Use->use_end(); III != EEE; ++III) {
7590             SDNode *UseUse = *III;
7591             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7592               RealUse = true;
7593           }
7594
7595           if (!RealUse) {
7596             TryNext = true;
7597             break;
7598           }
7599         }
7600       }
7601
7602       if (TryNext)
7603         continue;
7604
7605       // Check for #2
7606       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7607         SDValue Result = isLoad
7608           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7609                                BasePtr, Offset, AM)
7610           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7611                                 BasePtr, Offset, AM);
7612         ++PostIndexedNodes;
7613         ++NodesCombined;
7614         DEBUG(dbgs() << "\nReplacing.5 ";
7615               N->dump(&DAG);
7616               dbgs() << "\nWith: ";
7617               Result.getNode()->dump(&DAG);
7618               dbgs() << '\n');
7619         WorkListRemover DeadNodes(*this);
7620         if (isLoad) {
7621           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7622           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7623         } else {
7624           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7625         }
7626
7627         // Finally, since the node is now dead, remove it from the graph.
7628         DAG.DeleteNode(N);
7629
7630         // Replace the uses of Use with uses of the updated base value.
7631         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7632                                       Result.getValue(isLoad ? 1 : 0));
7633         removeFromWorkList(Op);
7634         DAG.DeleteNode(Op);
7635         return true;
7636       }
7637     }
7638   }
7639
7640   return false;
7641 }
7642
7643 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7644   LoadSDNode *LD  = cast<LoadSDNode>(N);
7645   SDValue Chain = LD->getChain();
7646   SDValue Ptr   = LD->getBasePtr();
7647
7648   // If load is not volatile and there are no uses of the loaded value (and
7649   // the updated indexed value in case of indexed loads), change uses of the
7650   // chain value into uses of the chain input (i.e. delete the dead load).
7651   if (!LD->isVolatile()) {
7652     if (N->getValueType(1) == MVT::Other) {
7653       // Unindexed loads.
7654       if (!N->hasAnyUseOfValue(0)) {
7655         // It's not safe to use the two value CombineTo variant here. e.g.
7656         // v1, chain2 = load chain1, loc
7657         // v2, chain3 = load chain2, loc
7658         // v3         = add v2, c
7659         // Now we replace use of chain2 with chain1.  This makes the second load
7660         // isomorphic to the one we are deleting, and thus makes this load live.
7661         DEBUG(dbgs() << "\nReplacing.6 ";
7662               N->dump(&DAG);
7663               dbgs() << "\nWith chain: ";
7664               Chain.getNode()->dump(&DAG);
7665               dbgs() << "\n");
7666         WorkListRemover DeadNodes(*this);
7667         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7668
7669         if (N->use_empty()) {
7670           removeFromWorkList(N);
7671           DAG.DeleteNode(N);
7672         }
7673
7674         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7675       }
7676     } else {
7677       // Indexed loads.
7678       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7679       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7680         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7681         DEBUG(dbgs() << "\nReplacing.7 ";
7682               N->dump(&DAG);
7683               dbgs() << "\nWith: ";
7684               Undef.getNode()->dump(&DAG);
7685               dbgs() << " and 2 other values\n");
7686         WorkListRemover DeadNodes(*this);
7687         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7688         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7689                                       DAG.getUNDEF(N->getValueType(1)));
7690         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7691         removeFromWorkList(N);
7692         DAG.DeleteNode(N);
7693         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7694       }
7695     }
7696   }
7697
7698   // If this load is directly stored, replace the load value with the stored
7699   // value.
7700   // TODO: Handle store large -> read small portion.
7701   // TODO: Handle TRUNCSTORE/LOADEXT
7702   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7703     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7704       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7705       if (PrevST->getBasePtr() == Ptr &&
7706           PrevST->getValue().getValueType() == N->getValueType(0))
7707       return CombineTo(N, Chain.getOperand(1), Chain);
7708     }
7709   }
7710
7711   // Try to infer better alignment information than the load already has.
7712   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7713     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7714       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7715         SDValue NewLoad =
7716                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7717                               LD->getValueType(0),
7718                               Chain, Ptr, LD->getPointerInfo(),
7719                               LD->getMemoryVT(),
7720                               LD->isVolatile(), LD->isNonTemporal(), Align,
7721                               LD->getTBAAInfo());
7722         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7723       }
7724     }
7725   }
7726
7727   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7728     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7729   if (UseAA && LD->isUnindexed()) {
7730     // Walk up chain skipping non-aliasing memory nodes.
7731     SDValue BetterChain = FindBetterChain(N, Chain);
7732
7733     // If there is a better chain.
7734     if (Chain != BetterChain) {
7735       SDValue ReplLoad;
7736
7737       // Replace the chain to void dependency.
7738       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7739         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7740                                BetterChain, Ptr, LD->getMemOperand());
7741       } else {
7742         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7743                                   LD->getValueType(0),
7744                                   BetterChain, Ptr, LD->getMemoryVT(),
7745                                   LD->getMemOperand());
7746       }
7747
7748       // Create token factor to keep old chain connected.
7749       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7750                                   MVT::Other, Chain, ReplLoad.getValue(1));
7751
7752       // Make sure the new and old chains are cleaned up.
7753       AddToWorkList(Token.getNode());
7754
7755       // Replace uses with load result and token factor. Don't add users
7756       // to work list.
7757       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7758     }
7759   }
7760
7761   // Try transforming N to an indexed load.
7762   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7763     return SDValue(N, 0);
7764
7765   // Try to slice up N to more direct loads if the slices are mapped to
7766   // different register banks or pairing can take place.
7767   if (SliceUpLoad(N))
7768     return SDValue(N, 0);
7769
7770   return SDValue();
7771 }
7772
7773 namespace {
7774 /// \brief Helper structure used to slice a load in smaller loads.
7775 /// Basically a slice is obtained from the following sequence:
7776 /// Origin = load Ty1, Base
7777 /// Shift = srl Ty1 Origin, CstTy Amount
7778 /// Inst = trunc Shift to Ty2
7779 ///
7780 /// Then, it will be rewriten into:
7781 /// Slice = load SliceTy, Base + SliceOffset
7782 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7783 ///
7784 /// SliceTy is deduced from the number of bits that are actually used to
7785 /// build Inst.
7786 struct LoadedSlice {
7787   /// \brief Helper structure used to compute the cost of a slice.
7788   struct Cost {
7789     /// Are we optimizing for code size.
7790     bool ForCodeSize;
7791     /// Various cost.
7792     unsigned Loads;
7793     unsigned Truncates;
7794     unsigned CrossRegisterBanksCopies;
7795     unsigned ZExts;
7796     unsigned Shift;
7797
7798     Cost(bool ForCodeSize = false)
7799         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7800           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7801
7802     /// \brief Get the cost of one isolated slice.
7803     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7804         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7805           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7806       EVT TruncType = LS.Inst->getValueType(0);
7807       EVT LoadedType = LS.getLoadedType();
7808       if (TruncType != LoadedType &&
7809           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7810         ZExts = 1;
7811     }
7812
7813     /// \brief Account for slicing gain in the current cost.
7814     /// Slicing provide a few gains like removing a shift or a
7815     /// truncate. This method allows to grow the cost of the original
7816     /// load with the gain from this slice.
7817     void addSliceGain(const LoadedSlice &LS) {
7818       // Each slice saves a truncate.
7819       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7820       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7821                               LS.Inst->getOperand(0).getValueType()))
7822         ++Truncates;
7823       // If there is a shift amount, this slice gets rid of it.
7824       if (LS.Shift)
7825         ++Shift;
7826       // If this slice can merge a cross register bank copy, account for it.
7827       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7828         ++CrossRegisterBanksCopies;
7829     }
7830
7831     Cost &operator+=(const Cost &RHS) {
7832       Loads += RHS.Loads;
7833       Truncates += RHS.Truncates;
7834       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7835       ZExts += RHS.ZExts;
7836       Shift += RHS.Shift;
7837       return *this;
7838     }
7839
7840     bool operator==(const Cost &RHS) const {
7841       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7842              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7843              ZExts == RHS.ZExts && Shift == RHS.Shift;
7844     }
7845
7846     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7847
7848     bool operator<(const Cost &RHS) const {
7849       // Assume cross register banks copies are as expensive as loads.
7850       // FIXME: Do we want some more target hooks?
7851       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7852       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7853       // Unless we are optimizing for code size, consider the
7854       // expensive operation first.
7855       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7856         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7857       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7858              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7859     }
7860
7861     bool operator>(const Cost &RHS) const { return RHS < *this; }
7862
7863     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7864
7865     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7866   };
7867   // The last instruction that represent the slice. This should be a
7868   // truncate instruction.
7869   SDNode *Inst;
7870   // The original load instruction.
7871   LoadSDNode *Origin;
7872   // The right shift amount in bits from the original load.
7873   unsigned Shift;
7874   // The DAG from which Origin came from.
7875   // This is used to get some contextual information about legal types, etc.
7876   SelectionDAG *DAG;
7877
7878   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7879               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7880       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7881
7882   LoadedSlice(const LoadedSlice &LS)
7883       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7884
7885   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7886   /// \return Result is \p BitWidth and has used bits set to 1 and
7887   ///         not used bits set to 0.
7888   APInt getUsedBits() const {
7889     // Reproduce the trunc(lshr) sequence:
7890     // - Start from the truncated value.
7891     // - Zero extend to the desired bit width.
7892     // - Shift left.
7893     assert(Origin && "No original load to compare against.");
7894     unsigned BitWidth = Origin->getValueSizeInBits(0);
7895     assert(Inst && "This slice is not bound to an instruction");
7896     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7897            "Extracted slice is bigger than the whole type!");
7898     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7899     UsedBits.setAllBits();
7900     UsedBits = UsedBits.zext(BitWidth);
7901     UsedBits <<= Shift;
7902     return UsedBits;
7903   }
7904
7905   /// \brief Get the size of the slice to be loaded in bytes.
7906   unsigned getLoadedSize() const {
7907     unsigned SliceSize = getUsedBits().countPopulation();
7908     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7909     return SliceSize / 8;
7910   }
7911
7912   /// \brief Get the type that will be loaded for this slice.
7913   /// Note: This may not be the final type for the slice.
7914   EVT getLoadedType() const {
7915     assert(DAG && "Missing context");
7916     LLVMContext &Ctxt = *DAG->getContext();
7917     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7918   }
7919
7920   /// \brief Get the alignment of the load used for this slice.
7921   unsigned getAlignment() const {
7922     unsigned Alignment = Origin->getAlignment();
7923     unsigned Offset = getOffsetFromBase();
7924     if (Offset != 0)
7925       Alignment = MinAlign(Alignment, Alignment + Offset);
7926     return Alignment;
7927   }
7928
7929   /// \brief Check if this slice can be rewritten with legal operations.
7930   bool isLegal() const {
7931     // An invalid slice is not legal.
7932     if (!Origin || !Inst || !DAG)
7933       return false;
7934
7935     // Offsets are for indexed load only, we do not handle that.
7936     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7937       return false;
7938
7939     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7940
7941     // Check that the type is legal.
7942     EVT SliceType = getLoadedType();
7943     if (!TLI.isTypeLegal(SliceType))
7944       return false;
7945
7946     // Check that the load is legal for this type.
7947     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7948       return false;
7949
7950     // Check that the offset can be computed.
7951     // 1. Check its type.
7952     EVT PtrType = Origin->getBasePtr().getValueType();
7953     if (PtrType == MVT::Untyped || PtrType.isExtended())
7954       return false;
7955
7956     // 2. Check that it fits in the immediate.
7957     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7958       return false;
7959
7960     // 3. Check that the computation is legal.
7961     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7962       return false;
7963
7964     // Check that the zext is legal if it needs one.
7965     EVT TruncateType = Inst->getValueType(0);
7966     if (TruncateType != SliceType &&
7967         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7968       return false;
7969
7970     return true;
7971   }
7972
7973   /// \brief Get the offset in bytes of this slice in the original chunk of
7974   /// bits.
7975   /// \pre DAG != NULL.
7976   uint64_t getOffsetFromBase() const {
7977     assert(DAG && "Missing context.");
7978     bool IsBigEndian =
7979         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7980     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7981     uint64_t Offset = Shift / 8;
7982     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7983     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7984            "The size of the original loaded type is not a multiple of a"
7985            " byte.");
7986     // If Offset is bigger than TySizeInBytes, it means we are loading all
7987     // zeros. This should have been optimized before in the process.
7988     assert(TySizeInBytes > Offset &&
7989            "Invalid shift amount for given loaded size");
7990     if (IsBigEndian)
7991       Offset = TySizeInBytes - Offset - getLoadedSize();
7992     return Offset;
7993   }
7994
7995   /// \brief Generate the sequence of instructions to load the slice
7996   /// represented by this object and redirect the uses of this slice to
7997   /// this new sequence of instructions.
7998   /// \pre this->Inst && this->Origin are valid Instructions and this
7999   /// object passed the legal check: LoadedSlice::isLegal returned true.
8000   /// \return The last instruction of the sequence used to load the slice.
8001   SDValue loadSlice() const {
8002     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8003     const SDValue &OldBaseAddr = Origin->getBasePtr();
8004     SDValue BaseAddr = OldBaseAddr;
8005     // Get the offset in that chunk of bytes w.r.t. the endianess.
8006     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8007     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8008     if (Offset) {
8009       // BaseAddr = BaseAddr + Offset.
8010       EVT ArithType = BaseAddr.getValueType();
8011       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8012                               DAG->getConstant(Offset, ArithType));
8013     }
8014
8015     // Create the type of the loaded slice according to its size.
8016     EVT SliceType = getLoadedType();
8017
8018     // Create the load for the slice.
8019     SDValue LastInst = DAG->getLoad(
8020         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8021         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8022         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8023     // If the final type is not the same as the loaded type, this means that
8024     // we have to pad with zero. Create a zero extend for that.
8025     EVT FinalType = Inst->getValueType(0);
8026     if (SliceType != FinalType)
8027       LastInst =
8028           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8029     return LastInst;
8030   }
8031
8032   /// \brief Check if this slice can be merged with an expensive cross register
8033   /// bank copy. E.g.,
8034   /// i = load i32
8035   /// f = bitcast i32 i to float
8036   bool canMergeExpensiveCrossRegisterBankCopy() const {
8037     if (!Inst || !Inst->hasOneUse())
8038       return false;
8039     SDNode *Use = *Inst->use_begin();
8040     if (Use->getOpcode() != ISD::BITCAST)
8041       return false;
8042     assert(DAG && "Missing context");
8043     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8044     EVT ResVT = Use->getValueType(0);
8045     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8046     const TargetRegisterClass *ArgRC =
8047         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8048     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8049       return false;
8050
8051     // At this point, we know that we perform a cross-register-bank copy.
8052     // Check if it is expensive.
8053     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8054     // Assume bitcasts are cheap, unless both register classes do not
8055     // explicitly share a common sub class.
8056     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8057       return false;
8058
8059     // Check if it will be merged with the load.
8060     // 1. Check the alignment constraint.
8061     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8062         ResVT.getTypeForEVT(*DAG->getContext()));
8063
8064     if (RequiredAlignment > getAlignment())
8065       return false;
8066
8067     // 2. Check that the load is a legal operation for that type.
8068     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8069       return false;
8070
8071     // 3. Check that we do not have a zext in the way.
8072     if (Inst->getValueType(0) != getLoadedType())
8073       return false;
8074
8075     return true;
8076   }
8077 };
8078 }
8079
8080 /// \brief Sorts LoadedSlice according to their offset.
8081 struct LoadedSliceSorter {
8082   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8083     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8084     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8085   }
8086 };
8087
8088 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8089 /// \p UsedBits looks like 0..0 1..1 0..0.
8090 static bool areUsedBitsDense(const APInt &UsedBits) {
8091   // If all the bits are one, this is dense!
8092   if (UsedBits.isAllOnesValue())
8093     return true;
8094
8095   // Get rid of the unused bits on the right.
8096   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8097   // Get rid of the unused bits on the left.
8098   if (NarrowedUsedBits.countLeadingZeros())
8099     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8100   // Check that the chunk of bits is completely used.
8101   return NarrowedUsedBits.isAllOnesValue();
8102 }
8103
8104 /// \brief Check whether or not \p First and \p Second are next to each other
8105 /// in memory. This means that there is no hole between the bits loaded
8106 /// by \p First and the bits loaded by \p Second.
8107 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8108                                      const LoadedSlice &Second) {
8109   assert(First.Origin == Second.Origin && First.Origin &&
8110          "Unable to match different memory origins.");
8111   APInt UsedBits = First.getUsedBits();
8112   assert((UsedBits & Second.getUsedBits()) == 0 &&
8113          "Slices are not supposed to overlap.");
8114   UsedBits |= Second.getUsedBits();
8115   return areUsedBitsDense(UsedBits);
8116 }
8117
8118 /// \brief Adjust the \p GlobalLSCost according to the target
8119 /// paring capabilities and the layout of the slices.
8120 /// \pre \p GlobalLSCost should account for at least as many loads as
8121 /// there is in the slices in \p LoadedSlices.
8122 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8123                                  LoadedSlice::Cost &GlobalLSCost) {
8124   unsigned NumberOfSlices = LoadedSlices.size();
8125   // If there is less than 2 elements, no pairing is possible.
8126   if (NumberOfSlices < 2)
8127     return;
8128
8129   // Sort the slices so that elements that are likely to be next to each
8130   // other in memory are next to each other in the list.
8131   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8132   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8133   // First (resp. Second) is the first (resp. Second) potentially candidate
8134   // to be placed in a paired load.
8135   const LoadedSlice *First = NULL;
8136   const LoadedSlice *Second = NULL;
8137   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8138                 // Set the beginning of the pair.
8139                                                            First = Second) {
8140
8141     Second = &LoadedSlices[CurrSlice];
8142
8143     // If First is NULL, it means we start a new pair.
8144     // Get to the next slice.
8145     if (!First)
8146       continue;
8147
8148     EVT LoadedType = First->getLoadedType();
8149
8150     // If the types of the slices are different, we cannot pair them.
8151     if (LoadedType != Second->getLoadedType())
8152       continue;
8153
8154     // Check if the target supplies paired loads for this type.
8155     unsigned RequiredAlignment = 0;
8156     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8157       // move to the next pair, this type is hopeless.
8158       Second = NULL;
8159       continue;
8160     }
8161     // Check if we meet the alignment requirement.
8162     if (RequiredAlignment > First->getAlignment())
8163       continue;
8164
8165     // Check that both loads are next to each other in memory.
8166     if (!areSlicesNextToEachOther(*First, *Second))
8167       continue;
8168
8169     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8170     --GlobalLSCost.Loads;
8171     // Move to the next pair.
8172     Second = NULL;
8173   }
8174 }
8175
8176 /// \brief Check the profitability of all involved LoadedSlice.
8177 /// Currently, it is considered profitable if there is exactly two
8178 /// involved slices (1) which are (2) next to each other in memory, and
8179 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8180 ///
8181 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8182 /// the elements themselves.
8183 ///
8184 /// FIXME: When the cost model will be mature enough, we can relax
8185 /// constraints (1) and (2).
8186 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8187                                 const APInt &UsedBits, bool ForCodeSize) {
8188   unsigned NumberOfSlices = LoadedSlices.size();
8189   if (StressLoadSlicing)
8190     return NumberOfSlices > 1;
8191
8192   // Check (1).
8193   if (NumberOfSlices != 2)
8194     return false;
8195
8196   // Check (2).
8197   if (!areUsedBitsDense(UsedBits))
8198     return false;
8199
8200   // Check (3).
8201   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8202   // The original code has one big load.
8203   OrigCost.Loads = 1;
8204   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8205     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8206     // Accumulate the cost of all the slices.
8207     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8208     GlobalSlicingCost += SliceCost;
8209
8210     // Account as cost in the original configuration the gain obtained
8211     // with the current slices.
8212     OrigCost.addSliceGain(LS);
8213   }
8214
8215   // If the target supports paired load, adjust the cost accordingly.
8216   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8217   return OrigCost > GlobalSlicingCost;
8218 }
8219
8220 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8221 /// operations, split it in the various pieces being extracted.
8222 ///
8223 /// This sort of thing is introduced by SROA.
8224 /// This slicing takes care not to insert overlapping loads.
8225 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8226 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8227   if (Level < AfterLegalizeDAG)
8228     return false;
8229
8230   LoadSDNode *LD = cast<LoadSDNode>(N);
8231   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8232       !LD->getValueType(0).isInteger())
8233     return false;
8234
8235   // Keep track of already used bits to detect overlapping values.
8236   // In that case, we will just abort the transformation.
8237   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8238
8239   SmallVector<LoadedSlice, 4> LoadedSlices;
8240
8241   // Check if this load is used as several smaller chunks of bits.
8242   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8243   // of computation for each trunc.
8244   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8245        UI != UIEnd; ++UI) {
8246     // Skip the uses of the chain.
8247     if (UI.getUse().getResNo() != 0)
8248       continue;
8249
8250     SDNode *User = *UI;
8251     unsigned Shift = 0;
8252
8253     // Check if this is a trunc(lshr).
8254     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8255         isa<ConstantSDNode>(User->getOperand(1))) {
8256       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8257       User = *User->use_begin();
8258     }
8259
8260     // At this point, User is a Truncate, iff we encountered, trunc or
8261     // trunc(lshr).
8262     if (User->getOpcode() != ISD::TRUNCATE)
8263       return false;
8264
8265     // The width of the type must be a power of 2 and greater than 8-bits.
8266     // Otherwise the load cannot be represented in LLVM IR.
8267     // Moreover, if we shifted with a non-8-bits multiple, the slice
8268     // will be across several bytes. We do not support that.
8269     unsigned Width = User->getValueSizeInBits(0);
8270     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8271       return 0;
8272
8273     // Build the slice for this chain of computations.
8274     LoadedSlice LS(User, LD, Shift, &DAG);
8275     APInt CurrentUsedBits = LS.getUsedBits();
8276
8277     // Check if this slice overlaps with another.
8278     if ((CurrentUsedBits & UsedBits) != 0)
8279       return false;
8280     // Update the bits used globally.
8281     UsedBits |= CurrentUsedBits;
8282
8283     // Check if the new slice would be legal.
8284     if (!LS.isLegal())
8285       return false;
8286
8287     // Record the slice.
8288     LoadedSlices.push_back(LS);
8289   }
8290
8291   // Abort slicing if it does not seem to be profitable.
8292   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8293     return false;
8294
8295   ++SlicedLoads;
8296
8297   // Rewrite each chain to use an independent load.
8298   // By construction, each chain can be represented by a unique load.
8299
8300   // Prepare the argument for the new token factor for all the slices.
8301   SmallVector<SDValue, 8> ArgChains;
8302   for (SmallVectorImpl<LoadedSlice>::const_iterator
8303            LSIt = LoadedSlices.begin(),
8304            LSItEnd = LoadedSlices.end();
8305        LSIt != LSItEnd; ++LSIt) {
8306     SDValue SliceInst = LSIt->loadSlice();
8307     CombineTo(LSIt->Inst, SliceInst, true);
8308     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8309       SliceInst = SliceInst.getOperand(0);
8310     assert(SliceInst->getOpcode() == ISD::LOAD &&
8311            "It takes more than a zext to get to the loaded slice!!");
8312     ArgChains.push_back(SliceInst.getValue(1));
8313   }
8314
8315   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8316                               &ArgChains[0], ArgChains.size());
8317   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8318   return true;
8319 }
8320
8321 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8322 /// load is having specific bytes cleared out.  If so, return the byte size
8323 /// being masked out and the shift amount.
8324 static std::pair<unsigned, unsigned>
8325 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8326   std::pair<unsigned, unsigned> Result(0, 0);
8327
8328   // Check for the structure we're looking for.
8329   if (V->getOpcode() != ISD::AND ||
8330       !isa<ConstantSDNode>(V->getOperand(1)) ||
8331       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8332     return Result;
8333
8334   // Check the chain and pointer.
8335   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8336   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8337
8338   // The store should be chained directly to the load or be an operand of a
8339   // tokenfactor.
8340   if (LD == Chain.getNode())
8341     ; // ok.
8342   else if (Chain->getOpcode() != ISD::TokenFactor)
8343     return Result; // Fail.
8344   else {
8345     bool isOk = false;
8346     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8347       if (Chain->getOperand(i).getNode() == LD) {
8348         isOk = true;
8349         break;
8350       }
8351     if (!isOk) return Result;
8352   }
8353
8354   // This only handles simple types.
8355   if (V.getValueType() != MVT::i16 &&
8356       V.getValueType() != MVT::i32 &&
8357       V.getValueType() != MVT::i64)
8358     return Result;
8359
8360   // Check the constant mask.  Invert it so that the bits being masked out are
8361   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8362   // follow the sign bit for uniformity.
8363   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8364   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8365   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8366   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8367   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8368   if (NotMaskLZ == 64) return Result;  // All zero mask.
8369
8370   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8371   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8372     return Result;
8373
8374   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8375   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8376     NotMaskLZ -= 64-V.getValueSizeInBits();
8377
8378   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8379   switch (MaskedBytes) {
8380   case 1:
8381   case 2:
8382   case 4: break;
8383   default: return Result; // All one mask, or 5-byte mask.
8384   }
8385
8386   // Verify that the first bit starts at a multiple of mask so that the access
8387   // is aligned the same as the access width.
8388   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8389
8390   Result.first = MaskedBytes;
8391   Result.second = NotMaskTZ/8;
8392   return Result;
8393 }
8394
8395
8396 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8397 /// provides a value as specified by MaskInfo.  If so, replace the specified
8398 /// store with a narrower store of truncated IVal.
8399 static SDNode *
8400 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8401                                 SDValue IVal, StoreSDNode *St,
8402                                 DAGCombiner *DC) {
8403   unsigned NumBytes = MaskInfo.first;
8404   unsigned ByteShift = MaskInfo.second;
8405   SelectionDAG &DAG = DC->getDAG();
8406
8407   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8408   // that uses this.  If not, this is not a replacement.
8409   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8410                                   ByteShift*8, (ByteShift+NumBytes)*8);
8411   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8412
8413   // Check that it is legal on the target to do this.  It is legal if the new
8414   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8415   // legalization.
8416   MVT VT = MVT::getIntegerVT(NumBytes*8);
8417   if (!DC->isTypeLegal(VT))
8418     return 0;
8419
8420   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8421   // shifted by ByteShift and truncated down to NumBytes.
8422   if (ByteShift)
8423     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8424                        DAG.getConstant(ByteShift*8,
8425                                     DC->getShiftAmountTy(IVal.getValueType())));
8426
8427   // Figure out the offset for the store and the alignment of the access.
8428   unsigned StOffset;
8429   unsigned NewAlign = St->getAlignment();
8430
8431   if (DAG.getTargetLoweringInfo().isLittleEndian())
8432     StOffset = ByteShift;
8433   else
8434     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8435
8436   SDValue Ptr = St->getBasePtr();
8437   if (StOffset) {
8438     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8439                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8440     NewAlign = MinAlign(NewAlign, StOffset);
8441   }
8442
8443   // Truncate down to the new size.
8444   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8445
8446   ++OpsNarrowed;
8447   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8448                       St->getPointerInfo().getWithOffset(StOffset),
8449                       false, false, NewAlign).getNode();
8450 }
8451
8452
8453 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8454 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8455 /// of the loaded bits, try narrowing the load and store if it would end up
8456 /// being a win for performance or code size.
8457 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8458   StoreSDNode *ST  = cast<StoreSDNode>(N);
8459   if (ST->isVolatile())
8460     return SDValue();
8461
8462   SDValue Chain = ST->getChain();
8463   SDValue Value = ST->getValue();
8464   SDValue Ptr   = ST->getBasePtr();
8465   EVT VT = Value.getValueType();
8466
8467   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8468     return SDValue();
8469
8470   unsigned Opc = Value.getOpcode();
8471
8472   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8473   // is a byte mask indicating a consecutive number of bytes, check to see if
8474   // Y is known to provide just those bytes.  If so, we try to replace the
8475   // load + replace + store sequence with a single (narrower) store, which makes
8476   // the load dead.
8477   if (Opc == ISD::OR) {
8478     std::pair<unsigned, unsigned> MaskedLoad;
8479     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8480     if (MaskedLoad.first)
8481       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8482                                                   Value.getOperand(1), ST,this))
8483         return SDValue(NewST, 0);
8484
8485     // Or is commutative, so try swapping X and Y.
8486     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8487     if (MaskedLoad.first)
8488       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8489                                                   Value.getOperand(0), ST,this))
8490         return SDValue(NewST, 0);
8491   }
8492
8493   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8494       Value.getOperand(1).getOpcode() != ISD::Constant)
8495     return SDValue();
8496
8497   SDValue N0 = Value.getOperand(0);
8498   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8499       Chain == SDValue(N0.getNode(), 1)) {
8500     LoadSDNode *LD = cast<LoadSDNode>(N0);
8501     if (LD->getBasePtr() != Ptr ||
8502         LD->getPointerInfo().getAddrSpace() !=
8503         ST->getPointerInfo().getAddrSpace())
8504       return SDValue();
8505
8506     // Find the type to narrow it the load / op / store to.
8507     SDValue N1 = Value.getOperand(1);
8508     unsigned BitWidth = N1.getValueSizeInBits();
8509     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8510     if (Opc == ISD::AND)
8511       Imm ^= APInt::getAllOnesValue(BitWidth);
8512     if (Imm == 0 || Imm.isAllOnesValue())
8513       return SDValue();
8514     unsigned ShAmt = Imm.countTrailingZeros();
8515     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8516     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8517     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8518     while (NewBW < BitWidth &&
8519            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8520              TLI.isNarrowingProfitable(VT, NewVT))) {
8521       NewBW = NextPowerOf2(NewBW);
8522       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8523     }
8524     if (NewBW >= BitWidth)
8525       return SDValue();
8526
8527     // If the lsb changed does not start at the type bitwidth boundary,
8528     // start at the previous one.
8529     if (ShAmt % NewBW)
8530       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8531     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8532                                    std::min(BitWidth, ShAmt + NewBW));
8533     if ((Imm & Mask) == Imm) {
8534       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8535       if (Opc == ISD::AND)
8536         NewImm ^= APInt::getAllOnesValue(NewBW);
8537       uint64_t PtrOff = ShAmt / 8;
8538       // For big endian targets, we need to adjust the offset to the pointer to
8539       // load the correct bytes.
8540       if (TLI.isBigEndian())
8541         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8542
8543       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8544       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8545       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8546         return SDValue();
8547
8548       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8549                                    Ptr.getValueType(), Ptr,
8550                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8551       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8552                                   LD->getChain(), NewPtr,
8553                                   LD->getPointerInfo().getWithOffset(PtrOff),
8554                                   LD->isVolatile(), LD->isNonTemporal(),
8555                                   LD->isInvariant(), NewAlign,
8556                                   LD->getTBAAInfo());
8557       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8558                                    DAG.getConstant(NewImm, NewVT));
8559       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8560                                    NewVal, NewPtr,
8561                                    ST->getPointerInfo().getWithOffset(PtrOff),
8562                                    false, false, NewAlign);
8563
8564       AddToWorkList(NewPtr.getNode());
8565       AddToWorkList(NewLD.getNode());
8566       AddToWorkList(NewVal.getNode());
8567       WorkListRemover DeadNodes(*this);
8568       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8569       ++OpsNarrowed;
8570       return NewST;
8571     }
8572   }
8573
8574   return SDValue();
8575 }
8576
8577 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8578 /// if the load value isn't used by any other operations, then consider
8579 /// transforming the pair to integer load / store operations if the target
8580 /// deems the transformation profitable.
8581 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8582   StoreSDNode *ST  = cast<StoreSDNode>(N);
8583   SDValue Chain = ST->getChain();
8584   SDValue Value = ST->getValue();
8585   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8586       Value.hasOneUse() &&
8587       Chain == SDValue(Value.getNode(), 1)) {
8588     LoadSDNode *LD = cast<LoadSDNode>(Value);
8589     EVT VT = LD->getMemoryVT();
8590     if (!VT.isFloatingPoint() ||
8591         VT != ST->getMemoryVT() ||
8592         LD->isNonTemporal() ||
8593         ST->isNonTemporal() ||
8594         LD->getPointerInfo().getAddrSpace() != 0 ||
8595         ST->getPointerInfo().getAddrSpace() != 0)
8596       return SDValue();
8597
8598     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8599     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8600         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8601         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8602         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8603       return SDValue();
8604
8605     unsigned LDAlign = LD->getAlignment();
8606     unsigned STAlign = ST->getAlignment();
8607     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8608     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8609     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8610       return SDValue();
8611
8612     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8613                                 LD->getChain(), LD->getBasePtr(),
8614                                 LD->getPointerInfo(),
8615                                 false, false, false, LDAlign);
8616
8617     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8618                                  NewLD, ST->getBasePtr(),
8619                                  ST->getPointerInfo(),
8620                                  false, false, STAlign);
8621
8622     AddToWorkList(NewLD.getNode());
8623     AddToWorkList(NewST.getNode());
8624     WorkListRemover DeadNodes(*this);
8625     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8626     ++LdStFP2Int;
8627     return NewST;
8628   }
8629
8630   return SDValue();
8631 }
8632
8633 /// Helper struct to parse and store a memory address as base + index + offset.
8634 /// We ignore sign extensions when it is safe to do so.
8635 /// The following two expressions are not equivalent. To differentiate we need
8636 /// to store whether there was a sign extension involved in the index
8637 /// computation.
8638 ///  (load (i64 add (i64 copyfromreg %c)
8639 ///                 (i64 signextend (add (i8 load %index)
8640 ///                                      (i8 1))))
8641 /// vs
8642 ///
8643 /// (load (i64 add (i64 copyfromreg %c)
8644 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8645 ///                                         (i32 1)))))
8646 struct BaseIndexOffset {
8647   SDValue Base;
8648   SDValue Index;
8649   int64_t Offset;
8650   bool IsIndexSignExt;
8651
8652   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8653
8654   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8655                   bool IsIndexSignExt) :
8656     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8657
8658   bool equalBaseIndex(const BaseIndexOffset &Other) {
8659     return Other.Base == Base && Other.Index == Index &&
8660       Other.IsIndexSignExt == IsIndexSignExt;
8661   }
8662
8663   /// Parses tree in Ptr for base, index, offset addresses.
8664   static BaseIndexOffset match(SDValue Ptr) {
8665     bool IsIndexSignExt = false;
8666
8667     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8668     // instruction, then it could be just the BASE or everything else we don't
8669     // know how to handle. Just use Ptr as BASE and give up.
8670     if (Ptr->getOpcode() != ISD::ADD)
8671       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8672
8673     // We know that we have at least an ADD instruction. Try to pattern match
8674     // the simple case of BASE + OFFSET.
8675     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8676       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8677       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8678                               IsIndexSignExt);
8679     }
8680
8681     // Inside a loop the current BASE pointer is calculated using an ADD and a
8682     // MUL instruction. In this case Ptr is the actual BASE pointer.
8683     // (i64 add (i64 %array_ptr)
8684     //          (i64 mul (i64 %induction_var)
8685     //                   (i64 %element_size)))
8686     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8687       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8688
8689     // Look at Base + Index + Offset cases.
8690     SDValue Base = Ptr->getOperand(0);
8691     SDValue IndexOffset = Ptr->getOperand(1);
8692
8693     // Skip signextends.
8694     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8695       IndexOffset = IndexOffset->getOperand(0);
8696       IsIndexSignExt = true;
8697     }
8698
8699     // Either the case of Base + Index (no offset) or something else.
8700     if (IndexOffset->getOpcode() != ISD::ADD)
8701       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8702
8703     // Now we have the case of Base + Index + offset.
8704     SDValue Index = IndexOffset->getOperand(0);
8705     SDValue Offset = IndexOffset->getOperand(1);
8706
8707     if (!isa<ConstantSDNode>(Offset))
8708       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8709
8710     // Ignore signextends.
8711     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8712       Index = Index->getOperand(0);
8713       IsIndexSignExt = true;
8714     } else IsIndexSignExt = false;
8715
8716     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8717     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8718   }
8719 };
8720
8721 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8722 /// is located in a sequence of memory operations connected by a chain.
8723 struct MemOpLink {
8724   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8725     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8726   // Ptr to the mem node.
8727   LSBaseSDNode *MemNode;
8728   // Offset from the base ptr.
8729   int64_t OffsetFromBase;
8730   // What is the sequence number of this mem node.
8731   // Lowest mem operand in the DAG starts at zero.
8732   unsigned SequenceNum;
8733 };
8734
8735 /// Sorts store nodes in a link according to their offset from a shared
8736 // base ptr.
8737 struct ConsecutiveMemoryChainSorter {
8738   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8739     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8740   }
8741 };
8742
8743 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8744   EVT MemVT = St->getMemoryVT();
8745   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8746   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8747     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8748
8749   // Don't merge vectors into wider inputs.
8750   if (MemVT.isVector() || !MemVT.isSimple())
8751     return false;
8752
8753   // Perform an early exit check. Do not bother looking at stored values that
8754   // are not constants or loads.
8755   SDValue StoredVal = St->getValue();
8756   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8757   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8758       !IsLoadSrc)
8759     return false;
8760
8761   // Only look at ends of store sequences.
8762   SDValue Chain = SDValue(St, 1);
8763   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8764     return false;
8765
8766   // This holds the base pointer, index, and the offset in bytes from the base
8767   // pointer.
8768   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8769
8770   // We must have a base and an offset.
8771   if (!BasePtr.Base.getNode())
8772     return false;
8773
8774   // Do not handle stores to undef base pointers.
8775   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8776     return false;
8777
8778   // Save the LoadSDNodes that we find in the chain.
8779   // We need to make sure that these nodes do not interfere with
8780   // any of the store nodes.
8781   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8782
8783   // Save the StoreSDNodes that we find in the chain.
8784   SmallVector<MemOpLink, 8> StoreNodes;
8785
8786   // Walk up the chain and look for nodes with offsets from the same
8787   // base pointer. Stop when reaching an instruction with a different kind
8788   // or instruction which has a different base pointer.
8789   unsigned Seq = 0;
8790   StoreSDNode *Index = St;
8791   while (Index) {
8792     // If the chain has more than one use, then we can't reorder the mem ops.
8793     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8794       break;
8795
8796     // Find the base pointer and offset for this memory node.
8797     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8798
8799     // Check that the base pointer is the same as the original one.
8800     if (!Ptr.equalBaseIndex(BasePtr))
8801       break;
8802
8803     // Check that the alignment is the same.
8804     if (Index->getAlignment() != St->getAlignment())
8805       break;
8806
8807     // The memory operands must not be volatile.
8808     if (Index->isVolatile() || Index->isIndexed())
8809       break;
8810
8811     // No truncation.
8812     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8813       if (St->isTruncatingStore())
8814         break;
8815
8816     // The stored memory type must be the same.
8817     if (Index->getMemoryVT() != MemVT)
8818       break;
8819
8820     // We do not allow unaligned stores because we want to prevent overriding
8821     // stores.
8822     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8823       break;
8824
8825     // We found a potential memory operand to merge.
8826     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8827
8828     // Find the next memory operand in the chain. If the next operand in the
8829     // chain is a store then move up and continue the scan with the next
8830     // memory operand. If the next operand is a load save it and use alias
8831     // information to check if it interferes with anything.
8832     SDNode *NextInChain = Index->getChain().getNode();
8833     while (1) {
8834       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8835         // We found a store node. Use it for the next iteration.
8836         Index = STn;
8837         break;
8838       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8839         if (Ldn->isVolatile()) {
8840           Index = NULL;
8841           break;
8842         }
8843
8844         // Save the load node for later. Continue the scan.
8845         AliasLoadNodes.push_back(Ldn);
8846         NextInChain = Ldn->getChain().getNode();
8847         continue;
8848       } else {
8849         Index = NULL;
8850         break;
8851       }
8852     }
8853   }
8854
8855   // Check if there is anything to merge.
8856   if (StoreNodes.size() < 2)
8857     return false;
8858
8859   // Sort the memory operands according to their distance from the base pointer.
8860   std::sort(StoreNodes.begin(), StoreNodes.end(),
8861             ConsecutiveMemoryChainSorter());
8862
8863   // Scan the memory operations on the chain and find the first non-consecutive
8864   // store memory address.
8865   unsigned LastConsecutiveStore = 0;
8866   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8867   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8868
8869     // Check that the addresses are consecutive starting from the second
8870     // element in the list of stores.
8871     if (i > 0) {
8872       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8873       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8874         break;
8875     }
8876
8877     bool Alias = false;
8878     // Check if this store interferes with any of the loads that we found.
8879     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8880       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8881         Alias = true;
8882         break;
8883       }
8884     // We found a load that alias with this store. Stop the sequence.
8885     if (Alias)
8886       break;
8887
8888     // Mark this node as useful.
8889     LastConsecutiveStore = i;
8890   }
8891
8892   // The node with the lowest store address.
8893   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8894
8895   // Store the constants into memory as one consecutive store.
8896   if (!IsLoadSrc) {
8897     unsigned LastLegalType = 0;
8898     unsigned LastLegalVectorType = 0;
8899     bool NonZero = false;
8900     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8901       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8902       SDValue StoredVal = St->getValue();
8903
8904       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8905         NonZero |= !C->isNullValue();
8906       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8907         NonZero |= !C->getConstantFPValue()->isNullValue();
8908       } else {
8909         // Non-constant.
8910         break;
8911       }
8912
8913       // Find a legal type for the constant store.
8914       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8915       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8916       if (TLI.isTypeLegal(StoreTy))
8917         LastLegalType = i+1;
8918       // Or check whether a truncstore is legal.
8919       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8920                TargetLowering::TypePromoteInteger) {
8921         EVT LegalizedStoredValueTy =
8922           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8923         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8924           LastLegalType = i+1;
8925       }
8926
8927       // Find a legal type for the vector store.
8928       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8929       if (TLI.isTypeLegal(Ty))
8930         LastLegalVectorType = i + 1;
8931     }
8932
8933     // We only use vectors if the constant is known to be zero and the
8934     // function is not marked with the noimplicitfloat attribute.
8935     if (NonZero || NoVectors)
8936       LastLegalVectorType = 0;
8937
8938     // Check if we found a legal integer type to store.
8939     if (LastLegalType == 0 && LastLegalVectorType == 0)
8940       return false;
8941
8942     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8943     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8944
8945     // Make sure we have something to merge.
8946     if (NumElem < 2)
8947       return false;
8948
8949     unsigned EarliestNodeUsed = 0;
8950     for (unsigned i=0; i < NumElem; ++i) {
8951       // Find a chain for the new wide-store operand. Notice that some
8952       // of the store nodes that we found may not be selected for inclusion
8953       // in the wide store. The chain we use needs to be the chain of the
8954       // earliest store node which is *used* and replaced by the wide store.
8955       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8956         EarliestNodeUsed = i;
8957     }
8958
8959     // The earliest Node in the DAG.
8960     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8961     SDLoc DL(StoreNodes[0].MemNode);
8962
8963     SDValue StoredVal;
8964     if (UseVector) {
8965       // Find a legal type for the vector store.
8966       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8967       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8968       StoredVal = DAG.getConstant(0, Ty);
8969     } else {
8970       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8971       APInt StoreInt(StoreBW, 0);
8972
8973       // Construct a single integer constant which is made of the smaller
8974       // constant inputs.
8975       bool IsLE = TLI.isLittleEndian();
8976       for (unsigned i = 0; i < NumElem ; ++i) {
8977         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8978         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8979         SDValue Val = St->getValue();
8980         StoreInt<<=ElementSizeBytes*8;
8981         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8982           StoreInt|=C->getAPIntValue().zext(StoreBW);
8983         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8984           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8985         } else {
8986           assert(false && "Invalid constant element type");
8987         }
8988       }
8989
8990       // Create the new Load and Store operations.
8991       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8992       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8993     }
8994
8995     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8996                                     FirstInChain->getBasePtr(),
8997                                     FirstInChain->getPointerInfo(),
8998                                     false, false,
8999                                     FirstInChain->getAlignment());
9000
9001     // Replace the first store with the new store
9002     CombineTo(EarliestOp, NewStore);
9003     // Erase all other stores.
9004     for (unsigned i = 0; i < NumElem ; ++i) {
9005       if (StoreNodes[i].MemNode == EarliestOp)
9006         continue;
9007       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9008       // ReplaceAllUsesWith will replace all uses that existed when it was
9009       // called, but graph optimizations may cause new ones to appear. For
9010       // example, the case in pr14333 looks like
9011       //
9012       //  St's chain -> St -> another store -> X
9013       //
9014       // And the only difference from St to the other store is the chain.
9015       // When we change it's chain to be St's chain they become identical,
9016       // get CSEed and the net result is that X is now a use of St.
9017       // Since we know that St is redundant, just iterate.
9018       while (!St->use_empty())
9019         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9020       removeFromWorkList(St);
9021       DAG.DeleteNode(St);
9022     }
9023
9024     return true;
9025   }
9026
9027   // Below we handle the case of multiple consecutive stores that
9028   // come from multiple consecutive loads. We merge them into a single
9029   // wide load and a single wide store.
9030
9031   // Look for load nodes which are used by the stored values.
9032   SmallVector<MemOpLink, 8> LoadNodes;
9033
9034   // Find acceptable loads. Loads need to have the same chain (token factor),
9035   // must not be zext, volatile, indexed, and they must be consecutive.
9036   BaseIndexOffset LdBasePtr;
9037   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9038     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9039     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9040     if (!Ld) break;
9041
9042     // Loads must only have one use.
9043     if (!Ld->hasNUsesOfValue(1, 0))
9044       break;
9045
9046     // Check that the alignment is the same as the stores.
9047     if (Ld->getAlignment() != St->getAlignment())
9048       break;
9049
9050     // The memory operands must not be volatile.
9051     if (Ld->isVolatile() || Ld->isIndexed())
9052       break;
9053
9054     // We do not accept ext loads.
9055     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9056       break;
9057
9058     // The stored memory type must be the same.
9059     if (Ld->getMemoryVT() != MemVT)
9060       break;
9061
9062     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9063     // If this is not the first ptr that we check.
9064     if (LdBasePtr.Base.getNode()) {
9065       // The base ptr must be the same.
9066       if (!LdPtr.equalBaseIndex(LdBasePtr))
9067         break;
9068     } else {
9069       // Check that all other base pointers are the same as this one.
9070       LdBasePtr = LdPtr;
9071     }
9072
9073     // We found a potential memory operand to merge.
9074     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9075   }
9076
9077   if (LoadNodes.size() < 2)
9078     return false;
9079
9080   // Scan the memory operations on the chain and find the first non-consecutive
9081   // load memory address. These variables hold the index in the store node
9082   // array.
9083   unsigned LastConsecutiveLoad = 0;
9084   // This variable refers to the size and not index in the array.
9085   unsigned LastLegalVectorType = 0;
9086   unsigned LastLegalIntegerType = 0;
9087   StartAddress = LoadNodes[0].OffsetFromBase;
9088   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9089   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9090     // All loads much share the same chain.
9091     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9092       break;
9093
9094     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9095     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9096       break;
9097     LastConsecutiveLoad = i;
9098
9099     // Find a legal type for the vector store.
9100     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9101     if (TLI.isTypeLegal(StoreTy))
9102       LastLegalVectorType = i + 1;
9103
9104     // Find a legal type for the integer store.
9105     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9106     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9107     if (TLI.isTypeLegal(StoreTy))
9108       LastLegalIntegerType = i + 1;
9109     // Or check whether a truncstore and extload is legal.
9110     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9111              TargetLowering::TypePromoteInteger) {
9112       EVT LegalizedStoredValueTy =
9113         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9114       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9115           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9116           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9117           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9118         LastLegalIntegerType = i+1;
9119     }
9120   }
9121
9122   // Only use vector types if the vector type is larger than the integer type.
9123   // If they are the same, use integers.
9124   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9125   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9126
9127   // We add +1 here because the LastXXX variables refer to location while
9128   // the NumElem refers to array/index size.
9129   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9130   NumElem = std::min(LastLegalType, NumElem);
9131
9132   if (NumElem < 2)
9133     return false;
9134
9135   // The earliest Node in the DAG.
9136   unsigned EarliestNodeUsed = 0;
9137   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9138   for (unsigned i=1; i<NumElem; ++i) {
9139     // Find a chain for the new wide-store operand. Notice that some
9140     // of the store nodes that we found may not be selected for inclusion
9141     // in the wide store. The chain we use needs to be the chain of the
9142     // earliest store node which is *used* and replaced by the wide store.
9143     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9144       EarliestNodeUsed = i;
9145   }
9146
9147   // Find if it is better to use vectors or integers to load and store
9148   // to memory.
9149   EVT JointMemOpVT;
9150   if (UseVectorTy) {
9151     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9152   } else {
9153     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9154     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9155   }
9156
9157   SDLoc LoadDL(LoadNodes[0].MemNode);
9158   SDLoc StoreDL(StoreNodes[0].MemNode);
9159
9160   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9161   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9162                                 FirstLoad->getChain(),
9163                                 FirstLoad->getBasePtr(),
9164                                 FirstLoad->getPointerInfo(),
9165                                 false, false, false,
9166                                 FirstLoad->getAlignment());
9167
9168   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9169                                   FirstInChain->getBasePtr(),
9170                                   FirstInChain->getPointerInfo(), false, false,
9171                                   FirstInChain->getAlignment());
9172
9173   // Replace one of the loads with the new load.
9174   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9175   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9176                                 SDValue(NewLoad.getNode(), 1));
9177
9178   // Remove the rest of the load chains.
9179   for (unsigned i = 1; i < NumElem ; ++i) {
9180     // Replace all chain users of the old load nodes with the chain of the new
9181     // load node.
9182     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9183     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9184   }
9185
9186   // Replace the first store with the new store.
9187   CombineTo(EarliestOp, NewStore);
9188   // Erase all other stores.
9189   for (unsigned i = 0; i < NumElem ; ++i) {
9190     // Remove all Store nodes.
9191     if (StoreNodes[i].MemNode == EarliestOp)
9192       continue;
9193     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9194     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9195     removeFromWorkList(St);
9196     DAG.DeleteNode(St);
9197   }
9198
9199   return true;
9200 }
9201
9202 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9203   StoreSDNode *ST  = cast<StoreSDNode>(N);
9204   SDValue Chain = ST->getChain();
9205   SDValue Value = ST->getValue();
9206   SDValue Ptr   = ST->getBasePtr();
9207
9208   // If this is a store of a bit convert, store the input value if the
9209   // resultant store does not need a higher alignment than the original.
9210   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9211       ST->isUnindexed()) {
9212     unsigned OrigAlign = ST->getAlignment();
9213     EVT SVT = Value.getOperand(0).getValueType();
9214     unsigned Align = TLI.getDataLayout()->
9215       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9216     if (Align <= OrigAlign &&
9217         ((!LegalOperations && !ST->isVolatile()) ||
9218          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9219       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9220                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9221                           ST->isNonTemporal(), OrigAlign,
9222                           ST->getTBAAInfo());
9223   }
9224
9225   // Turn 'store undef, Ptr' -> nothing.
9226   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9227     return Chain;
9228
9229   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9230   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9231     // NOTE: If the original store is volatile, this transform must not increase
9232     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9233     // processor operation but an i64 (which is not legal) requires two.  So the
9234     // transform should not be done in this case.
9235     if (Value.getOpcode() != ISD::TargetConstantFP) {
9236       SDValue Tmp;
9237       switch (CFP->getSimpleValueType(0).SimpleTy) {
9238       default: llvm_unreachable("Unknown FP type");
9239       case MVT::f16:    // We don't do this for these yet.
9240       case MVT::f80:
9241       case MVT::f128:
9242       case MVT::ppcf128:
9243         break;
9244       case MVT::f32:
9245         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9246             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9247           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9248                               bitcastToAPInt().getZExtValue(), MVT::i32);
9249           return DAG.getStore(Chain, SDLoc(N), Tmp,
9250                               Ptr, ST->getMemOperand());
9251         }
9252         break;
9253       case MVT::f64:
9254         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9255              !ST->isVolatile()) ||
9256             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9257           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9258                                 getZExtValue(), MVT::i64);
9259           return DAG.getStore(Chain, SDLoc(N), Tmp,
9260                               Ptr, ST->getMemOperand());
9261         }
9262
9263         if (!ST->isVolatile() &&
9264             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9265           // Many FP stores are not made apparent until after legalize, e.g. for
9266           // argument passing.  Since this is so common, custom legalize the
9267           // 64-bit integer store into two 32-bit stores.
9268           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9269           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9270           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9271           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9272
9273           unsigned Alignment = ST->getAlignment();
9274           bool isVolatile = ST->isVolatile();
9275           bool isNonTemporal = ST->isNonTemporal();
9276           const MDNode *TBAAInfo = ST->getTBAAInfo();
9277
9278           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9279                                      Ptr, ST->getPointerInfo(),
9280                                      isVolatile, isNonTemporal,
9281                                      ST->getAlignment(), TBAAInfo);
9282           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9283                             DAG.getConstant(4, Ptr.getValueType()));
9284           Alignment = MinAlign(Alignment, 4U);
9285           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9286                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9287                                      isVolatile, isNonTemporal,
9288                                      Alignment, TBAAInfo);
9289           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9290                              St0, St1);
9291         }
9292
9293         break;
9294       }
9295     }
9296   }
9297
9298   // Try to infer better alignment information than the store already has.
9299   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9300     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9301       if (Align > ST->getAlignment())
9302         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9303                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9304                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9305                                  ST->getTBAAInfo());
9306     }
9307   }
9308
9309   // Try transforming a pair floating point load / store ops to integer
9310   // load / store ops.
9311   SDValue NewST = TransformFPLoadStorePair(N);
9312   if (NewST.getNode())
9313     return NewST;
9314
9315   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9316     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9317   if (UseAA && ST->isUnindexed()) {
9318     // Walk up chain skipping non-aliasing memory nodes.
9319     SDValue BetterChain = FindBetterChain(N, Chain);
9320
9321     // If there is a better chain.
9322     if (Chain != BetterChain) {
9323       SDValue ReplStore;
9324
9325       // Replace the chain to avoid dependency.
9326       if (ST->isTruncatingStore()) {
9327         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9328                                       ST->getMemoryVT(), ST->getMemOperand());
9329       } else {
9330         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9331                                  ST->getMemOperand());
9332       }
9333
9334       // Create token to keep both nodes around.
9335       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9336                                   MVT::Other, Chain, ReplStore);
9337
9338       // Make sure the new and old chains are cleaned up.
9339       AddToWorkList(Token.getNode());
9340
9341       // Don't add users to work list.
9342       return CombineTo(N, Token, false);
9343     }
9344   }
9345
9346   // Try transforming N to an indexed store.
9347   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9348     return SDValue(N, 0);
9349
9350   // FIXME: is there such a thing as a truncating indexed store?
9351   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9352       Value.getValueType().isInteger()) {
9353     // See if we can simplify the input to this truncstore with knowledge that
9354     // only the low bits are being used.  For example:
9355     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9356     SDValue Shorter =
9357       GetDemandedBits(Value,
9358                       APInt::getLowBitsSet(
9359                         Value.getValueType().getScalarType().getSizeInBits(),
9360                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9361     AddToWorkList(Value.getNode());
9362     if (Shorter.getNode())
9363       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9364                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9365
9366     // Otherwise, see if we can simplify the operation with
9367     // SimplifyDemandedBits, which only works if the value has a single use.
9368     if (SimplifyDemandedBits(Value,
9369                         APInt::getLowBitsSet(
9370                           Value.getValueType().getScalarType().getSizeInBits(),
9371                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9372       return SDValue(N, 0);
9373   }
9374
9375   // If this is a load followed by a store to the same location, then the store
9376   // is dead/noop.
9377   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9378     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9379         ST->isUnindexed() && !ST->isVolatile() &&
9380         // There can't be any side effects between the load and store, such as
9381         // a call or store.
9382         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9383       // The store is dead, remove it.
9384       return Chain;
9385     }
9386   }
9387
9388   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9389   // truncating store.  We can do this even if this is already a truncstore.
9390   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9391       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9392       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9393                             ST->getMemoryVT())) {
9394     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9395                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9396   }
9397
9398   // Only perform this optimization before the types are legal, because we
9399   // don't want to perform this optimization on every DAGCombine invocation.
9400   if (!LegalTypes) {
9401     bool EverChanged = false;
9402
9403     do {
9404       // There can be multiple store sequences on the same chain.
9405       // Keep trying to merge store sequences until we are unable to do so
9406       // or until we merge the last store on the chain.
9407       bool Changed = MergeConsecutiveStores(ST);
9408       EverChanged |= Changed;
9409       if (!Changed) break;
9410     } while (ST->getOpcode() != ISD::DELETED_NODE);
9411
9412     if (EverChanged)
9413       return SDValue(N, 0);
9414   }
9415
9416   return ReduceLoadOpStoreWidth(N);
9417 }
9418
9419 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9420   SDValue InVec = N->getOperand(0);
9421   SDValue InVal = N->getOperand(1);
9422   SDValue EltNo = N->getOperand(2);
9423   SDLoc dl(N);
9424
9425   // If the inserted element is an UNDEF, just use the input vector.
9426   if (InVal.getOpcode() == ISD::UNDEF)
9427     return InVec;
9428
9429   EVT VT = InVec.getValueType();
9430
9431   // If we can't generate a legal BUILD_VECTOR, exit
9432   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9433     return SDValue();
9434
9435   // Check that we know which element is being inserted
9436   if (!isa<ConstantSDNode>(EltNo))
9437     return SDValue();
9438   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9439
9440   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9441   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9442   // vector elements.
9443   SmallVector<SDValue, 8> Ops;
9444   // Do not combine these two vectors if the output vector will not replace
9445   // the input vector.
9446   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9447     Ops.append(InVec.getNode()->op_begin(),
9448                InVec.getNode()->op_end());
9449   } else if (InVec.getOpcode() == ISD::UNDEF) {
9450     unsigned NElts = VT.getVectorNumElements();
9451     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9452   } else {
9453     return SDValue();
9454   }
9455
9456   // Insert the element
9457   if (Elt < Ops.size()) {
9458     // All the operands of BUILD_VECTOR must have the same type;
9459     // we enforce that here.
9460     EVT OpVT = Ops[0].getValueType();
9461     if (InVal.getValueType() != OpVT)
9462       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9463                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9464                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9465     Ops[Elt] = InVal;
9466   }
9467
9468   // Return the new vector
9469   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9470                      VT, &Ops[0], Ops.size());
9471 }
9472
9473 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9474   // (vextract (scalar_to_vector val, 0) -> val
9475   SDValue InVec = N->getOperand(0);
9476   EVT VT = InVec.getValueType();
9477   EVT NVT = N->getValueType(0);
9478
9479   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9480     // Check if the result type doesn't match the inserted element type. A
9481     // SCALAR_TO_VECTOR may truncate the inserted element and the
9482     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9483     SDValue InOp = InVec.getOperand(0);
9484     if (InOp.getValueType() != NVT) {
9485       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9486       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9487     }
9488     return InOp;
9489   }
9490
9491   SDValue EltNo = N->getOperand(1);
9492   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9493
9494   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9495   // We only perform this optimization before the op legalization phase because
9496   // we may introduce new vector instructions which are not backed by TD
9497   // patterns. For example on AVX, extracting elements from a wide vector
9498   // without using extract_subvector.
9499   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9500       && ConstEltNo && !LegalOperations) {
9501     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9502     int NumElem = VT.getVectorNumElements();
9503     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9504     // Find the new index to extract from.
9505     int OrigElt = SVOp->getMaskElt(Elt);
9506
9507     // Extracting an undef index is undef.
9508     if (OrigElt == -1)
9509       return DAG.getUNDEF(NVT);
9510
9511     // Select the right vector half to extract from.
9512     if (OrigElt < NumElem) {
9513       InVec = InVec->getOperand(0);
9514     } else {
9515       InVec = InVec->getOperand(1);
9516       OrigElt -= NumElem;
9517     }
9518
9519     EVT IndexTy = TLI.getVectorIdxTy();
9520     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9521                        InVec, DAG.getConstant(OrigElt, IndexTy));
9522   }
9523
9524   // Perform only after legalization to ensure build_vector / vector_shuffle
9525   // optimizations have already been done.
9526   if (!LegalOperations) return SDValue();
9527
9528   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9529   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9530   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9531
9532   if (ConstEltNo) {
9533     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9534     bool NewLoad = false;
9535     bool BCNumEltsChanged = false;
9536     EVT ExtVT = VT.getVectorElementType();
9537     EVT LVT = ExtVT;
9538
9539     // If the result of load has to be truncated, then it's not necessarily
9540     // profitable.
9541     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9542       return SDValue();
9543
9544     if (InVec.getOpcode() == ISD::BITCAST) {
9545       // Don't duplicate a load with other uses.
9546       if (!InVec.hasOneUse())
9547         return SDValue();
9548
9549       EVT BCVT = InVec.getOperand(0).getValueType();
9550       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9551         return SDValue();
9552       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9553         BCNumEltsChanged = true;
9554       InVec = InVec.getOperand(0);
9555       ExtVT = BCVT.getVectorElementType();
9556       NewLoad = true;
9557     }
9558
9559     LoadSDNode *LN0 = NULL;
9560     const ShuffleVectorSDNode *SVN = NULL;
9561     if (ISD::isNormalLoad(InVec.getNode())) {
9562       LN0 = cast<LoadSDNode>(InVec);
9563     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9564                InVec.getOperand(0).getValueType() == ExtVT &&
9565                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9566       // Don't duplicate a load with other uses.
9567       if (!InVec.hasOneUse())
9568         return SDValue();
9569
9570       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9571     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9572       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9573       // =>
9574       // (load $addr+1*size)
9575
9576       // Don't duplicate a load with other uses.
9577       if (!InVec.hasOneUse())
9578         return SDValue();
9579
9580       // If the bit convert changed the number of elements, it is unsafe
9581       // to examine the mask.
9582       if (BCNumEltsChanged)
9583         return SDValue();
9584
9585       // Select the input vector, guarding against out of range extract vector.
9586       unsigned NumElems = VT.getVectorNumElements();
9587       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9588       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9589
9590       if (InVec.getOpcode() == ISD::BITCAST) {
9591         // Don't duplicate a load with other uses.
9592         if (!InVec.hasOneUse())
9593           return SDValue();
9594
9595         InVec = InVec.getOperand(0);
9596       }
9597       if (ISD::isNormalLoad(InVec.getNode())) {
9598         LN0 = cast<LoadSDNode>(InVec);
9599         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9600       }
9601     }
9602
9603     // Make sure we found a non-volatile load and the extractelement is
9604     // the only use.
9605     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9606       return SDValue();
9607
9608     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9609     if (Elt == -1)
9610       return DAG.getUNDEF(LVT);
9611
9612     unsigned Align = LN0->getAlignment();
9613     if (NewLoad) {
9614       // Check the resultant load doesn't need a higher alignment than the
9615       // original load.
9616       unsigned NewAlign =
9617         TLI.getDataLayout()
9618             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9619
9620       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9621         return SDValue();
9622
9623       Align = NewAlign;
9624     }
9625
9626     SDValue NewPtr = LN0->getBasePtr();
9627     unsigned PtrOff = 0;
9628
9629     if (Elt) {
9630       PtrOff = LVT.getSizeInBits() * Elt / 8;
9631       EVT PtrType = NewPtr.getValueType();
9632       if (TLI.isBigEndian())
9633         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9634       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9635                            DAG.getConstant(PtrOff, PtrType));
9636     }
9637
9638     // The replacement we need to do here is a little tricky: we need to
9639     // replace an extractelement of a load with a load.
9640     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9641     // Note that this replacement assumes that the extractvalue is the only
9642     // use of the load; that's okay because we don't want to perform this
9643     // transformation in other cases anyway.
9644     SDValue Load;
9645     SDValue Chain;
9646     if (NVT.bitsGT(LVT)) {
9647       // If the result type of vextract is wider than the load, then issue an
9648       // extending load instead.
9649       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9650         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9651       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9652                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9653                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9654                             Align, LN0->getTBAAInfo());
9655       Chain = Load.getValue(1);
9656     } else {
9657       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9658                          LN0->getPointerInfo().getWithOffset(PtrOff),
9659                          LN0->isVolatile(), LN0->isNonTemporal(),
9660                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9661       Chain = Load.getValue(1);
9662       if (NVT.bitsLT(LVT))
9663         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9664       else
9665         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9666     }
9667     WorkListRemover DeadNodes(*this);
9668     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9669     SDValue To[] = { Load, Chain };
9670     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9671     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9672     // worklist explicitly as well.
9673     AddToWorkList(Load.getNode());
9674     AddUsersToWorkList(Load.getNode()); // Add users too
9675     // Make sure to revisit this node to clean it up; it will usually be dead.
9676     AddToWorkList(N);
9677     return SDValue(N, 0);
9678   }
9679
9680   return SDValue();
9681 }
9682
9683 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9684 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9685   // We perform this optimization post type-legalization because
9686   // the type-legalizer often scalarizes integer-promoted vectors.
9687   // Performing this optimization before may create bit-casts which
9688   // will be type-legalized to complex code sequences.
9689   // We perform this optimization only before the operation legalizer because we
9690   // may introduce illegal operations.
9691   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9692     return SDValue();
9693
9694   unsigned NumInScalars = N->getNumOperands();
9695   SDLoc dl(N);
9696   EVT VT = N->getValueType(0);
9697
9698   // Check to see if this is a BUILD_VECTOR of a bunch of values
9699   // which come from any_extend or zero_extend nodes. If so, we can create
9700   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9701   // optimizations. We do not handle sign-extend because we can't fill the sign
9702   // using shuffles.
9703   EVT SourceType = MVT::Other;
9704   bool AllAnyExt = true;
9705
9706   for (unsigned i = 0; i != NumInScalars; ++i) {
9707     SDValue In = N->getOperand(i);
9708     // Ignore undef inputs.
9709     if (In.getOpcode() == ISD::UNDEF) continue;
9710
9711     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9712     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9713
9714     // Abort if the element is not an extension.
9715     if (!ZeroExt && !AnyExt) {
9716       SourceType = MVT::Other;
9717       break;
9718     }
9719
9720     // The input is a ZeroExt or AnyExt. Check the original type.
9721     EVT InTy = In.getOperand(0).getValueType();
9722
9723     // Check that all of the widened source types are the same.
9724     if (SourceType == MVT::Other)
9725       // First time.
9726       SourceType = InTy;
9727     else if (InTy != SourceType) {
9728       // Multiple income types. Abort.
9729       SourceType = MVT::Other;
9730       break;
9731     }
9732
9733     // Check if all of the extends are ANY_EXTENDs.
9734     AllAnyExt &= AnyExt;
9735   }
9736
9737   // In order to have valid types, all of the inputs must be extended from the
9738   // same source type and all of the inputs must be any or zero extend.
9739   // Scalar sizes must be a power of two.
9740   EVT OutScalarTy = VT.getScalarType();
9741   bool ValidTypes = SourceType != MVT::Other &&
9742                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9743                  isPowerOf2_32(SourceType.getSizeInBits());
9744
9745   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9746   // turn into a single shuffle instruction.
9747   if (!ValidTypes)
9748     return SDValue();
9749
9750   bool isLE = TLI.isLittleEndian();
9751   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9752   assert(ElemRatio > 1 && "Invalid element size ratio");
9753   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9754                                DAG.getConstant(0, SourceType);
9755
9756   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9757   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9758
9759   // Populate the new build_vector
9760   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9761     SDValue Cast = N->getOperand(i);
9762     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9763             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9764             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9765     SDValue In;
9766     if (Cast.getOpcode() == ISD::UNDEF)
9767       In = DAG.getUNDEF(SourceType);
9768     else
9769       In = Cast->getOperand(0);
9770     unsigned Index = isLE ? (i * ElemRatio) :
9771                             (i * ElemRatio + (ElemRatio - 1));
9772
9773     assert(Index < Ops.size() && "Invalid index");
9774     Ops[Index] = In;
9775   }
9776
9777   // The type of the new BUILD_VECTOR node.
9778   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9779   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9780          "Invalid vector size");
9781   // Check if the new vector type is legal.
9782   if (!isTypeLegal(VecVT)) return SDValue();
9783
9784   // Make the new BUILD_VECTOR.
9785   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9786
9787   // The new BUILD_VECTOR node has the potential to be further optimized.
9788   AddToWorkList(BV.getNode());
9789   // Bitcast to the desired type.
9790   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9791 }
9792
9793 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9794   EVT VT = N->getValueType(0);
9795
9796   unsigned NumInScalars = N->getNumOperands();
9797   SDLoc dl(N);
9798
9799   EVT SrcVT = MVT::Other;
9800   unsigned Opcode = ISD::DELETED_NODE;
9801   unsigned NumDefs = 0;
9802
9803   for (unsigned i = 0; i != NumInScalars; ++i) {
9804     SDValue In = N->getOperand(i);
9805     unsigned Opc = In.getOpcode();
9806
9807     if (Opc == ISD::UNDEF)
9808       continue;
9809
9810     // If all scalar values are floats and converted from integers.
9811     if (Opcode == ISD::DELETED_NODE &&
9812         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9813       Opcode = Opc;
9814     }
9815
9816     if (Opc != Opcode)
9817       return SDValue();
9818
9819     EVT InVT = In.getOperand(0).getValueType();
9820
9821     // If all scalar values are typed differently, bail out. It's chosen to
9822     // simplify BUILD_VECTOR of integer types.
9823     if (SrcVT == MVT::Other)
9824       SrcVT = InVT;
9825     if (SrcVT != InVT)
9826       return SDValue();
9827     NumDefs++;
9828   }
9829
9830   // If the vector has just one element defined, it's not worth to fold it into
9831   // a vectorized one.
9832   if (NumDefs < 2)
9833     return SDValue();
9834
9835   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9836          && "Should only handle conversion from integer to float.");
9837   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9838
9839   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9840
9841   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9842     return SDValue();
9843
9844   SmallVector<SDValue, 8> Opnds;
9845   for (unsigned i = 0; i != NumInScalars; ++i) {
9846     SDValue In = N->getOperand(i);
9847
9848     if (In.getOpcode() == ISD::UNDEF)
9849       Opnds.push_back(DAG.getUNDEF(SrcVT));
9850     else
9851       Opnds.push_back(In.getOperand(0));
9852   }
9853   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9854                            &Opnds[0], Opnds.size());
9855   AddToWorkList(BV.getNode());
9856
9857   return DAG.getNode(Opcode, dl, VT, BV);
9858 }
9859
9860 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9861   unsigned NumInScalars = N->getNumOperands();
9862   SDLoc dl(N);
9863   EVT VT = N->getValueType(0);
9864
9865   // A vector built entirely of undefs is undef.
9866   if (ISD::allOperandsUndef(N))
9867     return DAG.getUNDEF(VT);
9868
9869   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9870   if (V.getNode())
9871     return V;
9872
9873   V = reduceBuildVecConvertToConvertBuildVec(N);
9874   if (V.getNode())
9875     return V;
9876
9877   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9878   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9879   // at most two distinct vectors, turn this into a shuffle node.
9880
9881   // May only combine to shuffle after legalize if shuffle is legal.
9882   if (LegalOperations &&
9883       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9884     return SDValue();
9885
9886   SDValue VecIn1, VecIn2;
9887   for (unsigned i = 0; i != NumInScalars; ++i) {
9888     // Ignore undef inputs.
9889     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9890
9891     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9892     // constant index, bail out.
9893     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9894         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9895       VecIn1 = VecIn2 = SDValue(0, 0);
9896       break;
9897     }
9898
9899     // We allow up to two distinct input vectors.
9900     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9901     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9902       continue;
9903
9904     if (VecIn1.getNode() == 0) {
9905       VecIn1 = ExtractedFromVec;
9906     } else if (VecIn2.getNode() == 0) {
9907       VecIn2 = ExtractedFromVec;
9908     } else {
9909       // Too many inputs.
9910       VecIn1 = VecIn2 = SDValue(0, 0);
9911       break;
9912     }
9913   }
9914
9915     // If everything is good, we can make a shuffle operation.
9916   if (VecIn1.getNode()) {
9917     SmallVector<int, 8> Mask;
9918     for (unsigned i = 0; i != NumInScalars; ++i) {
9919       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9920         Mask.push_back(-1);
9921         continue;
9922       }
9923
9924       // If extracting from the first vector, just use the index directly.
9925       SDValue Extract = N->getOperand(i);
9926       SDValue ExtVal = Extract.getOperand(1);
9927       if (Extract.getOperand(0) == VecIn1) {
9928         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9929         if (ExtIndex > VT.getVectorNumElements())
9930           return SDValue();
9931
9932         Mask.push_back(ExtIndex);
9933         continue;
9934       }
9935
9936       // Otherwise, use InIdx + VecSize
9937       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9938       Mask.push_back(Idx+NumInScalars);
9939     }
9940
9941     // We can't generate a shuffle node with mismatched input and output types.
9942     // Attempt to transform a single input vector to the correct type.
9943     if ((VT != VecIn1.getValueType())) {
9944       // We don't support shuffeling between TWO values of different types.
9945       if (VecIn2.getNode() != 0)
9946         return SDValue();
9947
9948       // We only support widening of vectors which are half the size of the
9949       // output registers. For example XMM->YMM widening on X86 with AVX.
9950       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9951         return SDValue();
9952
9953       // If the input vector type has a different base type to the output
9954       // vector type, bail out.
9955       if (VecIn1.getValueType().getVectorElementType() !=
9956           VT.getVectorElementType())
9957         return SDValue();
9958
9959       // Widen the input vector by adding undef values.
9960       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9961                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9962     }
9963
9964     // If VecIn2 is unused then change it to undef.
9965     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9966
9967     // Check that we were able to transform all incoming values to the same
9968     // type.
9969     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9970         VecIn1.getValueType() != VT)
9971           return SDValue();
9972
9973     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9974     if (!isTypeLegal(VT))
9975       return SDValue();
9976
9977     // Return the new VECTOR_SHUFFLE node.
9978     SDValue Ops[2];
9979     Ops[0] = VecIn1;
9980     Ops[1] = VecIn2;
9981     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9982   }
9983
9984   return SDValue();
9985 }
9986
9987 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9988   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9989   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9990   // inputs come from at most two distinct vectors, turn this into a shuffle
9991   // node.
9992
9993   // If we only have one input vector, we don't need to do any concatenation.
9994   if (N->getNumOperands() == 1)
9995     return N->getOperand(0);
9996
9997   // Check if all of the operands are undefs.
9998   EVT VT = N->getValueType(0);
9999   if (ISD::allOperandsUndef(N))
10000     return DAG.getUNDEF(VT);
10001
10002   // Optimize concat_vectors where one of the vectors is undef.
10003   if (N->getNumOperands() == 2 &&
10004       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10005     SDValue In = N->getOperand(0);
10006     assert(In.getValueType().isVector() && "Must concat vectors");
10007
10008     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10009     if (In->getOpcode() == ISD::BITCAST &&
10010         !In->getOperand(0)->getValueType(0).isVector()) {
10011       SDValue Scalar = In->getOperand(0);
10012       EVT SclTy = Scalar->getValueType(0);
10013
10014       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10015         return SDValue();
10016
10017       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10018                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10019       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10020         return SDValue();
10021
10022       SDLoc dl = SDLoc(N);
10023       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10024       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10025     }
10026   }
10027
10028   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10029   // nodes often generate nop CONCAT_VECTOR nodes.
10030   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10031   // place the incoming vectors at the exact same location.
10032   SDValue SingleSource = SDValue();
10033   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10034
10035   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10036     SDValue Op = N->getOperand(i);
10037
10038     if (Op.getOpcode() == ISD::UNDEF)
10039       continue;
10040
10041     // Check if this is the identity extract:
10042     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10043       return SDValue();
10044
10045     // Find the single incoming vector for the extract_subvector.
10046     if (SingleSource.getNode()) {
10047       if (Op.getOperand(0) != SingleSource)
10048         return SDValue();
10049     } else {
10050       SingleSource = Op.getOperand(0);
10051
10052       // Check the source type is the same as the type of the result.
10053       // If not, this concat may extend the vector, so we can not
10054       // optimize it away.
10055       if (SingleSource.getValueType() != N->getValueType(0))
10056         return SDValue();
10057     }
10058
10059     unsigned IdentityIndex = i * PartNumElem;
10060     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10061     // The extract index must be constant.
10062     if (!CS)
10063       return SDValue();
10064
10065     // Check that we are reading from the identity index.
10066     if (CS->getZExtValue() != IdentityIndex)
10067       return SDValue();
10068   }
10069
10070   if (SingleSource.getNode())
10071     return SingleSource;
10072
10073   return SDValue();
10074 }
10075
10076 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10077   EVT NVT = N->getValueType(0);
10078   SDValue V = N->getOperand(0);
10079
10080   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10081     // Combine:
10082     //    (extract_subvec (concat V1, V2, ...), i)
10083     // Into:
10084     //    Vi if possible
10085     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10086     // type.
10087     if (V->getOperand(0).getValueType() != NVT)
10088       return SDValue();
10089     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10090     unsigned NumElems = NVT.getVectorNumElements();
10091     assert((Idx % NumElems) == 0 &&
10092            "IDX in concat is not a multiple of the result vector length.");
10093     return V->getOperand(Idx / NumElems);
10094   }
10095
10096   // Skip bitcasting
10097   if (V->getOpcode() == ISD::BITCAST)
10098     V = V.getOperand(0);
10099
10100   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10101     SDLoc dl(N);
10102     // Handle only simple case where vector being inserted and vector
10103     // being extracted are of same type, and are half size of larger vectors.
10104     EVT BigVT = V->getOperand(0).getValueType();
10105     EVT SmallVT = V->getOperand(1).getValueType();
10106     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10107       return SDValue();
10108
10109     // Only handle cases where both indexes are constants with the same type.
10110     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10111     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10112
10113     if (InsIdx && ExtIdx &&
10114         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10115         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10116       // Combine:
10117       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10118       // Into:
10119       //    indices are equal or bit offsets are equal => V1
10120       //    otherwise => (extract_subvec V1, ExtIdx)
10121       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10122           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10123         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10124       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10125                          DAG.getNode(ISD::BITCAST, dl,
10126                                      N->getOperand(0).getValueType(),
10127                                      V->getOperand(0)), N->getOperand(1));
10128     }
10129   }
10130
10131   return SDValue();
10132 }
10133
10134 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10135 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10136   EVT VT = N->getValueType(0);
10137   unsigned NumElts = VT.getVectorNumElements();
10138
10139   SDValue N0 = N->getOperand(0);
10140   SDValue N1 = N->getOperand(1);
10141   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10142
10143   SmallVector<SDValue, 4> Ops;
10144   EVT ConcatVT = N0.getOperand(0).getValueType();
10145   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10146   unsigned NumConcats = NumElts / NumElemsPerConcat;
10147
10148   // Look at every vector that's inserted. We're looking for exact
10149   // subvector-sized copies from a concatenated vector
10150   for (unsigned I = 0; I != NumConcats; ++I) {
10151     // Make sure we're dealing with a copy.
10152     unsigned Begin = I * NumElemsPerConcat;
10153     bool AllUndef = true, NoUndef = true;
10154     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10155       if (SVN->getMaskElt(J) >= 0)
10156         AllUndef = false;
10157       else
10158         NoUndef = false;
10159     }
10160
10161     if (NoUndef) {
10162       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10163         return SDValue();
10164
10165       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10166         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10167           return SDValue();
10168
10169       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10170       if (FirstElt < N0.getNumOperands())
10171         Ops.push_back(N0.getOperand(FirstElt));
10172       else
10173         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10174
10175     } else if (AllUndef) {
10176       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10177     } else { // Mixed with general masks and undefs, can't do optimization.
10178       return SDValue();
10179     }
10180   }
10181
10182   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10183                      Ops.size());
10184 }
10185
10186 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10187   EVT VT = N->getValueType(0);
10188   unsigned NumElts = VT.getVectorNumElements();
10189
10190   SDValue N0 = N->getOperand(0);
10191   SDValue N1 = N->getOperand(1);
10192
10193   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10194
10195   // Canonicalize shuffle undef, undef -> undef
10196   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10197     return DAG.getUNDEF(VT);
10198
10199   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10200
10201   // Canonicalize shuffle v, v -> v, undef
10202   if (N0 == N1) {
10203     SmallVector<int, 8> NewMask;
10204     for (unsigned i = 0; i != NumElts; ++i) {
10205       int Idx = SVN->getMaskElt(i);
10206       if (Idx >= (int)NumElts) Idx -= NumElts;
10207       NewMask.push_back(Idx);
10208     }
10209     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10210                                 &NewMask[0]);
10211   }
10212
10213   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10214   if (N0.getOpcode() == ISD::UNDEF) {
10215     SmallVector<int, 8> NewMask;
10216     for (unsigned i = 0; i != NumElts; ++i) {
10217       int Idx = SVN->getMaskElt(i);
10218       if (Idx >= 0) {
10219         if (Idx >= (int)NumElts)
10220           Idx -= NumElts;
10221         else
10222           Idx = -1; // remove reference to lhs
10223       }
10224       NewMask.push_back(Idx);
10225     }
10226     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10227                                 &NewMask[0]);
10228   }
10229
10230   // Remove references to rhs if it is undef
10231   if (N1.getOpcode() == ISD::UNDEF) {
10232     bool Changed = false;
10233     SmallVector<int, 8> NewMask;
10234     for (unsigned i = 0; i != NumElts; ++i) {
10235       int Idx = SVN->getMaskElt(i);
10236       if (Idx >= (int)NumElts) {
10237         Idx = -1;
10238         Changed = true;
10239       }
10240       NewMask.push_back(Idx);
10241     }
10242     if (Changed)
10243       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10244   }
10245
10246   // If it is a splat, check if the argument vector is another splat or a
10247   // build_vector with all scalar elements the same.
10248   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10249     SDNode *V = N0.getNode();
10250
10251     // If this is a bit convert that changes the element type of the vector but
10252     // not the number of vector elements, look through it.  Be careful not to
10253     // look though conversions that change things like v4f32 to v2f64.
10254     if (V->getOpcode() == ISD::BITCAST) {
10255       SDValue ConvInput = V->getOperand(0);
10256       if (ConvInput.getValueType().isVector() &&
10257           ConvInput.getValueType().getVectorNumElements() == NumElts)
10258         V = ConvInput.getNode();
10259     }
10260
10261     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10262       assert(V->getNumOperands() == NumElts &&
10263              "BUILD_VECTOR has wrong number of operands");
10264       SDValue Base;
10265       bool AllSame = true;
10266       for (unsigned i = 0; i != NumElts; ++i) {
10267         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10268           Base = V->getOperand(i);
10269           break;
10270         }
10271       }
10272       // Splat of <u, u, u, u>, return <u, u, u, u>
10273       if (!Base.getNode())
10274         return N0;
10275       for (unsigned i = 0; i != NumElts; ++i) {
10276         if (V->getOperand(i) != Base) {
10277           AllSame = false;
10278           break;
10279         }
10280       }
10281       // Splat of <x, x, x, x>, return <x, x, x, x>
10282       if (AllSame)
10283         return N0;
10284     }
10285   }
10286
10287   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10288       Level < AfterLegalizeVectorOps &&
10289       (N1.getOpcode() == ISD::UNDEF ||
10290       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10291        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10292     SDValue V = partitionShuffleOfConcats(N, DAG);
10293
10294     if (V.getNode())
10295       return V;
10296   }
10297
10298   // If this shuffle node is simply a swizzle of another shuffle node,
10299   // and it reverses the swizzle of the previous shuffle then we can
10300   // optimize shuffle(shuffle(x, undef), undef) -> x.
10301   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10302       N1.getOpcode() == ISD::UNDEF) {
10303
10304     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10305
10306     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10307     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10308       return SDValue();
10309
10310     // The incoming shuffle must be of the same type as the result of the
10311     // current shuffle.
10312     assert(OtherSV->getOperand(0).getValueType() == VT &&
10313            "Shuffle types don't match");
10314
10315     for (unsigned i = 0; i != NumElts; ++i) {
10316       int Idx = SVN->getMaskElt(i);
10317       assert(Idx < (int)NumElts && "Index references undef operand");
10318       // Next, this index comes from the first value, which is the incoming
10319       // shuffle. Adopt the incoming index.
10320       if (Idx >= 0)
10321         Idx = OtherSV->getMaskElt(Idx);
10322
10323       // The combined shuffle must map each index to itself.
10324       if (Idx >= 0 && (unsigned)Idx != i)
10325         return SDValue();
10326     }
10327
10328     return OtherSV->getOperand(0);
10329   }
10330
10331   return SDValue();
10332 }
10333
10334 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10335 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10336 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10337 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10338 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10339   EVT VT = N->getValueType(0);
10340   SDLoc dl(N);
10341   SDValue LHS = N->getOperand(0);
10342   SDValue RHS = N->getOperand(1);
10343   if (N->getOpcode() == ISD::AND) {
10344     if (RHS.getOpcode() == ISD::BITCAST)
10345       RHS = RHS.getOperand(0);
10346     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10347       SmallVector<int, 8> Indices;
10348       unsigned NumElts = RHS.getNumOperands();
10349       for (unsigned i = 0; i != NumElts; ++i) {
10350         SDValue Elt = RHS.getOperand(i);
10351         if (!isa<ConstantSDNode>(Elt))
10352           return SDValue();
10353
10354         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10355           Indices.push_back(i);
10356         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10357           Indices.push_back(NumElts);
10358         else
10359           return SDValue();
10360       }
10361
10362       // Let's see if the target supports this vector_shuffle.
10363       EVT RVT = RHS.getValueType();
10364       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10365         return SDValue();
10366
10367       // Return the new VECTOR_SHUFFLE node.
10368       EVT EltVT = RVT.getVectorElementType();
10369       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10370                                      DAG.getConstant(0, EltVT));
10371       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10372                                  RVT, &ZeroOps[0], ZeroOps.size());
10373       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10374       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10375       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10376     }
10377   }
10378
10379   return SDValue();
10380 }
10381
10382 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10383 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10384   assert(N->getValueType(0).isVector() &&
10385          "SimplifyVBinOp only works on vectors!");
10386
10387   SDValue LHS = N->getOperand(0);
10388   SDValue RHS = N->getOperand(1);
10389   SDValue Shuffle = XformToShuffleWithZero(N);
10390   if (Shuffle.getNode()) return Shuffle;
10391
10392   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10393   // this operation.
10394   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10395       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10396     // Check if both vectors are constants. If not bail out.
10397     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10398           cast<BuildVectorSDNode>(RHS)->isConstant()))
10399       return SDValue();
10400
10401     SmallVector<SDValue, 8> Ops;
10402     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10403       SDValue LHSOp = LHS.getOperand(i);
10404       SDValue RHSOp = RHS.getOperand(i);
10405
10406       // Can't fold divide by zero.
10407       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10408           N->getOpcode() == ISD::FDIV) {
10409         if ((RHSOp.getOpcode() == ISD::Constant &&
10410              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10411             (RHSOp.getOpcode() == ISD::ConstantFP &&
10412              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10413           break;
10414       }
10415
10416       EVT VT = LHSOp.getValueType();
10417       EVT RVT = RHSOp.getValueType();
10418       if (RVT != VT) {
10419         // Integer BUILD_VECTOR operands may have types larger than the element
10420         // size (e.g., when the element type is not legal).  Prior to type
10421         // legalization, the types may not match between the two BUILD_VECTORS.
10422         // Truncate one of the operands to make them match.
10423         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10424           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10425         } else {
10426           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10427           VT = RVT;
10428         }
10429       }
10430       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10431                                    LHSOp, RHSOp);
10432       if (FoldOp.getOpcode() != ISD::UNDEF &&
10433           FoldOp.getOpcode() != ISD::Constant &&
10434           FoldOp.getOpcode() != ISD::ConstantFP)
10435         break;
10436       Ops.push_back(FoldOp);
10437       AddToWorkList(FoldOp.getNode());
10438     }
10439
10440     if (Ops.size() == LHS.getNumOperands())
10441       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10442                          LHS.getValueType(), &Ops[0], Ops.size());
10443   }
10444
10445   return SDValue();
10446 }
10447
10448 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10449 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10450   assert(N->getValueType(0).isVector() &&
10451          "SimplifyVUnaryOp only works on vectors!");
10452
10453   SDValue N0 = N->getOperand(0);
10454
10455   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10456     return SDValue();
10457
10458   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10459   SmallVector<SDValue, 8> Ops;
10460   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10461     SDValue Op = N0.getOperand(i);
10462     if (Op.getOpcode() != ISD::UNDEF &&
10463         Op.getOpcode() != ISD::ConstantFP)
10464       break;
10465     EVT EltVT = Op.getValueType();
10466     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10467     if (FoldOp.getOpcode() != ISD::UNDEF &&
10468         FoldOp.getOpcode() != ISD::ConstantFP)
10469       break;
10470     Ops.push_back(FoldOp);
10471     AddToWorkList(FoldOp.getNode());
10472   }
10473
10474   if (Ops.size() != N0.getNumOperands())
10475     return SDValue();
10476
10477   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10478                      N0.getValueType(), &Ops[0], Ops.size());
10479 }
10480
10481 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10482                                     SDValue N1, SDValue N2){
10483   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10484
10485   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10486                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10487
10488   // If we got a simplified select_cc node back from SimplifySelectCC, then
10489   // break it down into a new SETCC node, and a new SELECT node, and then return
10490   // the SELECT node, since we were called with a SELECT node.
10491   if (SCC.getNode()) {
10492     // Check to see if we got a select_cc back (to turn into setcc/select).
10493     // Otherwise, just return whatever node we got back, like fabs.
10494     if (SCC.getOpcode() == ISD::SELECT_CC) {
10495       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10496                                   N0.getValueType(),
10497                                   SCC.getOperand(0), SCC.getOperand(1),
10498                                   SCC.getOperand(4));
10499       AddToWorkList(SETCC.getNode());
10500       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10501                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10502     }
10503
10504     return SCC;
10505   }
10506   return SDValue();
10507 }
10508
10509 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10510 /// are the two values being selected between, see if we can simplify the
10511 /// select.  Callers of this should assume that TheSelect is deleted if this
10512 /// returns true.  As such, they should return the appropriate thing (e.g. the
10513 /// node) back to the top-level of the DAG combiner loop to avoid it being
10514 /// looked at.
10515 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10516                                     SDValue RHS) {
10517
10518   // Cannot simplify select with vector condition
10519   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10520
10521   // If this is a select from two identical things, try to pull the operation
10522   // through the select.
10523   if (LHS.getOpcode() != RHS.getOpcode() ||
10524       !LHS.hasOneUse() || !RHS.hasOneUse())
10525     return false;
10526
10527   // If this is a load and the token chain is identical, replace the select
10528   // of two loads with a load through a select of the address to load from.
10529   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10530   // constants have been dropped into the constant pool.
10531   if (LHS.getOpcode() == ISD::LOAD) {
10532     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10533     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10534
10535     // Token chains must be identical.
10536     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10537         // Do not let this transformation reduce the number of volatile loads.
10538         LLD->isVolatile() || RLD->isVolatile() ||
10539         // If this is an EXTLOAD, the VT's must match.
10540         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10541         // If this is an EXTLOAD, the kind of extension must match.
10542         (LLD->getExtensionType() != RLD->getExtensionType() &&
10543          // The only exception is if one of the extensions is anyext.
10544          LLD->getExtensionType() != ISD::EXTLOAD &&
10545          RLD->getExtensionType() != ISD::EXTLOAD) ||
10546         // FIXME: this discards src value information.  This is
10547         // over-conservative. It would be beneficial to be able to remember
10548         // both potential memory locations.  Since we are discarding
10549         // src value info, don't do the transformation if the memory
10550         // locations are not in the default address space.
10551         LLD->getPointerInfo().getAddrSpace() != 0 ||
10552         RLD->getPointerInfo().getAddrSpace() != 0 ||
10553         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10554                                       LLD->getBasePtr().getValueType()))
10555       return false;
10556
10557     // Check that the select condition doesn't reach either load.  If so,
10558     // folding this will induce a cycle into the DAG.  If not, this is safe to
10559     // xform, so create a select of the addresses.
10560     SDValue Addr;
10561     if (TheSelect->getOpcode() == ISD::SELECT) {
10562       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10563       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10564           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10565         return false;
10566       // The loads must not depend on one another.
10567       if (LLD->isPredecessorOf(RLD) ||
10568           RLD->isPredecessorOf(LLD))
10569         return false;
10570       Addr = DAG.getSelect(SDLoc(TheSelect),
10571                            LLD->getBasePtr().getValueType(),
10572                            TheSelect->getOperand(0), LLD->getBasePtr(),
10573                            RLD->getBasePtr());
10574     } else {  // Otherwise SELECT_CC
10575       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10576       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10577
10578       if ((LLD->hasAnyUseOfValue(1) &&
10579            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10580           (RLD->hasAnyUseOfValue(1) &&
10581            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10582         return false;
10583
10584       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10585                          LLD->getBasePtr().getValueType(),
10586                          TheSelect->getOperand(0),
10587                          TheSelect->getOperand(1),
10588                          LLD->getBasePtr(), RLD->getBasePtr(),
10589                          TheSelect->getOperand(4));
10590     }
10591
10592     SDValue Load;
10593     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10594       Load = DAG.getLoad(TheSelect->getValueType(0),
10595                          SDLoc(TheSelect),
10596                          // FIXME: Discards pointer and TBAA info.
10597                          LLD->getChain(), Addr, MachinePointerInfo(),
10598                          LLD->isVolatile(), LLD->isNonTemporal(),
10599                          LLD->isInvariant(), LLD->getAlignment());
10600     } else {
10601       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10602                             RLD->getExtensionType() : LLD->getExtensionType(),
10603                             SDLoc(TheSelect),
10604                             TheSelect->getValueType(0),
10605                             // FIXME: Discards pointer and TBAA info.
10606                             LLD->getChain(), Addr, MachinePointerInfo(),
10607                             LLD->getMemoryVT(), LLD->isVolatile(),
10608                             LLD->isNonTemporal(), LLD->getAlignment());
10609     }
10610
10611     // Users of the select now use the result of the load.
10612     CombineTo(TheSelect, Load);
10613
10614     // Users of the old loads now use the new load's chain.  We know the
10615     // old-load value is dead now.
10616     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10617     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10618     return true;
10619   }
10620
10621   return false;
10622 }
10623
10624 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10625 /// where 'cond' is the comparison specified by CC.
10626 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10627                                       SDValue N2, SDValue N3,
10628                                       ISD::CondCode CC, bool NotExtCompare) {
10629   // (x ? y : y) -> y.
10630   if (N2 == N3) return N2;
10631
10632   EVT VT = N2.getValueType();
10633   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10634   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10635   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10636
10637   // Determine if the condition we're dealing with is constant
10638   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10639                               N0, N1, CC, DL, false);
10640   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10641   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10642
10643   // fold select_cc true, x, y -> x
10644   if (SCCC && !SCCC->isNullValue())
10645     return N2;
10646   // fold select_cc false, x, y -> y
10647   if (SCCC && SCCC->isNullValue())
10648     return N3;
10649
10650   // Check to see if we can simplify the select into an fabs node
10651   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10652     // Allow either -0.0 or 0.0
10653     if (CFP->getValueAPF().isZero()) {
10654       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10655       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10656           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10657           N2 == N3.getOperand(0))
10658         return DAG.getNode(ISD::FABS, DL, VT, N0);
10659
10660       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10661       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10662           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10663           N2.getOperand(0) == N3)
10664         return DAG.getNode(ISD::FABS, DL, VT, N3);
10665     }
10666   }
10667
10668   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10669   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10670   // in it.  This is a win when the constant is not otherwise available because
10671   // it replaces two constant pool loads with one.  We only do this if the FP
10672   // type is known to be legal, because if it isn't, then we are before legalize
10673   // types an we want the other legalization to happen first (e.g. to avoid
10674   // messing with soft float) and if the ConstantFP is not legal, because if
10675   // it is legal, we may not need to store the FP constant in a constant pool.
10676   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10677     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10678       if (TLI.isTypeLegal(N2.getValueType()) &&
10679           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10680            TargetLowering::Legal) &&
10681           // If both constants have multiple uses, then we won't need to do an
10682           // extra load, they are likely around in registers for other users.
10683           (TV->hasOneUse() || FV->hasOneUse())) {
10684         Constant *Elts[] = {
10685           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10686           const_cast<ConstantFP*>(TV->getConstantFPValue())
10687         };
10688         Type *FPTy = Elts[0]->getType();
10689         const DataLayout &TD = *TLI.getDataLayout();
10690
10691         // Create a ConstantArray of the two constants.
10692         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10693         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10694                                             TD.getPrefTypeAlignment(FPTy));
10695         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10696
10697         // Get the offsets to the 0 and 1 element of the array so that we can
10698         // select between them.
10699         SDValue Zero = DAG.getIntPtrConstant(0);
10700         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10701         SDValue One = DAG.getIntPtrConstant(EltSize);
10702
10703         SDValue Cond = DAG.getSetCC(DL,
10704                                     getSetCCResultType(N0.getValueType()),
10705                                     N0, N1, CC);
10706         AddToWorkList(Cond.getNode());
10707         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10708                                           Cond, One, Zero);
10709         AddToWorkList(CstOffset.getNode());
10710         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10711                             CstOffset);
10712         AddToWorkList(CPIdx.getNode());
10713         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10714                            MachinePointerInfo::getConstantPool(), false,
10715                            false, false, Alignment);
10716
10717       }
10718     }
10719
10720   // Check to see if we can perform the "gzip trick", transforming
10721   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10722   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10723       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10724        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10725     EVT XType = N0.getValueType();
10726     EVT AType = N2.getValueType();
10727     if (XType.bitsGE(AType)) {
10728       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10729       // single-bit constant.
10730       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10731         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10732         ShCtV = XType.getSizeInBits()-ShCtV-1;
10733         SDValue ShCt = DAG.getConstant(ShCtV,
10734                                        getShiftAmountTy(N0.getValueType()));
10735         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10736                                     XType, N0, ShCt);
10737         AddToWorkList(Shift.getNode());
10738
10739         if (XType.bitsGT(AType)) {
10740           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10741           AddToWorkList(Shift.getNode());
10742         }
10743
10744         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10745       }
10746
10747       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10748                                   XType, N0,
10749                                   DAG.getConstant(XType.getSizeInBits()-1,
10750                                          getShiftAmountTy(N0.getValueType())));
10751       AddToWorkList(Shift.getNode());
10752
10753       if (XType.bitsGT(AType)) {
10754         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10755         AddToWorkList(Shift.getNode());
10756       }
10757
10758       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10759     }
10760   }
10761
10762   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10763   // where y is has a single bit set.
10764   // A plaintext description would be, we can turn the SELECT_CC into an AND
10765   // when the condition can be materialized as an all-ones register.  Any
10766   // single bit-test can be materialized as an all-ones register with
10767   // shift-left and shift-right-arith.
10768   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10769       N0->getValueType(0) == VT &&
10770       N1C && N1C->isNullValue() &&
10771       N2C && N2C->isNullValue()) {
10772     SDValue AndLHS = N0->getOperand(0);
10773     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10774     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10775       // Shift the tested bit over the sign bit.
10776       APInt AndMask = ConstAndRHS->getAPIntValue();
10777       SDValue ShlAmt =
10778         DAG.getConstant(AndMask.countLeadingZeros(),
10779                         getShiftAmountTy(AndLHS.getValueType()));
10780       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10781
10782       // Now arithmetic right shift it all the way over, so the result is either
10783       // all-ones, or zero.
10784       SDValue ShrAmt =
10785         DAG.getConstant(AndMask.getBitWidth()-1,
10786                         getShiftAmountTy(Shl.getValueType()));
10787       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10788
10789       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10790     }
10791   }
10792
10793   // fold select C, 16, 0 -> shl C, 4
10794   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10795     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10796       TargetLowering::ZeroOrOneBooleanContent) {
10797
10798     // If the caller doesn't want us to simplify this into a zext of a compare,
10799     // don't do it.
10800     if (NotExtCompare && N2C->getAPIntValue() == 1)
10801       return SDValue();
10802
10803     // Get a SetCC of the condition
10804     // NOTE: Don't create a SETCC if it's not legal on this target.
10805     if (!LegalOperations ||
10806         TLI.isOperationLegal(ISD::SETCC,
10807           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10808       SDValue Temp, SCC;
10809       // cast from setcc result type to select result type
10810       if (LegalTypes) {
10811         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10812                             N0, N1, CC);
10813         if (N2.getValueType().bitsLT(SCC.getValueType()))
10814           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10815                                         N2.getValueType());
10816         else
10817           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10818                              N2.getValueType(), SCC);
10819       } else {
10820         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10821         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10822                            N2.getValueType(), SCC);
10823       }
10824
10825       AddToWorkList(SCC.getNode());
10826       AddToWorkList(Temp.getNode());
10827
10828       if (N2C->getAPIntValue() == 1)
10829         return Temp;
10830
10831       // shl setcc result by log2 n2c
10832       return DAG.getNode(
10833           ISD::SHL, DL, N2.getValueType(), Temp,
10834           DAG.getConstant(N2C->getAPIntValue().logBase2(),
10835                           getShiftAmountTy(Temp.getValueType())));
10836     }
10837   }
10838
10839   // Check to see if this is the equivalent of setcc
10840   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10841   // otherwise, go ahead with the folds.
10842   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10843     EVT XType = N0.getValueType();
10844     if (!LegalOperations ||
10845         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10846       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10847       if (Res.getValueType() != VT)
10848         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10849       return Res;
10850     }
10851
10852     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10853     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10854         (!LegalOperations ||
10855          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10856       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10857       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10858                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10859                                        getShiftAmountTy(Ctlz.getValueType())));
10860     }
10861     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10862     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10863       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10864                                   XType, DAG.getConstant(0, XType), N0);
10865       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10866       return DAG.getNode(ISD::SRL, DL, XType,
10867                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10868                          DAG.getConstant(XType.getSizeInBits()-1,
10869                                          getShiftAmountTy(XType)));
10870     }
10871     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10872     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10873       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10874                                  DAG.getConstant(XType.getSizeInBits()-1,
10875                                          getShiftAmountTy(N0.getValueType())));
10876       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10877     }
10878   }
10879
10880   // Check to see if this is an integer abs.
10881   // select_cc setg[te] X,  0,  X, -X ->
10882   // select_cc setgt    X, -1,  X, -X ->
10883   // select_cc setl[te] X,  0, -X,  X ->
10884   // select_cc setlt    X,  1, -X,  X ->
10885   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10886   if (N1C) {
10887     ConstantSDNode *SubC = NULL;
10888     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10889          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10890         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10891       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10892     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10893               (N1C->isOne() && CC == ISD::SETLT)) &&
10894              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10895       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10896
10897     EVT XType = N0.getValueType();
10898     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10899       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10900                                   N0,
10901                                   DAG.getConstant(XType.getSizeInBits()-1,
10902                                          getShiftAmountTy(N0.getValueType())));
10903       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10904                                 XType, N0, Shift);
10905       AddToWorkList(Shift.getNode());
10906       AddToWorkList(Add.getNode());
10907       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10908     }
10909   }
10910
10911   return SDValue();
10912 }
10913
10914 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10915 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10916                                    SDValue N1, ISD::CondCode Cond,
10917                                    SDLoc DL, bool foldBooleans) {
10918   TargetLowering::DAGCombinerInfo
10919     DagCombineInfo(DAG, Level, false, this);
10920   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10921 }
10922
10923 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10924 /// return a DAG expression to select that will generate the same value by
10925 /// multiplying by a magic number.  See:
10926 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10927 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10928   std::vector<SDNode*> Built;
10929   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10930
10931   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10932        ii != ee; ++ii)
10933     AddToWorkList(*ii);
10934   return S;
10935 }
10936
10937 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10938 /// return a DAG expression to select that will generate the same value by
10939 /// multiplying by a magic number.  See:
10940 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10941 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10942   std::vector<SDNode*> Built;
10943   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10944
10945   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10946        ii != ee; ++ii)
10947     AddToWorkList(*ii);
10948   return S;
10949 }
10950
10951 /// FindBaseOffset - Return true if base is a frame index, which is known not
10952 // to alias with anything but itself.  Provides base object and offset as
10953 // results.
10954 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10955                            const GlobalValue *&GV, const void *&CV) {
10956   // Assume it is a primitive operation.
10957   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10958
10959   // If it's an adding a simple constant then integrate the offset.
10960   if (Base.getOpcode() == ISD::ADD) {
10961     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10962       Base = Base.getOperand(0);
10963       Offset += C->getZExtValue();
10964     }
10965   }
10966
10967   // Return the underlying GlobalValue, and update the Offset.  Return false
10968   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10969   // by multiple nodes with different offsets.
10970   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10971     GV = G->getGlobal();
10972     Offset += G->getOffset();
10973     return false;
10974   }
10975
10976   // Return the underlying Constant value, and update the Offset.  Return false
10977   // for ConstantSDNodes since the same constant pool entry may be represented
10978   // by multiple nodes with different offsets.
10979   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10980     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10981                                          : (const void *)C->getConstVal();
10982     Offset += C->getOffset();
10983     return false;
10984   }
10985   // If it's any of the following then it can't alias with anything but itself.
10986   return isa<FrameIndexSDNode>(Base);
10987 }
10988
10989 /// isAlias - Return true if there is any possibility that the two addresses
10990 /// overlap.
10991 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10992                           const Value *SrcValue1, int SrcValueOffset1,
10993                           unsigned SrcValueAlign1,
10994                           const MDNode *TBAAInfo1,
10995                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10996                           const Value *SrcValue2, int SrcValueOffset2,
10997                           unsigned SrcValueAlign2,
10998                           const MDNode *TBAAInfo2) const {
10999   // If they are the same then they must be aliases.
11000   if (Ptr1 == Ptr2) return true;
11001
11002   // If they are both volatile then they cannot be reordered.
11003   if (IsVolatile1 && IsVolatile2) return true;
11004
11005   // Gather base node and offset information.
11006   SDValue Base1, Base2;
11007   int64_t Offset1, Offset2;
11008   const GlobalValue *GV1, *GV2;
11009   const void *CV1, *CV2;
11010   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11011   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11012
11013   // If they have a same base address then check to see if they overlap.
11014   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11015     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11016
11017   // It is possible for different frame indices to alias each other, mostly
11018   // when tail call optimization reuses return address slots for arguments.
11019   // To catch this case, look up the actual index of frame indices to compute
11020   // the real alias relationship.
11021   if (isFrameIndex1 && isFrameIndex2) {
11022     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11023     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11024     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11025     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11026   }
11027
11028   // Otherwise, if we know what the bases are, and they aren't identical, then
11029   // we know they cannot alias.
11030   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11031     return false;
11032
11033   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11034   // compared to the size and offset of the access, we may be able to prove they
11035   // do not alias.  This check is conservative for now to catch cases created by
11036   // splitting vector types.
11037   if ((SrcValueAlign1 == SrcValueAlign2) &&
11038       (SrcValueOffset1 != SrcValueOffset2) &&
11039       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11040     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11041     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11042
11043     // There is no overlap between these relatively aligned accesses of similar
11044     // size, return no alias.
11045     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11046       return false;
11047   }
11048
11049   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11050     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11051   if (UseAA && SrcValue1 && SrcValue2) {
11052     // Use alias analysis information.
11053     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11054     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11055     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11056     AliasAnalysis::AliasResult AAResult =
11057       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11058                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
11059     if (AAResult == AliasAnalysis::NoAlias)
11060       return false;
11061   }
11062
11063   // Otherwise we have to assume they alias.
11064   return true;
11065 }
11066
11067 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11068   SDValue Ptr0, Ptr1;
11069   int64_t Size0, Size1;
11070   bool IsVolatile0, IsVolatile1;
11071   const Value *SrcValue0, *SrcValue1;
11072   int SrcValueOffset0, SrcValueOffset1;
11073   unsigned SrcValueAlign0, SrcValueAlign1;
11074   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11075   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11076                 SrcValueAlign0, SrcTBAAInfo0);
11077   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11078                 SrcValueAlign1, SrcTBAAInfo1);
11079   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11080                  SrcValueAlign0, SrcTBAAInfo0,
11081                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11082                  SrcValueAlign1, SrcTBAAInfo1);
11083 }
11084
11085 /// FindAliasInfo - Extracts the relevant alias information from the memory
11086 /// node.  Returns true if the operand was a nonvolatile load.
11087 bool DAGCombiner::FindAliasInfo(SDNode *N,
11088                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11089                                 const Value *&SrcValue,
11090                                 int &SrcValueOffset,
11091                                 unsigned &SrcValueAlign,
11092                                 const MDNode *&TBAAInfo) const {
11093   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11094
11095   Ptr = LS->getBasePtr();
11096   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11097   IsVolatile = LS->isVolatile();
11098   SrcValue = LS->getSrcValue();
11099   SrcValueOffset = LS->getSrcValueOffset();
11100   SrcValueAlign = LS->getOriginalAlignment();
11101   TBAAInfo = LS->getTBAAInfo();
11102   return isa<LoadSDNode>(LS) && !IsVolatile;
11103 }
11104
11105 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11106 /// looking for aliasing nodes and adding them to the Aliases vector.
11107 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11108                                    SmallVectorImpl<SDValue> &Aliases) {
11109   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11110   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11111
11112   // Get alias information for node.
11113   SDValue Ptr;
11114   int64_t Size;
11115   bool IsVolatile;
11116   const Value *SrcValue;
11117   int SrcValueOffset;
11118   unsigned SrcValueAlign;
11119   const MDNode *SrcTBAAInfo;
11120   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11121                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11122
11123   // Starting off.
11124   Chains.push_back(OriginalChain);
11125   unsigned Depth = 0;
11126
11127   // Look at each chain and determine if it is an alias.  If so, add it to the
11128   // aliases list.  If not, then continue up the chain looking for the next
11129   // candidate.
11130   while (!Chains.empty()) {
11131     SDValue Chain = Chains.back();
11132     Chains.pop_back();
11133
11134     // For TokenFactor nodes, look at each operand and only continue up the
11135     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11136     // find more and revert to original chain since the xform is unlikely to be
11137     // profitable.
11138     //
11139     // FIXME: The depth check could be made to return the last non-aliasing
11140     // chain we found before we hit a tokenfactor rather than the original
11141     // chain.
11142     if (Depth > 6 || Aliases.size() == 2) {
11143       Aliases.clear();
11144       Aliases.push_back(OriginalChain);
11145       return;
11146     }
11147
11148     // Don't bother if we've been before.
11149     if (!Visited.insert(Chain.getNode()))
11150       continue;
11151
11152     switch (Chain.getOpcode()) {
11153     case ISD::EntryToken:
11154       // Entry token is ideal chain operand, but handled in FindBetterChain.
11155       break;
11156
11157     case ISD::LOAD:
11158     case ISD::STORE: {
11159       // Get alias information for Chain.
11160       SDValue OpPtr;
11161       int64_t OpSize;
11162       bool OpIsVolatile;
11163       const Value *OpSrcValue;
11164       int OpSrcValueOffset;
11165       unsigned OpSrcValueAlign;
11166       const MDNode *OpSrcTBAAInfo;
11167       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11168                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11169                                     OpSrcValueAlign,
11170                                     OpSrcTBAAInfo);
11171
11172       // If chain is alias then stop here.
11173       if (!(IsLoad && IsOpLoad) &&
11174           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11175                   SrcValueAlign, SrcTBAAInfo,
11176                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11177                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11178         Aliases.push_back(Chain);
11179       } else {
11180         // Look further up the chain.
11181         Chains.push_back(Chain.getOperand(0));
11182         ++Depth;
11183       }
11184       break;
11185     }
11186
11187     case ISD::TokenFactor:
11188       // We have to check each of the operands of the token factor for "small"
11189       // token factors, so we queue them up.  Adding the operands to the queue
11190       // (stack) in reverse order maintains the original order and increases the
11191       // likelihood that getNode will find a matching token factor (CSE.)
11192       if (Chain.getNumOperands() > 16) {
11193         Aliases.push_back(Chain);
11194         break;
11195       }
11196       for (unsigned n = Chain.getNumOperands(); n;)
11197         Chains.push_back(Chain.getOperand(--n));
11198       ++Depth;
11199       break;
11200
11201     default:
11202       // For all other instructions we will just have to take what we can get.
11203       Aliases.push_back(Chain);
11204       break;
11205     }
11206   }
11207
11208   // We need to be careful here to also search for aliases through the
11209   // value operand of a store, etc. Consider the following situation:
11210   //   Token1 = ...
11211   //   L1 = load Token1, %52
11212   //   S1 = store Token1, L1, %51
11213   //   L2 = load Token1, %52+8
11214   //   S2 = store Token1, L2, %51+8
11215   //   Token2 = Token(S1, S2)
11216   //   L3 = load Token2, %53
11217   //   S3 = store Token2, L3, %52
11218   //   L4 = load Token2, %53+8
11219   //   S4 = store Token2, L4, %52+8
11220   // If we search for aliases of S3 (which loads address %52), and we look
11221   // only through the chain, then we'll miss the trivial dependence on L1
11222   // (which also loads from %52). We then might change all loads and
11223   // stores to use Token1 as their chain operand, which could result in
11224   // copying %53 into %52 before copying %52 into %51 (which should
11225   // happen first).
11226   //
11227   // The problem is, however, that searching for such data dependencies
11228   // can become expensive, and the cost is not directly related to the
11229   // chain depth. Instead, we'll rule out such configurations here by
11230   // insisting that we've visited all chain users (except for users
11231   // of the original chain, which is not necessary). When doing this,
11232   // we need to look through nodes we don't care about (otherwise, things
11233   // like register copies will interfere with trivial cases).
11234
11235   SmallVector<const SDNode *, 16> Worklist;
11236   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11237        IE = Visited.end(); I != IE; ++I)
11238     if (*I != OriginalChain.getNode())
11239       Worklist.push_back(*I);
11240
11241   while (!Worklist.empty()) {
11242     const SDNode *M = Worklist.pop_back_val();
11243
11244     // We have already visited M, and want to make sure we've visited any uses
11245     // of M that we care about. For uses that we've not visisted, and don't
11246     // care about, queue them to the worklist.
11247
11248     for (SDNode::use_iterator UI = M->use_begin(),
11249          UIE = M->use_end(); UI != UIE; ++UI)
11250       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11251         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11252           // We've not visited this use, and we care about it (it could have an
11253           // ordering dependency with the original node).
11254           Aliases.clear();
11255           Aliases.push_back(OriginalChain);
11256           return;
11257         }
11258
11259         // We've not visited this use, but we don't care about it. Mark it as
11260         // visited and enqueue it to the worklist.
11261         Worklist.push_back(*UI);
11262       }
11263   }
11264 }
11265
11266 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11267 /// for a better chain (aliasing node.)
11268 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11269   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11270
11271   // Accumulate all the aliases to this node.
11272   GatherAllAliases(N, OldChain, Aliases);
11273
11274   // If no operands then chain to entry token.
11275   if (Aliases.size() == 0)
11276     return DAG.getEntryNode();
11277
11278   // If a single operand then chain to it.  We don't need to revisit it.
11279   if (Aliases.size() == 1)
11280     return Aliases[0];
11281
11282   // Construct a custom tailored token factor.
11283   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11284                      &Aliases[0], Aliases.size());
11285 }
11286
11287 // SelectionDAG::Combine - This is the entry point for the file.
11288 //
11289 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11290                            CodeGenOpt::Level OptLevel) {
11291   /// run - This is the main entry point to this class.
11292   ///
11293   DAGCombiner(*this, AA, OptLevel).Run(Level);
11294 }