[c++11] Range'ify use list loops in DAGCombiner.
[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("Enable DAG combiner alias-analysis heuristics"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Enable DAG combiner's use of IR alias analysis"));
58
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 //   1. Stack coloring does not update TBAA when merging allocas
61 //   2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 //      Because BasicAA does not handle inttoptr, we'll often miss basic type
63 //      punning idioms that we need to catch so we don't miscompile real-world
64 //      code.
65   static cl::opt<bool>
66     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67                cl::desc("Enable DAG combiner's use of TBAA"));
68
69 #ifndef NDEBUG
70   static cl::opt<std::string>
71     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72                cl::desc("Only use DAG-combiner alias analysis in this"
73                         " function"));
74 #endif
75
76   /// Hidden option to stress test load slicing, i.e., when this option
77   /// is enabled, load slicing bypasses most of its profitability guards.
78   static cl::opt<bool>
79   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80                     cl::desc("Bypass the profitability model of load "
81                              "slicing"),
82                     cl::init(false));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     // Worklist of all of the nodes that need to be simplified.
96     //
97     // This has the semantics that when adding to the worklist,
98     // the item added must be next to be processed. It should
99     // also only appear once. The naive approach to this takes
100     // linear time.
101     //
102     // To reduce the insert/remove time to logarithmic, we use
103     // a set and a vector to maintain our worklist.
104     //
105     // The set contains the items on the worklist, but does not
106     // maintain the order they should be visited.
107     //
108     // The vector maintains the order nodes should be visited, but may
109     // contain duplicate or removed nodes. When choosing a node to
110     // visit, we pop off the order stack until we find an item that is
111     // also in the contents set. All operations are O(log N).
112     SmallPtrSet<SDNode*, 64> WorkListContents;
113     SmallVector<SDNode*, 64> WorkListOrder;
114
115     // AA - Used for DAG load/store alias analysis.
116     AliasAnalysis &AA;
117
118     /// AddUsersToWorkList - When an instruction is simplified, add all users of
119     /// the instruction to the work lists because they might get more simplified
120     /// now.
121     ///
122     void AddUsersToWorkList(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorkList(Node);
125     }
126
127     /// visit - call the node-specific routine that knows how to fold each
128     /// particular type of node.
129     SDValue visit(SDNode *N);
130
131   public:
132     /// AddToWorkList - Add to the work list making sure its instance is at the
133     /// back (next to be processed.)
134     void AddToWorkList(SDNode *N) {
135       WorkListContents.insert(N);
136       WorkListOrder.push_back(N);
137     }
138
139     /// removeFromWorkList - remove all instances of N from the worklist.
140     ///
141     void removeFromWorkList(SDNode *N) {
142       WorkListContents.erase(N);
143     }
144
145     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
146                       bool AddTo = true);
147
148     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
149       return CombineTo(N, &Res, 1, AddTo);
150     }
151
152     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
153                       bool AddTo = true) {
154       SDValue To[] = { Res0, Res1 };
155       return CombineTo(N, To, 2, AddTo);
156     }
157
158     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
159
160   private:
161
162     /// SimplifyDemandedBits - Check the specified integer node value to see if
163     /// it can be simplified or if things it uses can be simplified by bit
164     /// propagation.  If so, return true.
165     bool SimplifyDemandedBits(SDValue Op) {
166       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
167       APInt Demanded = APInt::getAllOnesValue(BitWidth);
168       return SimplifyDemandedBits(Op, Demanded);
169     }
170
171     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
172
173     bool CombineToPreIndexedLoadStore(SDNode *N);
174     bool CombineToPostIndexedLoadStore(SDNode *N);
175     bool SliceUpLoad(SDNode *N);
176
177     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
178     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
179     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
180     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
181     SDValue PromoteIntBinOp(SDValue Op);
182     SDValue PromoteIntShiftOp(SDValue Op);
183     SDValue PromoteExtend(SDValue Op);
184     bool PromoteLoad(SDValue Op);
185
186     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
187                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
188                          ISD::NodeType ExtType);
189
190     /// combine - call the node-specific routine that knows how to fold each
191     /// particular type of node. If that doesn't do anything, try the
192     /// target-specific DAG combines.
193     SDValue combine(SDNode *N);
194
195     // Visitation implementation - Implement dag node combining for different
196     // node types.  The semantics are as follows:
197     // Return Value:
198     //   SDValue.getNode() == 0 - No change was made
199     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
200     //   otherwise              - N should be replaced by the returned Operand.
201     //
202     SDValue visitTokenFactor(SDNode *N);
203     SDValue visitMERGE_VALUES(SDNode *N);
204     SDValue visitADD(SDNode *N);
205     SDValue visitSUB(SDNode *N);
206     SDValue visitADDC(SDNode *N);
207     SDValue visitSUBC(SDNode *N);
208     SDValue visitADDE(SDNode *N);
209     SDValue visitSUBE(SDNode *N);
210     SDValue visitMUL(SDNode *N);
211     SDValue visitSDIV(SDNode *N);
212     SDValue visitUDIV(SDNode *N);
213     SDValue visitSREM(SDNode *N);
214     SDValue visitUREM(SDNode *N);
215     SDValue visitMULHU(SDNode *N);
216     SDValue visitMULHS(SDNode *N);
217     SDValue visitSMUL_LOHI(SDNode *N);
218     SDValue visitUMUL_LOHI(SDNode *N);
219     SDValue visitSMULO(SDNode *N);
220     SDValue visitUMULO(SDNode *N);
221     SDValue visitSDIVREM(SDNode *N);
222     SDValue visitUDIVREM(SDNode *N);
223     SDValue visitAND(SDNode *N);
224     SDValue visitOR(SDNode *N);
225     SDValue visitXOR(SDNode *N);
226     SDValue SimplifyVBinOp(SDNode *N);
227     SDValue SimplifyVUnaryOp(SDNode *N);
228     SDValue visitSHL(SDNode *N);
229     SDValue visitSRA(SDNode *N);
230     SDValue visitSRL(SDNode *N);
231     SDValue visitRotate(SDNode *N);
232     SDValue visitCTLZ(SDNode *N);
233     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234     SDValue visitCTTZ(SDNode *N);
235     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236     SDValue visitCTPOP(SDNode *N);
237     SDValue visitSELECT(SDNode *N);
238     SDValue visitVSELECT(SDNode *N);
239     SDValue visitSELECT_CC(SDNode *N);
240     SDValue visitSETCC(SDNode *N);
241     SDValue visitSIGN_EXTEND(SDNode *N);
242     SDValue visitZERO_EXTEND(SDNode *N);
243     SDValue visitANY_EXTEND(SDNode *N);
244     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245     SDValue visitTRUNCATE(SDNode *N);
246     SDValue visitBITCAST(SDNode *N);
247     SDValue visitBUILD_PAIR(SDNode *N);
248     SDValue visitFADD(SDNode *N);
249     SDValue visitFSUB(SDNode *N);
250     SDValue visitFMUL(SDNode *N);
251     SDValue visitFMA(SDNode *N);
252     SDValue visitFDIV(SDNode *N);
253     SDValue visitFREM(SDNode *N);
254     SDValue visitFCOPYSIGN(SDNode *N);
255     SDValue visitSINT_TO_FP(SDNode *N);
256     SDValue visitUINT_TO_FP(SDNode *N);
257     SDValue visitFP_TO_SINT(SDNode *N);
258     SDValue visitFP_TO_UINT(SDNode *N);
259     SDValue visitFP_ROUND(SDNode *N);
260     SDValue visitFP_ROUND_INREG(SDNode *N);
261     SDValue visitFP_EXTEND(SDNode *N);
262     SDValue visitFNEG(SDNode *N);
263     SDValue visitFABS(SDNode *N);
264     SDValue visitFCEIL(SDNode *N);
265     SDValue visitFTRUNC(SDNode *N);
266     SDValue visitFFLOOR(SDNode *N);
267     SDValue visitBRCOND(SDNode *N);
268     SDValue visitBR_CC(SDNode *N);
269     SDValue visitLOAD(SDNode *N);
270     SDValue visitSTORE(SDNode *N);
271     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273     SDValue visitBUILD_VECTOR(SDNode *N);
274     SDValue visitCONCAT_VECTORS(SDNode *N);
275     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276     SDValue visitVECTOR_SHUFFLE(SDNode *N);
277     SDValue visitINSERT_SUBVECTOR(SDNode *N);
278
279     SDValue XformToShuffleWithZero(SDNode *N);
280     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
281
282     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
283
284     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288                              SDValue N3, ISD::CondCode CC,
289                              bool NotExtCompare = false);
290     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291                           SDLoc DL, bool foldBooleans = true);
292
293     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
294                            SDValue &CC) const;
295     bool isOneUseSetCC(SDValue N) const;
296
297     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
298                                          unsigned HiOp);
299     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
300     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
301     SDValue BuildSDIV(SDNode *N);
302     SDValue BuildUDIV(SDNode *N);
303     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
304                                bool DemandHighBits = true);
305     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
306     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
307                               SDValue InnerPos, SDValue InnerNeg,
308                               unsigned PosOpcode, unsigned NegOpcode,
309                               SDLoc DL);
310     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
311     SDValue ReduceLoadWidth(SDNode *N);
312     SDValue ReduceLoadOpStoreWidth(SDNode *N);
313     SDValue TransformFPLoadStorePair(SDNode *N);
314     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
315     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
316
317     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
318
319     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
320     /// looking for aliasing nodes and adding them to the Aliases vector.
321     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
322                           SmallVectorImpl<SDValue> &Aliases);
323
324     /// isAlias - Return true if there is any possibility that the two addresses
325     /// overlap.
326     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
327                  const Value *SrcValue1, int SrcValueOffset1,
328                  unsigned SrcValueAlign1,
329                  const MDNode *TBAAInfo1,
330                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
331                  const Value *SrcValue2, int SrcValueOffset2,
332                  unsigned SrcValueAlign2,
333                  const MDNode *TBAAInfo2) const;
334
335     /// isAlias - Return true if there is any possibility that the two addresses
336     /// overlap.
337     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
338
339     /// FindAliasInfo - Extracts the relevant alias information from the memory
340     /// node.  Returns true if the operand was a load.
341     bool FindAliasInfo(SDNode *N,
342                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
343                        const Value *&SrcValue, int &SrcValueOffset,
344                        unsigned &SrcValueAlignment,
345                        const MDNode *&TBAAInfo) const;
346
347     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
348     /// looking for a better chain (aliasing node.)
349     SDValue FindBetterChain(SDNode *N, SDValue Chain);
350
351     /// Merge consecutive store operations into a wide store.
352     /// This optimization uses wide integers or vectors when possible.
353     /// \return True if some memory operations were changed.
354     bool MergeConsecutiveStores(StoreSDNode *N);
355
356     /// \brief Try to transform a truncation where C is a constant:
357     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
358     ///
359     /// \p N needs to be a truncation and its first operand an AND. Other
360     /// requirements are checked by the function (e.g. that trunc is
361     /// single-use) and if missed an empty SDValue is returned.
362     SDValue distributeTruncateThroughAnd(SDNode *N);
363
364   public:
365     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
366         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
367           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
368       AttributeSet FnAttrs =
369           DAG.getMachineFunction().getFunction()->getAttributes();
370       ForCodeSize =
371           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
372                                Attribute::OptimizeForSize) ||
373           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
374     }
375
376     /// Run - runs the dag combiner on all nodes in the work list
377     void Run(CombineLevel AtLevel);
378
379     SelectionDAG &getDAG() const { return DAG; }
380
381     /// getShiftAmountTy - Returns a type large enough to hold any valid
382     /// shift amount - before type legalization these can be huge.
383     EVT getShiftAmountTy(EVT LHSTy) {
384       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
385       if (LHSTy.isVector())
386         return LHSTy;
387       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
388                         : TLI.getPointerTy();
389     }
390
391     /// isTypeLegal - This method returns true if we are running before type
392     /// legalization or if the specified VT is legal.
393     bool isTypeLegal(const EVT &VT) {
394       if (!LegalTypes) return true;
395       return TLI.isTypeLegal(VT);
396     }
397
398     /// getSetCCResultType - Convenience wrapper around
399     /// TargetLowering::getSetCCResultType
400     EVT getSetCCResultType(EVT VT) const {
401       return TLI.getSetCCResultType(*DAG.getContext(), VT);
402     }
403   };
404 }
405
406
407 namespace {
408 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
409 /// nodes from the worklist.
410 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
411   DAGCombiner &DC;
412 public:
413   explicit WorkListRemover(DAGCombiner &dc)
414     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
415
416   void NodeDeleted(SDNode *N, SDNode *E) override {
417     DC.removeFromWorkList(N);
418   }
419 };
420 }
421
422 //===----------------------------------------------------------------------===//
423 //  TargetLowering::DAGCombinerInfo implementation
424 //===----------------------------------------------------------------------===//
425
426 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
427   ((DAGCombiner*)DC)->AddToWorkList(N);
428 }
429
430 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
431   ((DAGCombiner*)DC)->removeFromWorkList(N);
432 }
433
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
436   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
437 }
438
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
442 }
443
444
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
447   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
448 }
449
450 void TargetLowering::DAGCombinerInfo::
451 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
452   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
453 }
454
455 //===----------------------------------------------------------------------===//
456 // Helper Functions
457 //===----------------------------------------------------------------------===//
458
459 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
460 /// specified expression for the same cost as the expression itself, or 2 if we
461 /// can compute the negated form more cheaply than the expression itself.
462 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
463                                const TargetLowering &TLI,
464                                const TargetOptions *Options,
465                                unsigned Depth = 0) {
466   // fneg is removable even if it has multiple uses.
467   if (Op.getOpcode() == ISD::FNEG) return 2;
468
469   // Don't allow anything with multiple uses.
470   if (!Op.hasOneUse()) return 0;
471
472   // Don't recurse exponentially.
473   if (Depth > 6) return 0;
474
475   switch (Op.getOpcode()) {
476   default: return false;
477   case ISD::ConstantFP:
478     // Don't invert constant FP values after legalize.  The negated constant
479     // isn't necessarily legal.
480     return LegalOperations ? 0 : 1;
481   case ISD::FADD:
482     // FIXME: determine better conditions for this xform.
483     if (!Options->UnsafeFPMath) return 0;
484
485     // After operation legalization, it might not be legal to create new FSUBs.
486     if (LegalOperations &&
487         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
488       return 0;
489
490     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
491     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
492                                     Options, Depth + 1))
493       return V;
494     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
495     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
496                               Depth + 1);
497   case ISD::FSUB:
498     // We can't turn -(A-B) into B-A when we honor signed zeros.
499     if (!Options->UnsafeFPMath) return 0;
500
501     // fold (fneg (fsub A, B)) -> (fsub B, A)
502     return 1;
503
504   case ISD::FMUL:
505   case ISD::FDIV:
506     if (Options->HonorSignDependentRoundingFPMath()) return 0;
507
508     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
509     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
510                                     Options, Depth + 1))
511       return V;
512
513     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514                               Depth + 1);
515
516   case ISD::FP_EXTEND:
517   case ISD::FP_ROUND:
518   case ISD::FSIN:
519     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
520                               Depth + 1);
521   }
522 }
523
524 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
525 /// returns the newly negated expression.
526 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
527                                     bool LegalOperations, unsigned Depth = 0) {
528   // fneg is removable even if it has multiple uses.
529   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
530
531   // Don't allow anything with multiple uses.
532   assert(Op.hasOneUse() && "Unknown reuse!");
533
534   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
535   switch (Op.getOpcode()) {
536   default: llvm_unreachable("Unknown code");
537   case ISD::ConstantFP: {
538     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
539     V.changeSign();
540     return DAG.getConstantFP(V, Op.getValueType());
541   }
542   case ISD::FADD:
543     // FIXME: determine better conditions for this xform.
544     assert(DAG.getTarget().Options.UnsafeFPMath);
545
546     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
547     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
548                            DAG.getTargetLoweringInfo(),
549                            &DAG.getTarget().Options, Depth+1))
550       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551                          GetNegatedExpression(Op.getOperand(0), DAG,
552                                               LegalOperations, Depth+1),
553                          Op.getOperand(1));
554     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
555     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
556                        GetNegatedExpression(Op.getOperand(1), DAG,
557                                             LegalOperations, Depth+1),
558                        Op.getOperand(0));
559   case ISD::FSUB:
560     // We can't turn -(A-B) into B-A when we honor signed zeros.
561     assert(DAG.getTarget().Options.UnsafeFPMath);
562
563     // fold (fneg (fsub 0, B)) -> B
564     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
565       if (N0CFP->getValueAPF().isZero())
566         return Op.getOperand(1);
567
568     // fold (fneg (fsub A, B)) -> (fsub B, A)
569     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
570                        Op.getOperand(1), Op.getOperand(0));
571
572   case ISD::FMUL:
573   case ISD::FDIV:
574     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
575
576     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
577     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
578                            DAG.getTargetLoweringInfo(),
579                            &DAG.getTarget().Options, Depth+1))
580       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
581                          GetNegatedExpression(Op.getOperand(0), DAG,
582                                               LegalOperations, Depth+1),
583                          Op.getOperand(1));
584
585     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
586     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
587                        Op.getOperand(0),
588                        GetNegatedExpression(Op.getOperand(1), DAG,
589                                             LegalOperations, Depth+1));
590
591   case ISD::FP_EXTEND:
592   case ISD::FSIN:
593     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
594                        GetNegatedExpression(Op.getOperand(0), DAG,
595                                             LegalOperations, Depth+1));
596   case ISD::FP_ROUND:
597       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
598                          GetNegatedExpression(Op.getOperand(0), DAG,
599                                               LegalOperations, Depth+1),
600                          Op.getOperand(1));
601   }
602 }
603
604 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
605 // that selects between the target values used for true and false, making it
606 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
607 // the appropriate nodes based on the type of node we are checking. This
608 // simplifies life a bit for the callers.
609 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
610                                     SDValue &CC) const {
611   if (N.getOpcode() == ISD::SETCC) {
612     LHS = N.getOperand(0);
613     RHS = N.getOperand(1);
614     CC  = N.getOperand(2);
615     return true;
616   }
617
618   if (N.getOpcode() != ISD::SELECT_CC ||
619       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
620       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
621     return false;
622
623   LHS = N.getOperand(0);
624   RHS = N.getOperand(1);
625   CC  = N.getOperand(4);
626   return true;
627 }
628
629 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
630 // one use.  If this is true, it allows the users to invert the operation for
631 // free when it is profitable to do so.
632 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
633   SDValue N0, N1, N2;
634   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
635     return true;
636   return false;
637 }
638
639 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
640 /// elements are all the same constant or undefined.
641 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
642   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
643   if (!C)
644     return false;
645
646   APInt SplatUndef;
647   unsigned SplatBitSize;
648   bool HasAnyUndefs;
649   EVT EltVT = N->getValueType(0).getVectorElementType();
650   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
651                              HasAnyUndefs) &&
652           EltVT.getSizeInBits() >= SplatBitSize);
653 }
654
655 // \brief Returns the SDNode if it is a constant BuildVector or constant.
656 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
657   if (isa<ConstantSDNode>(N))
658     return N.getNode();
659   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
660   if(BV && BV->isConstant())
661     return BV;
662   return NULL;
663 }
664
665 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
666 // int.
667 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
668   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
669     return CN;
670
671   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
672     return BV->getConstantSplatValue();
673
674   return nullptr;
675 }
676
677 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
678                                     SDValue N0, SDValue N1) {
679   EVT VT = N0.getValueType();
680   if (N0.getOpcode() == Opc) {
681     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
682       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
683         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
684         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
685         if (!OpNode.getNode())
686           return SDValue();
687         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
688       }
689       if (N0.hasOneUse()) {
690         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
691         // use
692         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
693         if (!OpNode.getNode())
694           return SDValue();
695         AddToWorkList(OpNode.getNode());
696         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
697       }
698     }
699   }
700
701   if (N1.getOpcode() == Opc) {
702     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
703       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
704         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
705         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
706         if (!OpNode.getNode())
707           return SDValue();
708         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
709       }
710       if (N1.hasOneUse()) {
711         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
712         // use
713         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
714         if (!OpNode.getNode())
715           return SDValue();
716         AddToWorkList(OpNode.getNode());
717         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
718       }
719     }
720   }
721
722   return SDValue();
723 }
724
725 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
726                                bool AddTo) {
727   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
728   ++NodesCombined;
729   DEBUG(dbgs() << "\nReplacing.1 ";
730         N->dump(&DAG);
731         dbgs() << "\nWith: ";
732         To[0].getNode()->dump(&DAG);
733         dbgs() << " and " << NumTo-1 << " other values\n";
734         for (unsigned i = 0, e = NumTo; i != e; ++i)
735           assert((!To[i].getNode() ||
736                   N->getValueType(i) == To[i].getValueType()) &&
737                  "Cannot combine value to value of different type!"));
738   WorkListRemover DeadNodes(*this);
739   DAG.ReplaceAllUsesWith(N, To);
740   if (AddTo) {
741     // Push the new nodes and any users onto the worklist
742     for (unsigned i = 0, e = NumTo; i != e; ++i) {
743       if (To[i].getNode()) {
744         AddToWorkList(To[i].getNode());
745         AddUsersToWorkList(To[i].getNode());
746       }
747     }
748   }
749
750   // Finally, if the node is now dead, remove it from the graph.  The node
751   // may not be dead if the replacement process recursively simplified to
752   // something else needing this node.
753   if (N->use_empty()) {
754     // Nodes can be reintroduced into the worklist.  Make sure we do not
755     // process a node that has been replaced.
756     removeFromWorkList(N);
757
758     // Finally, since the node is now dead, remove it from the graph.
759     DAG.DeleteNode(N);
760   }
761   return SDValue(N, 0);
762 }
763
764 void DAGCombiner::
765 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
766   // Replace all uses.  If any nodes become isomorphic to other nodes and
767   // are deleted, make sure to remove them from our worklist.
768   WorkListRemover DeadNodes(*this);
769   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
770
771   // Push the new node and any (possibly new) users onto the worklist.
772   AddToWorkList(TLO.New.getNode());
773   AddUsersToWorkList(TLO.New.getNode());
774
775   // Finally, if the node is now dead, remove it from the graph.  The node
776   // may not be dead if the replacement process recursively simplified to
777   // something else needing this node.
778   if (TLO.Old.getNode()->use_empty()) {
779     removeFromWorkList(TLO.Old.getNode());
780
781     // If the operands of this node are only used by the node, they will now
782     // be dead.  Make sure to visit them first to delete dead nodes early.
783     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
784       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
785         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
786
787     DAG.DeleteNode(TLO.Old.getNode());
788   }
789 }
790
791 /// SimplifyDemandedBits - Check the specified integer node value to see if
792 /// it can be simplified or if things it uses can be simplified by bit
793 /// propagation.  If so, return true.
794 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
795   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
796   APInt KnownZero, KnownOne;
797   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
798     return false;
799
800   // Revisit the node.
801   AddToWorkList(Op.getNode());
802
803   // Replace the old value with the new one.
804   ++NodesCombined;
805   DEBUG(dbgs() << "\nReplacing.2 ";
806         TLO.Old.getNode()->dump(&DAG);
807         dbgs() << "\nWith: ";
808         TLO.New.getNode()->dump(&DAG);
809         dbgs() << '\n');
810
811   CommitTargetLoweringOpt(TLO);
812   return true;
813 }
814
815 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
816   SDLoc dl(Load);
817   EVT VT = Load->getValueType(0);
818   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
819
820   DEBUG(dbgs() << "\nReplacing.9 ";
821         Load->dump(&DAG);
822         dbgs() << "\nWith: ";
823         Trunc.getNode()->dump(&DAG);
824         dbgs() << '\n');
825   WorkListRemover DeadNodes(*this);
826   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
827   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
828   removeFromWorkList(Load);
829   DAG.DeleteNode(Load);
830   AddToWorkList(Trunc.getNode());
831 }
832
833 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
834   Replace = false;
835   SDLoc dl(Op);
836   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
837     EVT MemVT = LD->getMemoryVT();
838     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
839       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
840                                                   : ISD::EXTLOAD)
841       : LD->getExtensionType();
842     Replace = true;
843     return DAG.getExtLoad(ExtType, dl, PVT,
844                           LD->getChain(), LD->getBasePtr(),
845                           MemVT, LD->getMemOperand());
846   }
847
848   unsigned Opc = Op.getOpcode();
849   switch (Opc) {
850   default: break;
851   case ISD::AssertSext:
852     return DAG.getNode(ISD::AssertSext, dl, PVT,
853                        SExtPromoteOperand(Op.getOperand(0), PVT),
854                        Op.getOperand(1));
855   case ISD::AssertZext:
856     return DAG.getNode(ISD::AssertZext, dl, PVT,
857                        ZExtPromoteOperand(Op.getOperand(0), PVT),
858                        Op.getOperand(1));
859   case ISD::Constant: {
860     unsigned ExtOpc =
861       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
862     return DAG.getNode(ExtOpc, dl, PVT, Op);
863   }
864   }
865
866   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
867     return SDValue();
868   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
869 }
870
871 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
872   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
873     return SDValue();
874   EVT OldVT = Op.getValueType();
875   SDLoc dl(Op);
876   bool Replace = false;
877   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
878   if (NewOp.getNode() == 0)
879     return SDValue();
880   AddToWorkList(NewOp.getNode());
881
882   if (Replace)
883     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
884   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
885                      DAG.getValueType(OldVT));
886 }
887
888 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
889   EVT OldVT = Op.getValueType();
890   SDLoc dl(Op);
891   bool Replace = false;
892   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
893   if (NewOp.getNode() == 0)
894     return SDValue();
895   AddToWorkList(NewOp.getNode());
896
897   if (Replace)
898     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
899   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
900 }
901
902 /// PromoteIntBinOp - Promote the specified integer binary operation if the
903 /// target indicates it is beneficial. e.g. On x86, it's usually better to
904 /// promote i16 operations to i32 since i16 instructions are longer.
905 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
906   if (!LegalOperations)
907     return SDValue();
908
909   EVT VT = Op.getValueType();
910   if (VT.isVector() || !VT.isInteger())
911     return SDValue();
912
913   // If operation type is 'undesirable', e.g. i16 on x86, consider
914   // promoting it.
915   unsigned Opc = Op.getOpcode();
916   if (TLI.isTypeDesirableForOp(Opc, VT))
917     return SDValue();
918
919   EVT PVT = VT;
920   // Consult target whether it is a good idea to promote this operation and
921   // what's the right type to promote it to.
922   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
923     assert(PVT != VT && "Don't know what type to promote to!");
924
925     bool Replace0 = false;
926     SDValue N0 = Op.getOperand(0);
927     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
928     if (NN0.getNode() == 0)
929       return SDValue();
930
931     bool Replace1 = false;
932     SDValue N1 = Op.getOperand(1);
933     SDValue NN1;
934     if (N0 == N1)
935       NN1 = NN0;
936     else {
937       NN1 = PromoteOperand(N1, PVT, Replace1);
938       if (NN1.getNode() == 0)
939         return SDValue();
940     }
941
942     AddToWorkList(NN0.getNode());
943     if (NN1.getNode())
944       AddToWorkList(NN1.getNode());
945
946     if (Replace0)
947       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
948     if (Replace1)
949       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
950
951     DEBUG(dbgs() << "\nPromoting ";
952           Op.getNode()->dump(&DAG));
953     SDLoc dl(Op);
954     return DAG.getNode(ISD::TRUNCATE, dl, VT,
955                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
956   }
957   return SDValue();
958 }
959
960 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
961 /// target indicates it is beneficial. e.g. On x86, it's usually better to
962 /// promote i16 operations to i32 since i16 instructions are longer.
963 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
964   if (!LegalOperations)
965     return SDValue();
966
967   EVT VT = Op.getValueType();
968   if (VT.isVector() || !VT.isInteger())
969     return SDValue();
970
971   // If operation type is 'undesirable', e.g. i16 on x86, consider
972   // promoting it.
973   unsigned Opc = Op.getOpcode();
974   if (TLI.isTypeDesirableForOp(Opc, VT))
975     return SDValue();
976
977   EVT PVT = VT;
978   // Consult target whether it is a good idea to promote this operation and
979   // what's the right type to promote it to.
980   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
981     assert(PVT != VT && "Don't know what type to promote to!");
982
983     bool Replace = false;
984     SDValue N0 = Op.getOperand(0);
985     if (Opc == ISD::SRA)
986       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
987     else if (Opc == ISD::SRL)
988       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
989     else
990       N0 = PromoteOperand(N0, PVT, Replace);
991     if (N0.getNode() == 0)
992       return SDValue();
993
994     AddToWorkList(N0.getNode());
995     if (Replace)
996       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
997
998     DEBUG(dbgs() << "\nPromoting ";
999           Op.getNode()->dump(&DAG));
1000     SDLoc dl(Op);
1001     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1002                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1003   }
1004   return SDValue();
1005 }
1006
1007 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1008   if (!LegalOperations)
1009     return SDValue();
1010
1011   EVT VT = Op.getValueType();
1012   if (VT.isVector() || !VT.isInteger())
1013     return SDValue();
1014
1015   // If operation type is 'undesirable', e.g. i16 on x86, consider
1016   // promoting it.
1017   unsigned Opc = Op.getOpcode();
1018   if (TLI.isTypeDesirableForOp(Opc, VT))
1019     return SDValue();
1020
1021   EVT PVT = VT;
1022   // Consult target whether it is a good idea to promote this operation and
1023   // what's the right type to promote it to.
1024   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1025     assert(PVT != VT && "Don't know what type to promote to!");
1026     // fold (aext (aext x)) -> (aext x)
1027     // fold (aext (zext x)) -> (zext x)
1028     // fold (aext (sext x)) -> (sext x)
1029     DEBUG(dbgs() << "\nPromoting ";
1030           Op.getNode()->dump(&DAG));
1031     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1032   }
1033   return SDValue();
1034 }
1035
1036 bool DAGCombiner::PromoteLoad(SDValue Op) {
1037   if (!LegalOperations)
1038     return false;
1039
1040   EVT VT = Op.getValueType();
1041   if (VT.isVector() || !VT.isInteger())
1042     return false;
1043
1044   // If operation type is 'undesirable', e.g. i16 on x86, consider
1045   // promoting it.
1046   unsigned Opc = Op.getOpcode();
1047   if (TLI.isTypeDesirableForOp(Opc, VT))
1048     return false;
1049
1050   EVT PVT = VT;
1051   // Consult target whether it is a good idea to promote this operation and
1052   // what's the right type to promote it to.
1053   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1054     assert(PVT != VT && "Don't know what type to promote to!");
1055
1056     SDLoc dl(Op);
1057     SDNode *N = Op.getNode();
1058     LoadSDNode *LD = cast<LoadSDNode>(N);
1059     EVT MemVT = LD->getMemoryVT();
1060     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1061       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1062                                                   : ISD::EXTLOAD)
1063       : LD->getExtensionType();
1064     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1065                                    LD->getChain(), LD->getBasePtr(),
1066                                    MemVT, LD->getMemOperand());
1067     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1068
1069     DEBUG(dbgs() << "\nPromoting ";
1070           N->dump(&DAG);
1071           dbgs() << "\nTo: ";
1072           Result.getNode()->dump(&DAG);
1073           dbgs() << '\n');
1074     WorkListRemover DeadNodes(*this);
1075     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1076     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1077     removeFromWorkList(N);
1078     DAG.DeleteNode(N);
1079     AddToWorkList(Result.getNode());
1080     return true;
1081   }
1082   return false;
1083 }
1084
1085
1086 //===----------------------------------------------------------------------===//
1087 //  Main DAG Combiner implementation
1088 //===----------------------------------------------------------------------===//
1089
1090 void DAGCombiner::Run(CombineLevel AtLevel) {
1091   // set the instance variables, so that the various visit routines may use it.
1092   Level = AtLevel;
1093   LegalOperations = Level >= AfterLegalizeVectorOps;
1094   LegalTypes = Level >= AfterLegalizeTypes;
1095
1096   // Add all the dag nodes to the worklist.
1097   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1098        E = DAG.allnodes_end(); I != E; ++I)
1099     AddToWorkList(I);
1100
1101   // Create a dummy node (which is not added to allnodes), that adds a reference
1102   // to the root node, preventing it from being deleted, and tracking any
1103   // changes of the root.
1104   HandleSDNode Dummy(DAG.getRoot());
1105
1106   // The root of the dag may dangle to deleted nodes until the dag combiner is
1107   // done.  Set it to null to avoid confusion.
1108   DAG.setRoot(SDValue());
1109
1110   // while the worklist isn't empty, find a node and
1111   // try and combine it.
1112   while (!WorkListContents.empty()) {
1113     SDNode *N;
1114     // The WorkListOrder holds the SDNodes in order, but it may contain
1115     // duplicates.
1116     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1117     // worklist *should* contain, and check the node we want to visit is should
1118     // actually be visited.
1119     do {
1120       N = WorkListOrder.pop_back_val();
1121     } while (!WorkListContents.erase(N));
1122
1123     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1124     // N is deleted from the DAG, since they too may now be dead or may have a
1125     // reduced number of uses, allowing other xforms.
1126     if (N->use_empty() && N != &Dummy) {
1127       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1128         AddToWorkList(N->getOperand(i).getNode());
1129
1130       DAG.DeleteNode(N);
1131       continue;
1132     }
1133
1134     SDValue RV = combine(N);
1135
1136     if (RV.getNode() == 0)
1137       continue;
1138
1139     ++NodesCombined;
1140
1141     // If we get back the same node we passed in, rather than a new node or
1142     // zero, we know that the node must have defined multiple values and
1143     // CombineTo was used.  Since CombineTo takes care of the worklist
1144     // mechanics for us, we have no work to do in this case.
1145     if (RV.getNode() == N)
1146       continue;
1147
1148     assert(N->getOpcode() != ISD::DELETED_NODE &&
1149            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1150            "Node was deleted but visit returned new node!");
1151
1152     DEBUG(dbgs() << "\nReplacing.3 ";
1153           N->dump(&DAG);
1154           dbgs() << "\nWith: ";
1155           RV.getNode()->dump(&DAG);
1156           dbgs() << '\n');
1157
1158     // Transfer debug value.
1159     DAG.TransferDbgValues(SDValue(N, 0), RV);
1160     WorkListRemover DeadNodes(*this);
1161     if (N->getNumValues() == RV.getNode()->getNumValues())
1162       DAG.ReplaceAllUsesWith(N, RV.getNode());
1163     else {
1164       assert(N->getValueType(0) == RV.getValueType() &&
1165              N->getNumValues() == 1 && "Type mismatch");
1166       SDValue OpV = RV;
1167       DAG.ReplaceAllUsesWith(N, &OpV);
1168     }
1169
1170     // Push the new node and any users onto the worklist
1171     AddToWorkList(RV.getNode());
1172     AddUsersToWorkList(RV.getNode());
1173
1174     // Add any uses of the old node to the worklist in case this node is the
1175     // last one that uses them.  They may become dead after this node is
1176     // deleted.
1177     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178       AddToWorkList(N->getOperand(i).getNode());
1179
1180     // Finally, if the node is now dead, remove it from the graph.  The node
1181     // may not be dead if the replacement process recursively simplified to
1182     // something else needing this node.
1183     if (N->use_empty()) {
1184       // Nodes can be reintroduced into the worklist.  Make sure we do not
1185       // process a node that has been replaced.
1186       removeFromWorkList(N);
1187
1188       // Finally, since the node is now dead, remove it from the graph.
1189       DAG.DeleteNode(N);
1190     }
1191   }
1192
1193   // If the root changed (e.g. it was a dead load, update the root).
1194   DAG.setRoot(Dummy.getValue());
1195   DAG.RemoveDeadNodes();
1196 }
1197
1198 SDValue DAGCombiner::visit(SDNode *N) {
1199   switch (N->getOpcode()) {
1200   default: break;
1201   case ISD::TokenFactor:        return visitTokenFactor(N);
1202   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1203   case ISD::ADD:                return visitADD(N);
1204   case ISD::SUB:                return visitSUB(N);
1205   case ISD::ADDC:               return visitADDC(N);
1206   case ISD::SUBC:               return visitSUBC(N);
1207   case ISD::ADDE:               return visitADDE(N);
1208   case ISD::SUBE:               return visitSUBE(N);
1209   case ISD::MUL:                return visitMUL(N);
1210   case ISD::SDIV:               return visitSDIV(N);
1211   case ISD::UDIV:               return visitUDIV(N);
1212   case ISD::SREM:               return visitSREM(N);
1213   case ISD::UREM:               return visitUREM(N);
1214   case ISD::MULHU:              return visitMULHU(N);
1215   case ISD::MULHS:              return visitMULHS(N);
1216   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1217   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1218   case ISD::SMULO:              return visitSMULO(N);
1219   case ISD::UMULO:              return visitUMULO(N);
1220   case ISD::SDIVREM:            return visitSDIVREM(N);
1221   case ISD::UDIVREM:            return visitUDIVREM(N);
1222   case ISD::AND:                return visitAND(N);
1223   case ISD::OR:                 return visitOR(N);
1224   case ISD::XOR:                return visitXOR(N);
1225   case ISD::SHL:                return visitSHL(N);
1226   case ISD::SRA:                return visitSRA(N);
1227   case ISD::SRL:                return visitSRL(N);
1228   case ISD::ROTR:
1229   case ISD::ROTL:               return visitRotate(N);
1230   case ISD::CTLZ:               return visitCTLZ(N);
1231   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1232   case ISD::CTTZ:               return visitCTTZ(N);
1233   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1234   case ISD::CTPOP:              return visitCTPOP(N);
1235   case ISD::SELECT:             return visitSELECT(N);
1236   case ISD::VSELECT:            return visitVSELECT(N);
1237   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1238   case ISD::SETCC:              return visitSETCC(N);
1239   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1240   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1241   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1242   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1243   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1244   case ISD::BITCAST:            return visitBITCAST(N);
1245   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1246   case ISD::FADD:               return visitFADD(N);
1247   case ISD::FSUB:               return visitFSUB(N);
1248   case ISD::FMUL:               return visitFMUL(N);
1249   case ISD::FMA:                return visitFMA(N);
1250   case ISD::FDIV:               return visitFDIV(N);
1251   case ISD::FREM:               return visitFREM(N);
1252   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1253   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1254   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1255   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1256   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1257   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1258   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1259   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1260   case ISD::FNEG:               return visitFNEG(N);
1261   case ISD::FABS:               return visitFABS(N);
1262   case ISD::FFLOOR:             return visitFFLOOR(N);
1263   case ISD::FCEIL:              return visitFCEIL(N);
1264   case ISD::FTRUNC:             return visitFTRUNC(N);
1265   case ISD::BRCOND:             return visitBRCOND(N);
1266   case ISD::BR_CC:              return visitBR_CC(N);
1267   case ISD::LOAD:               return visitLOAD(N);
1268   case ISD::STORE:              return visitSTORE(N);
1269   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1270   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1271   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1272   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1273   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1274   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1275   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1276   }
1277   return SDValue();
1278 }
1279
1280 SDValue DAGCombiner::combine(SDNode *N) {
1281   SDValue RV = visit(N);
1282
1283   // If nothing happened, try a target-specific DAG combine.
1284   if (RV.getNode() == 0) {
1285     assert(N->getOpcode() != ISD::DELETED_NODE &&
1286            "Node was deleted but visit returned NULL!");
1287
1288     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1289         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1290
1291       // Expose the DAG combiner to the target combiner impls.
1292       TargetLowering::DAGCombinerInfo
1293         DagCombineInfo(DAG, Level, false, this);
1294
1295       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1296     }
1297   }
1298
1299   // If nothing happened still, try promoting the operation.
1300   if (RV.getNode() == 0) {
1301     switch (N->getOpcode()) {
1302     default: break;
1303     case ISD::ADD:
1304     case ISD::SUB:
1305     case ISD::MUL:
1306     case ISD::AND:
1307     case ISD::OR:
1308     case ISD::XOR:
1309       RV = PromoteIntBinOp(SDValue(N, 0));
1310       break;
1311     case ISD::SHL:
1312     case ISD::SRA:
1313     case ISD::SRL:
1314       RV = PromoteIntShiftOp(SDValue(N, 0));
1315       break;
1316     case ISD::SIGN_EXTEND:
1317     case ISD::ZERO_EXTEND:
1318     case ISD::ANY_EXTEND:
1319       RV = PromoteExtend(SDValue(N, 0));
1320       break;
1321     case ISD::LOAD:
1322       if (PromoteLoad(SDValue(N, 0)))
1323         RV = SDValue(N, 0);
1324       break;
1325     }
1326   }
1327
1328   // If N is a commutative binary node, try commuting it to enable more
1329   // sdisel CSE.
1330   if (RV.getNode() == 0 &&
1331       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1332       N->getNumValues() == 1) {
1333     SDValue N0 = N->getOperand(0);
1334     SDValue N1 = N->getOperand(1);
1335
1336     // Constant operands are canonicalized to RHS.
1337     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1338       SDValue Ops[] = { N1, N0 };
1339       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1340                                             Ops, 2);
1341       if (CSENode)
1342         return SDValue(CSENode, 0);
1343     }
1344   }
1345
1346   return RV;
1347 }
1348
1349 /// getInputChainForNode - Given a node, return its input chain if it has one,
1350 /// otherwise return a null sd operand.
1351 static SDValue getInputChainForNode(SDNode *N) {
1352   if (unsigned NumOps = N->getNumOperands()) {
1353     if (N->getOperand(0).getValueType() == MVT::Other)
1354       return N->getOperand(0);
1355     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1356       return N->getOperand(NumOps-1);
1357     for (unsigned i = 1; i < NumOps-1; ++i)
1358       if (N->getOperand(i).getValueType() == MVT::Other)
1359         return N->getOperand(i);
1360   }
1361   return SDValue();
1362 }
1363
1364 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1365   // If N has two operands, where one has an input chain equal to the other,
1366   // the 'other' chain is redundant.
1367   if (N->getNumOperands() == 2) {
1368     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1369       return N->getOperand(0);
1370     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1371       return N->getOperand(1);
1372   }
1373
1374   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1375   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1376   SmallPtrSet<SDNode*, 16> SeenOps;
1377   bool Changed = false;             // If we should replace this token factor.
1378
1379   // Start out with this token factor.
1380   TFs.push_back(N);
1381
1382   // Iterate through token factors.  The TFs grows when new token factors are
1383   // encountered.
1384   for (unsigned i = 0; i < TFs.size(); ++i) {
1385     SDNode *TF = TFs[i];
1386
1387     // Check each of the operands.
1388     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1389       SDValue Op = TF->getOperand(i);
1390
1391       switch (Op.getOpcode()) {
1392       case ISD::EntryToken:
1393         // Entry tokens don't need to be added to the list. They are
1394         // rededundant.
1395         Changed = true;
1396         break;
1397
1398       case ISD::TokenFactor:
1399         if (Op.hasOneUse() &&
1400             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1401           // Queue up for processing.
1402           TFs.push_back(Op.getNode());
1403           // Clean up in case the token factor is removed.
1404           AddToWorkList(Op.getNode());
1405           Changed = true;
1406           break;
1407         }
1408         // Fall thru
1409
1410       default:
1411         // Only add if it isn't already in the list.
1412         if (SeenOps.insert(Op.getNode()))
1413           Ops.push_back(Op);
1414         else
1415           Changed = true;
1416         break;
1417       }
1418     }
1419   }
1420
1421   SDValue Result;
1422
1423   // If we've change things around then replace token factor.
1424   if (Changed) {
1425     if (Ops.empty()) {
1426       // The entry token is the only possible outcome.
1427       Result = DAG.getEntryNode();
1428     } else {
1429       // New and improved token factor.
1430       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1431                            MVT::Other, &Ops[0], Ops.size());
1432     }
1433
1434     // Don't add users to work list.
1435     return CombineTo(N, Result, false);
1436   }
1437
1438   return Result;
1439 }
1440
1441 /// MERGE_VALUES can always be eliminated.
1442 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1443   WorkListRemover DeadNodes(*this);
1444   // Replacing results may cause a different MERGE_VALUES to suddenly
1445   // be CSE'd with N, and carry its uses with it. Iterate until no
1446   // uses remain, to ensure that the node can be safely deleted.
1447   // First add the users of this node to the work list so that they
1448   // can be tried again once they have new operands.
1449   AddUsersToWorkList(N);
1450   do {
1451     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1452       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1453   } while (!N->use_empty());
1454   removeFromWorkList(N);
1455   DAG.DeleteNode(N);
1456   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1457 }
1458
1459 static
1460 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1461                               SelectionDAG &DAG) {
1462   EVT VT = N0.getValueType();
1463   SDValue N00 = N0.getOperand(0);
1464   SDValue N01 = N0.getOperand(1);
1465   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1466
1467   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1468       isa<ConstantSDNode>(N00.getOperand(1))) {
1469     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1470     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1471                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1472                                  N00.getOperand(0), N01),
1473                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1474                                  N00.getOperand(1), N01));
1475     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1476   }
1477
1478   return SDValue();
1479 }
1480
1481 SDValue DAGCombiner::visitADD(SDNode *N) {
1482   SDValue N0 = N->getOperand(0);
1483   SDValue N1 = N->getOperand(1);
1484   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1485   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1486   EVT VT = N0.getValueType();
1487
1488   // fold vector ops
1489   if (VT.isVector()) {
1490     SDValue FoldedVOp = SimplifyVBinOp(N);
1491     if (FoldedVOp.getNode()) return FoldedVOp;
1492
1493     // fold (add x, 0) -> x, vector edition
1494     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1495       return N0;
1496     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1497       return N1;
1498   }
1499
1500   // fold (add x, undef) -> undef
1501   if (N0.getOpcode() == ISD::UNDEF)
1502     return N0;
1503   if (N1.getOpcode() == ISD::UNDEF)
1504     return N1;
1505   // fold (add c1, c2) -> c1+c2
1506   if (N0C && N1C)
1507     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1508   // canonicalize constant to RHS
1509   if (N0C && !N1C)
1510     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1511   // fold (add x, 0) -> x
1512   if (N1C && N1C->isNullValue())
1513     return N0;
1514   // fold (add Sym, c) -> Sym+c
1515   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1516     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1517         GA->getOpcode() == ISD::GlobalAddress)
1518       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1519                                   GA->getOffset() +
1520                                     (uint64_t)N1C->getSExtValue());
1521   // fold ((c1-A)+c2) -> (c1+c2)-A
1522   if (N1C && N0.getOpcode() == ISD::SUB)
1523     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1524       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1525                          DAG.getConstant(N1C->getAPIntValue()+
1526                                          N0C->getAPIntValue(), VT),
1527                          N0.getOperand(1));
1528   // reassociate add
1529   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1530   if (RADD.getNode() != 0)
1531     return RADD;
1532   // fold ((0-A) + B) -> B-A
1533   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1534       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1535     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1536   // fold (A + (0-B)) -> A-B
1537   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1538       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1539     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1540   // fold (A+(B-A)) -> B
1541   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1542     return N1.getOperand(0);
1543   // fold ((B-A)+A) -> B
1544   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1545     return N0.getOperand(0);
1546   // fold (A+(B-(A+C))) to (B-C)
1547   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548       N0 == N1.getOperand(1).getOperand(0))
1549     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550                        N1.getOperand(1).getOperand(1));
1551   // fold (A+(B-(C+A))) to (B-C)
1552   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1553       N0 == N1.getOperand(1).getOperand(1))
1554     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1555                        N1.getOperand(1).getOperand(0));
1556   // fold (A+((B-A)+or-C)) to (B+or-C)
1557   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1558       N1.getOperand(0).getOpcode() == ISD::SUB &&
1559       N0 == N1.getOperand(0).getOperand(1))
1560     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1561                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1562
1563   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1564   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1565     SDValue N00 = N0.getOperand(0);
1566     SDValue N01 = N0.getOperand(1);
1567     SDValue N10 = N1.getOperand(0);
1568     SDValue N11 = N1.getOperand(1);
1569
1570     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1571       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1572                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1573                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1574   }
1575
1576   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1577     return SDValue(N, 0);
1578
1579   // fold (a+b) -> (a|b) iff a and b share no bits.
1580   if (VT.isInteger() && !VT.isVector()) {
1581     APInt LHSZero, LHSOne;
1582     APInt RHSZero, RHSOne;
1583     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1584
1585     if (LHSZero.getBoolValue()) {
1586       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1587
1588       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1589       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1590       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1591         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1592           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1593       }
1594     }
1595   }
1596
1597   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1598   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1599     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1600     if (Result.getNode()) return Result;
1601   }
1602   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1603     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1604     if (Result.getNode()) return Result;
1605   }
1606
1607   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1608   if (N1.getOpcode() == ISD::SHL &&
1609       N1.getOperand(0).getOpcode() == ISD::SUB)
1610     if (ConstantSDNode *C =
1611           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1612       if (C->getAPIntValue() == 0)
1613         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1614                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1615                                        N1.getOperand(0).getOperand(1),
1616                                        N1.getOperand(1)));
1617   if (N0.getOpcode() == ISD::SHL &&
1618       N0.getOperand(0).getOpcode() == ISD::SUB)
1619     if (ConstantSDNode *C =
1620           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1621       if (C->getAPIntValue() == 0)
1622         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1623                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1624                                        N0.getOperand(0).getOperand(1),
1625                                        N0.getOperand(1)));
1626
1627   if (N1.getOpcode() == ISD::AND) {
1628     SDValue AndOp0 = N1.getOperand(0);
1629     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1630     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1631     unsigned DestBits = VT.getScalarType().getSizeInBits();
1632
1633     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1634     // and similar xforms where the inner op is either ~0 or 0.
1635     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1636       SDLoc DL(N);
1637       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1638     }
1639   }
1640
1641   // add (sext i1), X -> sub X, (zext i1)
1642   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1643       N0.getOperand(0).getValueType() == MVT::i1 &&
1644       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1645     SDLoc DL(N);
1646     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1647     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1648   }
1649
1650   return SDValue();
1651 }
1652
1653 SDValue DAGCombiner::visitADDC(SDNode *N) {
1654   SDValue N0 = N->getOperand(0);
1655   SDValue N1 = N->getOperand(1);
1656   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1657   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1658   EVT VT = N0.getValueType();
1659
1660   // If the flag result is dead, turn this into an ADD.
1661   if (!N->hasAnyUseOfValue(1))
1662     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1663                      DAG.getNode(ISD::CARRY_FALSE,
1664                                  SDLoc(N), MVT::Glue));
1665
1666   // canonicalize constant to RHS.
1667   if (N0C && !N1C)
1668     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1669
1670   // fold (addc x, 0) -> x + no carry out
1671   if (N1C && N1C->isNullValue())
1672     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1673                                         SDLoc(N), MVT::Glue));
1674
1675   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1676   APInt LHSZero, LHSOne;
1677   APInt RHSZero, RHSOne;
1678   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1679
1680   if (LHSZero.getBoolValue()) {
1681     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1682
1683     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1684     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1685     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1686       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1687                        DAG.getNode(ISD::CARRY_FALSE,
1688                                    SDLoc(N), MVT::Glue));
1689   }
1690
1691   return SDValue();
1692 }
1693
1694 SDValue DAGCombiner::visitADDE(SDNode *N) {
1695   SDValue N0 = N->getOperand(0);
1696   SDValue N1 = N->getOperand(1);
1697   SDValue CarryIn = N->getOperand(2);
1698   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1699   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1700
1701   // canonicalize constant to RHS
1702   if (N0C && !N1C)
1703     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1704                        N1, N0, CarryIn);
1705
1706   // fold (adde x, y, false) -> (addc x, y)
1707   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1708     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1709
1710   return SDValue();
1711 }
1712
1713 // Since it may not be valid to emit a fold to zero for vector initializers
1714 // check if we can before folding.
1715 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1716                              SelectionDAG &DAG,
1717                              bool LegalOperations, bool LegalTypes) {
1718   if (!VT.isVector())
1719     return DAG.getConstant(0, VT);
1720   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1721     return DAG.getConstant(0, VT);
1722   return SDValue();
1723 }
1724
1725 SDValue DAGCombiner::visitSUB(SDNode *N) {
1726   SDValue N0 = N->getOperand(0);
1727   SDValue N1 = N->getOperand(1);
1728   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1729   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1730   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1731     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1732   EVT VT = N0.getValueType();
1733
1734   // fold vector ops
1735   if (VT.isVector()) {
1736     SDValue FoldedVOp = SimplifyVBinOp(N);
1737     if (FoldedVOp.getNode()) return FoldedVOp;
1738
1739     // fold (sub x, 0) -> x, vector edition
1740     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1741       return N0;
1742   }
1743
1744   // fold (sub x, x) -> 0
1745   // FIXME: Refactor this and xor and other similar operations together.
1746   if (N0 == N1)
1747     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1748   // fold (sub c1, c2) -> c1-c2
1749   if (N0C && N1C)
1750     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1751   // fold (sub x, c) -> (add x, -c)
1752   if (N1C)
1753     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1754                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1755   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1756   if (N0C && N0C->isAllOnesValue())
1757     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1758   // fold A-(A-B) -> B
1759   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1760     return N1.getOperand(1);
1761   // fold (A+B)-A -> B
1762   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1763     return N0.getOperand(1);
1764   // fold (A+B)-B -> A
1765   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1766     return N0.getOperand(0);
1767   // fold C2-(A+C1) -> (C2-C1)-A
1768   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1769     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1770                                    VT);
1771     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1772                        N1.getOperand(0));
1773   }
1774   // fold ((A+(B+or-C))-B) -> A+or-C
1775   if (N0.getOpcode() == ISD::ADD &&
1776       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1777        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1778       N0.getOperand(1).getOperand(0) == N1)
1779     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1780                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1781   // fold ((A+(C+B))-B) -> A+C
1782   if (N0.getOpcode() == ISD::ADD &&
1783       N0.getOperand(1).getOpcode() == ISD::ADD &&
1784       N0.getOperand(1).getOperand(1) == N1)
1785     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1786                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1787   // fold ((A-(B-C))-C) -> A-B
1788   if (N0.getOpcode() == ISD::SUB &&
1789       N0.getOperand(1).getOpcode() == ISD::SUB &&
1790       N0.getOperand(1).getOperand(1) == N1)
1791     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1792                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1793
1794   // If either operand of a sub is undef, the result is undef
1795   if (N0.getOpcode() == ISD::UNDEF)
1796     return N0;
1797   if (N1.getOpcode() == ISD::UNDEF)
1798     return N1;
1799
1800   // If the relocation model supports it, consider symbol offsets.
1801   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1802     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1803       // fold (sub Sym, c) -> Sym-c
1804       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1805         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1806                                     GA->getOffset() -
1807                                       (uint64_t)N1C->getSExtValue());
1808       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1809       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1810         if (GA->getGlobal() == GB->getGlobal())
1811           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1812                                  VT);
1813     }
1814
1815   return SDValue();
1816 }
1817
1818 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1819   SDValue N0 = N->getOperand(0);
1820   SDValue N1 = N->getOperand(1);
1821   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1822   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1823   EVT VT = N0.getValueType();
1824
1825   // If the flag result is dead, turn this into an SUB.
1826   if (!N->hasAnyUseOfValue(1))
1827     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1828                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1829                                  MVT::Glue));
1830
1831   // fold (subc x, x) -> 0 + no borrow
1832   if (N0 == N1)
1833     return CombineTo(N, DAG.getConstant(0, VT),
1834                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835                                  MVT::Glue));
1836
1837   // fold (subc x, 0) -> x + no borrow
1838   if (N1C && N1C->isNullValue())
1839     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1840                                         MVT::Glue));
1841
1842   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1843   if (N0C && N0C->isAllOnesValue())
1844     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1845                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1846                                  MVT::Glue));
1847
1848   return SDValue();
1849 }
1850
1851 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1852   SDValue N0 = N->getOperand(0);
1853   SDValue N1 = N->getOperand(1);
1854   SDValue CarryIn = N->getOperand(2);
1855
1856   // fold (sube x, y, false) -> (subc x, y)
1857   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1858     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1859
1860   return SDValue();
1861 }
1862
1863 SDValue DAGCombiner::visitMUL(SDNode *N) {
1864   SDValue N0 = N->getOperand(0);
1865   SDValue N1 = N->getOperand(1);
1866   EVT VT = N0.getValueType();
1867
1868   // fold (mul x, undef) -> 0
1869   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1870     return DAG.getConstant(0, VT);
1871
1872   bool N0IsConst = false;
1873   bool N1IsConst = false;
1874   APInt ConstValue0, ConstValue1;
1875   // fold vector ops
1876   if (VT.isVector()) {
1877     SDValue FoldedVOp = SimplifyVBinOp(N);
1878     if (FoldedVOp.getNode()) return FoldedVOp;
1879
1880     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1881     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1882   } else {
1883     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1884     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1885                             : APInt();
1886     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1887     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1888                             : APInt();
1889   }
1890
1891   // fold (mul c1, c2) -> c1*c2
1892   if (N0IsConst && N1IsConst)
1893     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1894
1895   // canonicalize constant to RHS
1896   if (N0IsConst && !N1IsConst)
1897     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1898   // fold (mul x, 0) -> 0
1899   if (N1IsConst && ConstValue1 == 0)
1900     return N1;
1901   // We require a splat of the entire scalar bit width for non-contiguous
1902   // bit patterns.
1903   bool IsFullSplat =
1904     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1905   // fold (mul x, 1) -> x
1906   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1907     return N0;
1908   // fold (mul x, -1) -> 0-x
1909   if (N1IsConst && ConstValue1.isAllOnesValue())
1910     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1911                        DAG.getConstant(0, VT), N0);
1912   // fold (mul x, (1 << c)) -> x << c
1913   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1914     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1915                        DAG.getConstant(ConstValue1.logBase2(),
1916                                        getShiftAmountTy(N0.getValueType())));
1917   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1918   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1919     unsigned Log2Val = (-ConstValue1).logBase2();
1920     // FIXME: If the input is something that is easily negated (e.g. a
1921     // single-use add), we should put the negate there.
1922     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1923                        DAG.getConstant(0, VT),
1924                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1925                             DAG.getConstant(Log2Val,
1926                                       getShiftAmountTy(N0.getValueType()))));
1927   }
1928
1929   APInt Val;
1930   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1931   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1932       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1933                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1934     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935                              N1, N0.getOperand(1));
1936     AddToWorkList(C3.getNode());
1937     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1938                        N0.getOperand(0), C3);
1939   }
1940
1941   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1942   // use.
1943   {
1944     SDValue Sh(0,0), Y(0,0);
1945     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1946     if (N0.getOpcode() == ISD::SHL &&
1947         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1948                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1949         N0.getNode()->hasOneUse()) {
1950       Sh = N0; Y = N1;
1951     } else if (N1.getOpcode() == ISD::SHL &&
1952                isa<ConstantSDNode>(N1.getOperand(1)) &&
1953                N1.getNode()->hasOneUse()) {
1954       Sh = N1; Y = N0;
1955     }
1956
1957     if (Sh.getNode()) {
1958       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1959                                 Sh.getOperand(0), Y);
1960       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1961                          Mul, Sh.getOperand(1));
1962     }
1963   }
1964
1965   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1966   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1967       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968                      isa<ConstantSDNode>(N0.getOperand(1))))
1969     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1970                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1971                                    N0.getOperand(0), N1),
1972                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1973                                    N0.getOperand(1), N1));
1974
1975   // reassociate mul
1976   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1977   if (RMUL.getNode() != 0)
1978     return RMUL;
1979
1980   return SDValue();
1981 }
1982
1983 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1984   SDValue N0 = N->getOperand(0);
1985   SDValue N1 = N->getOperand(1);
1986   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1987   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1988   EVT VT = N->getValueType(0);
1989
1990   // fold vector ops
1991   if (VT.isVector()) {
1992     SDValue FoldedVOp = SimplifyVBinOp(N);
1993     if (FoldedVOp.getNode()) return FoldedVOp;
1994   }
1995
1996   // fold (sdiv c1, c2) -> c1/c2
1997   if (N0C && N1C && !N1C->isNullValue())
1998     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1999   // fold (sdiv X, 1) -> X
2000   if (N1C && N1C->getAPIntValue() == 1LL)
2001     return N0;
2002   // fold (sdiv X, -1) -> 0-X
2003   if (N1C && N1C->isAllOnesValue())
2004     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2005                        DAG.getConstant(0, VT), N0);
2006   // If we know the sign bits of both operands are zero, strength reduce to a
2007   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2008   if (!VT.isVector()) {
2009     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2010       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2011                          N0, N1);
2012   }
2013   // fold (sdiv X, pow2) -> simple ops after legalize
2014   if (N1C && !N1C->isNullValue() &&
2015       (N1C->getAPIntValue().isPowerOf2() ||
2016        (-N1C->getAPIntValue()).isPowerOf2())) {
2017     // If dividing by powers of two is cheap, then don't perform the following
2018     // fold.
2019     if (TLI.isPow2DivCheap())
2020       return SDValue();
2021
2022     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2023
2024     // Splat the sign bit into the register
2025     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2026                               DAG.getConstant(VT.getSizeInBits()-1,
2027                                        getShiftAmountTy(N0.getValueType())));
2028     AddToWorkList(SGN.getNode());
2029
2030     // Add (N0 < 0) ? abs2 - 1 : 0;
2031     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2032                               DAG.getConstant(VT.getSizeInBits() - lg2,
2033                                        getShiftAmountTy(SGN.getValueType())));
2034     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2035     AddToWorkList(SRL.getNode());
2036     AddToWorkList(ADD.getNode());    // Divide by pow2
2037     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2038                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2039
2040     // If we're dividing by a positive value, we're done.  Otherwise, we must
2041     // negate the result.
2042     if (N1C->getAPIntValue().isNonNegative())
2043       return SRA;
2044
2045     AddToWorkList(SRA.getNode());
2046     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2047                        DAG.getConstant(0, VT), SRA);
2048   }
2049
2050   // if integer divide is expensive and we satisfy the requirements, emit an
2051   // alternate sequence.
2052   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2053     SDValue Op = BuildSDIV(N);
2054     if (Op.getNode()) return Op;
2055   }
2056
2057   // undef / X -> 0
2058   if (N0.getOpcode() == ISD::UNDEF)
2059     return DAG.getConstant(0, VT);
2060   // X / undef -> undef
2061   if (N1.getOpcode() == ISD::UNDEF)
2062     return N1;
2063
2064   return SDValue();
2065 }
2066
2067 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2068   SDValue N0 = N->getOperand(0);
2069   SDValue N1 = N->getOperand(1);
2070   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2071   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2072   EVT VT = N->getValueType(0);
2073
2074   // fold vector ops
2075   if (VT.isVector()) {
2076     SDValue FoldedVOp = SimplifyVBinOp(N);
2077     if (FoldedVOp.getNode()) return FoldedVOp;
2078   }
2079
2080   // fold (udiv c1, c2) -> c1/c2
2081   if (N0C && N1C && !N1C->isNullValue())
2082     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2083   // fold (udiv x, (1 << c)) -> x >>u c
2084   if (N1C && N1C->getAPIntValue().isPowerOf2())
2085     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2086                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2087                                        getShiftAmountTy(N0.getValueType())));
2088   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2089   if (N1.getOpcode() == ISD::SHL) {
2090     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2091       if (SHC->getAPIntValue().isPowerOf2()) {
2092         EVT ADDVT = N1.getOperand(1).getValueType();
2093         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2094                                   N1.getOperand(1),
2095                                   DAG.getConstant(SHC->getAPIntValue()
2096                                                                   .logBase2(),
2097                                                   ADDVT));
2098         AddToWorkList(Add.getNode());
2099         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2100       }
2101     }
2102   }
2103   // fold (udiv x, c) -> alternate
2104   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2105     SDValue Op = BuildUDIV(N);
2106     if (Op.getNode()) return Op;
2107   }
2108
2109   // undef / X -> 0
2110   if (N0.getOpcode() == ISD::UNDEF)
2111     return DAG.getConstant(0, VT);
2112   // X / undef -> undef
2113   if (N1.getOpcode() == ISD::UNDEF)
2114     return N1;
2115
2116   return SDValue();
2117 }
2118
2119 SDValue DAGCombiner::visitSREM(SDNode *N) {
2120   SDValue N0 = N->getOperand(0);
2121   SDValue N1 = N->getOperand(1);
2122   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2123   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2124   EVT VT = N->getValueType(0);
2125
2126   // fold (srem c1, c2) -> c1%c2
2127   if (N0C && N1C && !N1C->isNullValue())
2128     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2129   // If we know the sign bits of both operands are zero, strength reduce to a
2130   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2131   if (!VT.isVector()) {
2132     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2133       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2134   }
2135
2136   // If X/C can be simplified by the division-by-constant logic, lower
2137   // X%C to the equivalent of X-X/C*C.
2138   if (N1C && !N1C->isNullValue()) {
2139     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2140     AddToWorkList(Div.getNode());
2141     SDValue OptimizedDiv = combine(Div.getNode());
2142     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2143       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2144                                 OptimizedDiv, N1);
2145       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2146       AddToWorkList(Mul.getNode());
2147       return Sub;
2148     }
2149   }
2150
2151   // undef % X -> 0
2152   if (N0.getOpcode() == ISD::UNDEF)
2153     return DAG.getConstant(0, VT);
2154   // X % undef -> undef
2155   if (N1.getOpcode() == ISD::UNDEF)
2156     return N1;
2157
2158   return SDValue();
2159 }
2160
2161 SDValue DAGCombiner::visitUREM(SDNode *N) {
2162   SDValue N0 = N->getOperand(0);
2163   SDValue N1 = N->getOperand(1);
2164   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2165   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2166   EVT VT = N->getValueType(0);
2167
2168   // fold (urem c1, c2) -> c1%c2
2169   if (N0C && N1C && !N1C->isNullValue())
2170     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2171   // fold (urem x, pow2) -> (and x, pow2-1)
2172   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2173     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2174                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2175   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2176   if (N1.getOpcode() == ISD::SHL) {
2177     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2178       if (SHC->getAPIntValue().isPowerOf2()) {
2179         SDValue Add =
2180           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2181                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2182                                  VT));
2183         AddToWorkList(Add.getNode());
2184         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2185       }
2186     }
2187   }
2188
2189   // If X/C can be simplified by the division-by-constant logic, lower
2190   // X%C to the equivalent of X-X/C*C.
2191   if (N1C && !N1C->isNullValue()) {
2192     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2193     AddToWorkList(Div.getNode());
2194     SDValue OptimizedDiv = combine(Div.getNode());
2195     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2196       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2197                                 OptimizedDiv, N1);
2198       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2199       AddToWorkList(Mul.getNode());
2200       return Sub;
2201     }
2202   }
2203
2204   // undef % X -> 0
2205   if (N0.getOpcode() == ISD::UNDEF)
2206     return DAG.getConstant(0, VT);
2207   // X % undef -> undef
2208   if (N1.getOpcode() == ISD::UNDEF)
2209     return N1;
2210
2211   return SDValue();
2212 }
2213
2214 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2215   SDValue N0 = N->getOperand(0);
2216   SDValue N1 = N->getOperand(1);
2217   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2218   EVT VT = N->getValueType(0);
2219   SDLoc DL(N);
2220
2221   // fold (mulhs x, 0) -> 0
2222   if (N1C && N1C->isNullValue())
2223     return N1;
2224   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2225   if (N1C && N1C->getAPIntValue() == 1)
2226     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2227                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2228                                        getShiftAmountTy(N0.getValueType())));
2229   // fold (mulhs x, undef) -> 0
2230   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2231     return DAG.getConstant(0, VT);
2232
2233   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2234   // plus a shift.
2235   if (VT.isSimple() && !VT.isVector()) {
2236     MVT Simple = VT.getSimpleVT();
2237     unsigned SimpleSize = Simple.getSizeInBits();
2238     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2239     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2240       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2241       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2242       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2243       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2244             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2245       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2246     }
2247   }
2248
2249   return SDValue();
2250 }
2251
2252 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2253   SDValue N0 = N->getOperand(0);
2254   SDValue N1 = N->getOperand(1);
2255   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2256   EVT VT = N->getValueType(0);
2257   SDLoc DL(N);
2258
2259   // fold (mulhu x, 0) -> 0
2260   if (N1C && N1C->isNullValue())
2261     return N1;
2262   // fold (mulhu x, 1) -> 0
2263   if (N1C && N1C->getAPIntValue() == 1)
2264     return DAG.getConstant(0, N0.getValueType());
2265   // fold (mulhu x, undef) -> 0
2266   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2267     return DAG.getConstant(0, VT);
2268
2269   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2270   // plus a shift.
2271   if (VT.isSimple() && !VT.isVector()) {
2272     MVT Simple = VT.getSimpleVT();
2273     unsigned SimpleSize = Simple.getSizeInBits();
2274     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2275     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2276       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2277       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2278       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2279       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2280             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2281       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2282     }
2283   }
2284
2285   return SDValue();
2286 }
2287
2288 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2289 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2290 /// that are being performed. Return true if a simplification was made.
2291 ///
2292 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2293                                                 unsigned HiOp) {
2294   // If the high half is not needed, just compute the low half.
2295   bool HiExists = N->hasAnyUseOfValue(1);
2296   if (!HiExists &&
2297       (!LegalOperations ||
2298        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2299     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2300                               N->op_begin(), N->getNumOperands());
2301     return CombineTo(N, Res, Res);
2302   }
2303
2304   // If the low half is not needed, just compute the high half.
2305   bool LoExists = N->hasAnyUseOfValue(0);
2306   if (!LoExists &&
2307       (!LegalOperations ||
2308        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2309     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2310                               N->op_begin(), N->getNumOperands());
2311     return CombineTo(N, Res, Res);
2312   }
2313
2314   // If both halves are used, return as it is.
2315   if (LoExists && HiExists)
2316     return SDValue();
2317
2318   // If the two computed results can be simplified separately, separate them.
2319   if (LoExists) {
2320     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2321                              N->op_begin(), N->getNumOperands());
2322     AddToWorkList(Lo.getNode());
2323     SDValue LoOpt = combine(Lo.getNode());
2324     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2325         (!LegalOperations ||
2326          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2327       return CombineTo(N, LoOpt, LoOpt);
2328   }
2329
2330   if (HiExists) {
2331     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2332                              N->op_begin(), N->getNumOperands());
2333     AddToWorkList(Hi.getNode());
2334     SDValue HiOpt = combine(Hi.getNode());
2335     if (HiOpt.getNode() && HiOpt != Hi &&
2336         (!LegalOperations ||
2337          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2338       return CombineTo(N, HiOpt, HiOpt);
2339   }
2340
2341   return SDValue();
2342 }
2343
2344 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2345   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2346   if (Res.getNode()) return Res;
2347
2348   EVT VT = N->getValueType(0);
2349   SDLoc DL(N);
2350
2351   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2352   // plus a shift.
2353   if (VT.isSimple() && !VT.isVector()) {
2354     MVT Simple = VT.getSimpleVT();
2355     unsigned SimpleSize = Simple.getSizeInBits();
2356     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2357     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2358       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2359       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2360       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2361       // Compute the high part as N1.
2362       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2363             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2364       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2365       // Compute the low part as N0.
2366       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2367       return CombineTo(N, Lo, Hi);
2368     }
2369   }
2370
2371   return SDValue();
2372 }
2373
2374 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2375   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2376   if (Res.getNode()) return Res;
2377
2378   EVT VT = N->getValueType(0);
2379   SDLoc DL(N);
2380
2381   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2382   // plus a shift.
2383   if (VT.isSimple() && !VT.isVector()) {
2384     MVT Simple = VT.getSimpleVT();
2385     unsigned SimpleSize = Simple.getSizeInBits();
2386     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2387     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2388       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2389       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2390       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2391       // Compute the high part as N1.
2392       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2393             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2394       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2395       // Compute the low part as N0.
2396       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2397       return CombineTo(N, Lo, Hi);
2398     }
2399   }
2400
2401   return SDValue();
2402 }
2403
2404 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2405   // (smulo x, 2) -> (saddo x, x)
2406   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2407     if (C2->getAPIntValue() == 2)
2408       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2409                          N->getOperand(0), N->getOperand(0));
2410
2411   return SDValue();
2412 }
2413
2414 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2415   // (umulo x, 2) -> (uaddo x, x)
2416   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2417     if (C2->getAPIntValue() == 2)
2418       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2419                          N->getOperand(0), N->getOperand(0));
2420
2421   return SDValue();
2422 }
2423
2424 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2425   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2426   if (Res.getNode()) return Res;
2427
2428   return SDValue();
2429 }
2430
2431 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2432   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2433   if (Res.getNode()) return Res;
2434
2435   return SDValue();
2436 }
2437
2438 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2439 /// two operands of the same opcode, try to simplify it.
2440 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2441   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2442   EVT VT = N0.getValueType();
2443   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2444
2445   // Bail early if none of these transforms apply.
2446   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2447
2448   // For each of OP in AND/OR/XOR:
2449   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2450   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2451   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2452   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2453   //
2454   // do not sink logical op inside of a vector extend, since it may combine
2455   // into a vsetcc.
2456   EVT Op0VT = N0.getOperand(0).getValueType();
2457   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2458        N0.getOpcode() == ISD::SIGN_EXTEND ||
2459        // Avoid infinite looping with PromoteIntBinOp.
2460        (N0.getOpcode() == ISD::ANY_EXTEND &&
2461         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2462        (N0.getOpcode() == ISD::TRUNCATE &&
2463         (!TLI.isZExtFree(VT, Op0VT) ||
2464          !TLI.isTruncateFree(Op0VT, VT)) &&
2465         TLI.isTypeLegal(Op0VT))) &&
2466       !VT.isVector() &&
2467       Op0VT == N1.getOperand(0).getValueType() &&
2468       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2469     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2470                                  N0.getOperand(0).getValueType(),
2471                                  N0.getOperand(0), N1.getOperand(0));
2472     AddToWorkList(ORNode.getNode());
2473     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2474   }
2475
2476   // For each of OP in SHL/SRL/SRA/AND...
2477   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2478   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2479   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2480   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2481        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2482       N0.getOperand(1) == N1.getOperand(1)) {
2483     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2484                                  N0.getOperand(0).getValueType(),
2485                                  N0.getOperand(0), N1.getOperand(0));
2486     AddToWorkList(ORNode.getNode());
2487     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2488                        ORNode, N0.getOperand(1));
2489   }
2490
2491   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2492   // Only perform this optimization after type legalization and before
2493   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2494   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2495   // we don't want to undo this promotion.
2496   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2497   // on scalars.
2498   if ((N0.getOpcode() == ISD::BITCAST ||
2499        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2500       Level == AfterLegalizeTypes) {
2501     SDValue In0 = N0.getOperand(0);
2502     SDValue In1 = N1.getOperand(0);
2503     EVT In0Ty = In0.getValueType();
2504     EVT In1Ty = In1.getValueType();
2505     SDLoc DL(N);
2506     // If both incoming values are integers, and the original types are the
2507     // same.
2508     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2509       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2510       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2511       AddToWorkList(Op.getNode());
2512       return BC;
2513     }
2514   }
2515
2516   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2517   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2518   // If both shuffles use the same mask, and both shuffle within a single
2519   // vector, then it is worthwhile to move the swizzle after the operation.
2520   // The type-legalizer generates this pattern when loading illegal
2521   // vector types from memory. In many cases this allows additional shuffle
2522   // optimizations.
2523   // There are other cases where moving the shuffle after the xor/and/or
2524   // is profitable even if shuffles don't perform a swizzle.
2525   // If both shuffles use the same mask, and both shuffles have the same first
2526   // or second operand, then it might still be profitable to move the shuffle
2527   // after the xor/and/or operation.
2528   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2529     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2530     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2531
2532     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2533            "Inputs to shuffles are not the same type");
2534  
2535     // Check that both shuffles use the same mask. The masks are known to be of
2536     // the same length because the result vector type is the same.
2537     // Check also that shuffles have only one use to avoid introducing extra
2538     // instructions.
2539     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2540         SVN0->getMask().equals(SVN1->getMask())) {
2541       SDValue ShOp = N0->getOperand(1);
2542
2543       // Don't try to fold this node if it requires introducing a
2544       // build vector of all zeros that might be illegal at this stage.
2545       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2546         if (!LegalTypes)
2547           ShOp = DAG.getConstant(0, VT);
2548         else
2549           ShOp = SDValue();
2550       }
2551
2552       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2553       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2554       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2555       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2556         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2557                                       N0->getOperand(0), N1->getOperand(0));
2558         AddToWorkList(NewNode.getNode());
2559         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2560                                     &SVN0->getMask()[0]);
2561       }
2562
2563       // Don't try to fold this node if it requires introducing a
2564       // build vector of all zeros that might be illegal at this stage.
2565       ShOp = N0->getOperand(0);
2566       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2567         if (!LegalTypes)
2568           ShOp = DAG.getConstant(0, VT);
2569         else
2570           ShOp = SDValue();
2571       }
2572
2573       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2574       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2575       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2576       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2577         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2578                                       N0->getOperand(1), N1->getOperand(1));
2579         AddToWorkList(NewNode.getNode());
2580         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2581                                     &SVN0->getMask()[0]);
2582       }
2583     }
2584   }
2585
2586   return SDValue();
2587 }
2588
2589 SDValue DAGCombiner::visitAND(SDNode *N) {
2590   SDValue N0 = N->getOperand(0);
2591   SDValue N1 = N->getOperand(1);
2592   SDValue LL, LR, RL, RR, CC0, CC1;
2593   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2594   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2595   EVT VT = N1.getValueType();
2596   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2597
2598   // fold vector ops
2599   if (VT.isVector()) {
2600     SDValue FoldedVOp = SimplifyVBinOp(N);
2601     if (FoldedVOp.getNode()) return FoldedVOp;
2602
2603     // fold (and x, 0) -> 0, vector edition
2604     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2605       return N0;
2606     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2607       return N1;
2608
2609     // fold (and x, -1) -> x, vector edition
2610     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2611       return N1;
2612     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2613       return N0;
2614   }
2615
2616   // fold (and x, undef) -> 0
2617   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2618     return DAG.getConstant(0, VT);
2619   // fold (and c1, c2) -> c1&c2
2620   if (N0C && N1C)
2621     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2622   // canonicalize constant to RHS
2623   if (N0C && !N1C)
2624     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2625   // fold (and x, -1) -> x
2626   if (N1C && N1C->isAllOnesValue())
2627     return N0;
2628   // if (and x, c) is known to be zero, return 0
2629   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2630                                    APInt::getAllOnesValue(BitWidth)))
2631     return DAG.getConstant(0, VT);
2632   // reassociate and
2633   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2634   if (RAND.getNode() != 0)
2635     return RAND;
2636   // fold (and (or x, C), D) -> D if (C & D) == D
2637   if (N1C && N0.getOpcode() == ISD::OR)
2638     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2639       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2640         return N1;
2641   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2642   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2643     SDValue N0Op0 = N0.getOperand(0);
2644     APInt Mask = ~N1C->getAPIntValue();
2645     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2646     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2647       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2648                                  N0.getValueType(), N0Op0);
2649
2650       // Replace uses of the AND with uses of the Zero extend node.
2651       CombineTo(N, Zext);
2652
2653       // We actually want to replace all uses of the any_extend with the
2654       // zero_extend, to avoid duplicating things.  This will later cause this
2655       // AND to be folded.
2656       CombineTo(N0.getNode(), Zext);
2657       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2658     }
2659   }
2660   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2661   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2662   // already be zero by virtue of the width of the base type of the load.
2663   //
2664   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2665   // more cases.
2666   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2667        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2668       N0.getOpcode() == ISD::LOAD) {
2669     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2670                                          N0 : N0.getOperand(0) );
2671
2672     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2673     // This can be a pure constant or a vector splat, in which case we treat the
2674     // vector as a scalar and use the splat value.
2675     APInt Constant = APInt::getNullValue(1);
2676     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2677       Constant = C->getAPIntValue();
2678     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2679       APInt SplatValue, SplatUndef;
2680       unsigned SplatBitSize;
2681       bool HasAnyUndefs;
2682       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2683                                              SplatBitSize, HasAnyUndefs);
2684       if (IsSplat) {
2685         // Undef bits can contribute to a possible optimisation if set, so
2686         // set them.
2687         SplatValue |= SplatUndef;
2688
2689         // The splat value may be something like "0x00FFFFFF", which means 0 for
2690         // the first vector value and FF for the rest, repeating. We need a mask
2691         // that will apply equally to all members of the vector, so AND all the
2692         // lanes of the constant together.
2693         EVT VT = Vector->getValueType(0);
2694         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2695
2696         // If the splat value has been compressed to a bitlength lower
2697         // than the size of the vector lane, we need to re-expand it to
2698         // the lane size.
2699         if (BitWidth > SplatBitSize)
2700           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2701                SplatBitSize < BitWidth;
2702                SplatBitSize = SplatBitSize * 2)
2703             SplatValue |= SplatValue.shl(SplatBitSize);
2704
2705         Constant = APInt::getAllOnesValue(BitWidth);
2706         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2707           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2708       }
2709     }
2710
2711     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2712     // actually legal and isn't going to get expanded, else this is a false
2713     // optimisation.
2714     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2715                                                     Load->getMemoryVT());
2716
2717     // Resize the constant to the same size as the original memory access before
2718     // extension. If it is still the AllOnesValue then this AND is completely
2719     // unneeded.
2720     Constant =
2721       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2722
2723     bool B;
2724     switch (Load->getExtensionType()) {
2725     default: B = false; break;
2726     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2727     case ISD::ZEXTLOAD:
2728     case ISD::NON_EXTLOAD: B = true; break;
2729     }
2730
2731     if (B && Constant.isAllOnesValue()) {
2732       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2733       // preserve semantics once we get rid of the AND.
2734       SDValue NewLoad(Load, 0);
2735       if (Load->getExtensionType() == ISD::EXTLOAD) {
2736         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2737                               Load->getValueType(0), SDLoc(Load),
2738                               Load->getChain(), Load->getBasePtr(),
2739                               Load->getOffset(), Load->getMemoryVT(),
2740                               Load->getMemOperand());
2741         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2742         if (Load->getNumValues() == 3) {
2743           // PRE/POST_INC loads have 3 values.
2744           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2745                            NewLoad.getValue(2) };
2746           CombineTo(Load, To, 3, true);
2747         } else {
2748           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2749         }
2750       }
2751
2752       // Fold the AND away, taking care not to fold to the old load node if we
2753       // replaced it.
2754       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2755
2756       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2757     }
2758   }
2759   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2760   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2761     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2762     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2763
2764     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2765         LL.getValueType().isInteger()) {
2766       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2767       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2768         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2769                                      LR.getValueType(), LL, RL);
2770         AddToWorkList(ORNode.getNode());
2771         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2772       }
2773       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2774       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2775         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2776                                       LR.getValueType(), LL, RL);
2777         AddToWorkList(ANDNode.getNode());
2778         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2779       }
2780       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2781       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2782         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2783                                      LR.getValueType(), LL, RL);
2784         AddToWorkList(ORNode.getNode());
2785         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2786       }
2787     }
2788     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2789     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2790         Op0 == Op1 && LL.getValueType().isInteger() &&
2791       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2792                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2793                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2794                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2795       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2796                                     LL, DAG.getConstant(1, LL.getValueType()));
2797       AddToWorkList(ADDNode.getNode());
2798       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2799                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2800     }
2801     // canonicalize equivalent to ll == rl
2802     if (LL == RR && LR == RL) {
2803       Op1 = ISD::getSetCCSwappedOperands(Op1);
2804       std::swap(RL, RR);
2805     }
2806     if (LL == RL && LR == RR) {
2807       bool isInteger = LL.getValueType().isInteger();
2808       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2809       if (Result != ISD::SETCC_INVALID &&
2810           (!LegalOperations ||
2811            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2812             TLI.isOperationLegal(ISD::SETCC,
2813                             getSetCCResultType(N0.getSimpleValueType())))))
2814         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2815                             LL, LR, Result);
2816     }
2817   }
2818
2819   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2820   if (N0.getOpcode() == N1.getOpcode()) {
2821     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2822     if (Tmp.getNode()) return Tmp;
2823   }
2824
2825   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2826   // fold (and (sra)) -> (and (srl)) when possible.
2827   if (!VT.isVector() &&
2828       SimplifyDemandedBits(SDValue(N, 0)))
2829     return SDValue(N, 0);
2830
2831   // fold (zext_inreg (extload x)) -> (zextload x)
2832   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2833     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2834     EVT MemVT = LN0->getMemoryVT();
2835     // If we zero all the possible extended bits, then we can turn this into
2836     // a zextload if we are running before legalize or the operation is legal.
2837     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2838     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2839                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2840         ((!LegalOperations && !LN0->isVolatile()) ||
2841          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2842       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2843                                        LN0->getChain(), LN0->getBasePtr(),
2844                                        MemVT, LN0->getMemOperand());
2845       AddToWorkList(N);
2846       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2848     }
2849   }
2850   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2851   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2852       N0.hasOneUse()) {
2853     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2854     EVT MemVT = LN0->getMemoryVT();
2855     // If we zero all the possible extended bits, then we can turn this into
2856     // a zextload if we are running before legalize or the operation is legal.
2857     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2858     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2859                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2860         ((!LegalOperations && !LN0->isVolatile()) ||
2861          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2862       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2863                                        LN0->getChain(), LN0->getBasePtr(),
2864                                        MemVT, LN0->getMemOperand());
2865       AddToWorkList(N);
2866       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2867       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2868     }
2869   }
2870
2871   // fold (and (load x), 255) -> (zextload x, i8)
2872   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2873   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2874   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2875               (N0.getOpcode() == ISD::ANY_EXTEND &&
2876                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2877     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2878     LoadSDNode *LN0 = HasAnyExt
2879       ? cast<LoadSDNode>(N0.getOperand(0))
2880       : cast<LoadSDNode>(N0);
2881     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2882         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2883       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2884       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2885         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2886         EVT LoadedVT = LN0->getMemoryVT();
2887
2888         if (ExtVT == LoadedVT &&
2889             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2890           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2891
2892           SDValue NewLoad =
2893             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2894                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2895                            LN0->getMemOperand());
2896           AddToWorkList(N);
2897           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2898           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2899         }
2900
2901         // Do not change the width of a volatile load.
2902         // Do not generate loads of non-round integer types since these can
2903         // be expensive (and would be wrong if the type is not byte sized).
2904         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2905             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2906           EVT PtrType = LN0->getOperand(1).getValueType();
2907
2908           unsigned Alignment = LN0->getAlignment();
2909           SDValue NewPtr = LN0->getBasePtr();
2910
2911           // For big endian targets, we need to add an offset to the pointer
2912           // to load the correct bytes.  For little endian systems, we merely
2913           // need to read fewer bytes from the same pointer.
2914           if (TLI.isBigEndian()) {
2915             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2916             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2917             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2918             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2919                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2920             Alignment = MinAlign(Alignment, PtrOff);
2921           }
2922
2923           AddToWorkList(NewPtr.getNode());
2924
2925           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2926           SDValue Load =
2927             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2928                            LN0->getChain(), NewPtr,
2929                            LN0->getPointerInfo(),
2930                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2931                            Alignment, LN0->getTBAAInfo());
2932           AddToWorkList(N);
2933           CombineTo(LN0, Load, Load.getValue(1));
2934           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2935         }
2936       }
2937     }
2938   }
2939
2940   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2941       VT.getSizeInBits() <= 64) {
2942     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2943       APInt ADDC = ADDI->getAPIntValue();
2944       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2945         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2946         // immediate for an add, but it is legal if its top c2 bits are set,
2947         // transform the ADD so the immediate doesn't need to be materialized
2948         // in a register.
2949         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2950           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2951                                              SRLI->getZExtValue());
2952           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2953             ADDC |= Mask;
2954             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2955               SDValue NewAdd =
2956                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2957                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2958               CombineTo(N0.getNode(), NewAdd);
2959               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2960             }
2961           }
2962         }
2963       }
2964     }
2965   }
2966
2967   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2968   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2969     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2970                                        N0.getOperand(1), false);
2971     if (BSwap.getNode())
2972       return BSwap;
2973   }
2974
2975   return SDValue();
2976 }
2977
2978 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2979 ///
2980 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2981                                         bool DemandHighBits) {
2982   if (!LegalOperations)
2983     return SDValue();
2984
2985   EVT VT = N->getValueType(0);
2986   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2987     return SDValue();
2988   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2989     return SDValue();
2990
2991   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2992   bool LookPassAnd0 = false;
2993   bool LookPassAnd1 = false;
2994   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2995       std::swap(N0, N1);
2996   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2997       std::swap(N0, N1);
2998   if (N0.getOpcode() == ISD::AND) {
2999     if (!N0.getNode()->hasOneUse())
3000       return SDValue();
3001     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3002     if (!N01C || N01C->getZExtValue() != 0xFF00)
3003       return SDValue();
3004     N0 = N0.getOperand(0);
3005     LookPassAnd0 = true;
3006   }
3007
3008   if (N1.getOpcode() == ISD::AND) {
3009     if (!N1.getNode()->hasOneUse())
3010       return SDValue();
3011     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3012     if (!N11C || N11C->getZExtValue() != 0xFF)
3013       return SDValue();
3014     N1 = N1.getOperand(0);
3015     LookPassAnd1 = true;
3016   }
3017
3018   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3019     std::swap(N0, N1);
3020   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3021     return SDValue();
3022   if (!N0.getNode()->hasOneUse() ||
3023       !N1.getNode()->hasOneUse())
3024     return SDValue();
3025
3026   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3027   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3028   if (!N01C || !N11C)
3029     return SDValue();
3030   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3031     return SDValue();
3032
3033   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3034   SDValue N00 = N0->getOperand(0);
3035   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3036     if (!N00.getNode()->hasOneUse())
3037       return SDValue();
3038     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3039     if (!N001C || N001C->getZExtValue() != 0xFF)
3040       return SDValue();
3041     N00 = N00.getOperand(0);
3042     LookPassAnd0 = true;
3043   }
3044
3045   SDValue N10 = N1->getOperand(0);
3046   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3047     if (!N10.getNode()->hasOneUse())
3048       return SDValue();
3049     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3050     if (!N101C || N101C->getZExtValue() != 0xFF00)
3051       return SDValue();
3052     N10 = N10.getOperand(0);
3053     LookPassAnd1 = true;
3054   }
3055
3056   if (N00 != N10)
3057     return SDValue();
3058
3059   // Make sure everything beyond the low halfword gets set to zero since the SRL
3060   // 16 will clear the top bits.
3061   unsigned OpSizeInBits = VT.getSizeInBits();
3062   if (DemandHighBits && OpSizeInBits > 16) {
3063     // If the left-shift isn't masked out then the only way this is a bswap is
3064     // if all bits beyond the low 8 are 0. In that case the entire pattern
3065     // reduces to a left shift anyway: leave it for other parts of the combiner.
3066     if (!LookPassAnd0)
3067       return SDValue();
3068
3069     // However, if the right shift isn't masked out then it might be because
3070     // it's not needed. See if we can spot that too.
3071     if (!LookPassAnd1 &&
3072         !DAG.MaskedValueIsZero(
3073             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3074       return SDValue();
3075   }
3076
3077   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3078   if (OpSizeInBits > 16)
3079     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3080                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3081   return Res;
3082 }
3083
3084 /// isBSwapHWordElement - Return true if the specified node is an element
3085 /// that makes up a 32-bit packed halfword byteswap. i.e.
3086 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3087 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3088   if (!N.getNode()->hasOneUse())
3089     return false;
3090
3091   unsigned Opc = N.getOpcode();
3092   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3093     return false;
3094
3095   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3096   if (!N1C)
3097     return false;
3098
3099   unsigned Num;
3100   switch (N1C->getZExtValue()) {
3101   default:
3102     return false;
3103   case 0xFF:       Num = 0; break;
3104   case 0xFF00:     Num = 1; break;
3105   case 0xFF0000:   Num = 2; break;
3106   case 0xFF000000: Num = 3; break;
3107   }
3108
3109   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3110   SDValue N0 = N.getOperand(0);
3111   if (Opc == ISD::AND) {
3112     if (Num == 0 || Num == 2) {
3113       // (x >> 8) & 0xff
3114       // (x >> 8) & 0xff0000
3115       if (N0.getOpcode() != ISD::SRL)
3116         return false;
3117       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3118       if (!C || C->getZExtValue() != 8)
3119         return false;
3120     } else {
3121       // (x << 8) & 0xff00
3122       // (x << 8) & 0xff000000
3123       if (N0.getOpcode() != ISD::SHL)
3124         return false;
3125       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3126       if (!C || C->getZExtValue() != 8)
3127         return false;
3128     }
3129   } else if (Opc == ISD::SHL) {
3130     // (x & 0xff) << 8
3131     // (x & 0xff0000) << 8
3132     if (Num != 0 && Num != 2)
3133       return false;
3134     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3135     if (!C || C->getZExtValue() != 8)
3136       return false;
3137   } else { // Opc == ISD::SRL
3138     // (x & 0xff00) >> 8
3139     // (x & 0xff000000) >> 8
3140     if (Num != 1 && Num != 3)
3141       return false;
3142     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3143     if (!C || C->getZExtValue() != 8)
3144       return false;
3145   }
3146
3147   if (Parts[Num])
3148     return false;
3149
3150   Parts[Num] = N0.getOperand(0).getNode();
3151   return true;
3152 }
3153
3154 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3155 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3156 /// => (rotl (bswap x), 16)
3157 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3158   if (!LegalOperations)
3159     return SDValue();
3160
3161   EVT VT = N->getValueType(0);
3162   if (VT != MVT::i32)
3163     return SDValue();
3164   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3165     return SDValue();
3166
3167   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3168   // Look for either
3169   // (or (or (and), (and)), (or (and), (and)))
3170   // (or (or (or (and), (and)), (and)), (and))
3171   if (N0.getOpcode() != ISD::OR)
3172     return SDValue();
3173   SDValue N00 = N0.getOperand(0);
3174   SDValue N01 = N0.getOperand(1);
3175
3176   if (N1.getOpcode() == ISD::OR &&
3177       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3178     // (or (or (and), (and)), (or (and), (and)))
3179     SDValue N000 = N00.getOperand(0);
3180     if (!isBSwapHWordElement(N000, Parts))
3181       return SDValue();
3182
3183     SDValue N001 = N00.getOperand(1);
3184     if (!isBSwapHWordElement(N001, Parts))
3185       return SDValue();
3186     SDValue N010 = N01.getOperand(0);
3187     if (!isBSwapHWordElement(N010, Parts))
3188       return SDValue();
3189     SDValue N011 = N01.getOperand(1);
3190     if (!isBSwapHWordElement(N011, Parts))
3191       return SDValue();
3192   } else {
3193     // (or (or (or (and), (and)), (and)), (and))
3194     if (!isBSwapHWordElement(N1, Parts))
3195       return SDValue();
3196     if (!isBSwapHWordElement(N01, Parts))
3197       return SDValue();
3198     if (N00.getOpcode() != ISD::OR)
3199       return SDValue();
3200     SDValue N000 = N00.getOperand(0);
3201     if (!isBSwapHWordElement(N000, Parts))
3202       return SDValue();
3203     SDValue N001 = N00.getOperand(1);
3204     if (!isBSwapHWordElement(N001, Parts))
3205       return SDValue();
3206   }
3207
3208   // Make sure the parts are all coming from the same node.
3209   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3210     return SDValue();
3211
3212   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3213                               SDValue(Parts[0],0));
3214
3215   // Result of the bswap should be rotated by 16. If it's not legal, then
3216   // do  (x << 16) | (x >> 16).
3217   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3218   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3219     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3220   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3221     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3222   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3223                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3224                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3225 }
3226
3227 SDValue DAGCombiner::visitOR(SDNode *N) {
3228   SDValue N0 = N->getOperand(0);
3229   SDValue N1 = N->getOperand(1);
3230   SDValue LL, LR, RL, RR, CC0, CC1;
3231   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3232   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3233   EVT VT = N1.getValueType();
3234
3235   // fold vector ops
3236   if (VT.isVector()) {
3237     SDValue FoldedVOp = SimplifyVBinOp(N);
3238     if (FoldedVOp.getNode()) return FoldedVOp;
3239
3240     // fold (or x, 0) -> x, vector edition
3241     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3242       return N1;
3243     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3244       return N0;
3245
3246     // fold (or x, -1) -> -1, vector edition
3247     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3248       return N0;
3249     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3250       return N1;
3251
3252     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3253     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3254     // Do this only if the resulting shuffle is legal.
3255     if (isa<ShuffleVectorSDNode>(N0) &&
3256         isa<ShuffleVectorSDNode>(N1) &&
3257         N0->getOperand(1) == N1->getOperand(1) &&
3258         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3259       bool CanFold = true;
3260       unsigned NumElts = VT.getVectorNumElements();
3261       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3262       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3263       // We construct two shuffle masks:
3264       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3265       // and N1 as the second operand.
3266       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3267       // and N0 as the second operand.
3268       // We do this because OR is commutable and therefore there might be
3269       // two ways to fold this node into a shuffle.
3270       SmallVector<int,4> Mask1;
3271       SmallVector<int,4> Mask2;
3272       
3273       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3274         int M0 = SV0->getMaskElt(i);
3275         int M1 = SV1->getMaskElt(i);
3276    
3277         // Both shuffle indexes are undef. Propagate Undef.
3278         if (M0 < 0 && M1 < 0) {
3279           Mask1.push_back(M0);
3280           Mask2.push_back(M0);
3281           continue;
3282         }
3283
3284         if (M0 < 0 || M1 < 0 ||
3285             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3286             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3287           CanFold = false;
3288           break;
3289         }
3290         
3291         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3292         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3293       }
3294
3295       if (CanFold) {
3296         // Fold this sequence only if the resulting shuffle is 'legal'.
3297         if (TLI.isShuffleMaskLegal(Mask1, VT))
3298           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3299                                       N1->getOperand(0), &Mask1[0]);
3300         if (TLI.isShuffleMaskLegal(Mask2, VT))
3301           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3302                                       N0->getOperand(0), &Mask2[0]);
3303       }
3304     }
3305   }
3306
3307   // fold (or x, undef) -> -1
3308   if (!LegalOperations &&
3309       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3310     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3311     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3312   }
3313   // fold (or c1, c2) -> c1|c2
3314   if (N0C && N1C)
3315     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3316   // canonicalize constant to RHS
3317   if (N0C && !N1C)
3318     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3319   // fold (or x, 0) -> x
3320   if (N1C && N1C->isNullValue())
3321     return N0;
3322   // fold (or x, -1) -> -1
3323   if (N1C && N1C->isAllOnesValue())
3324     return N1;
3325   // fold (or x, c) -> c iff (x & ~c) == 0
3326   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3327     return N1;
3328
3329   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3330   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3331   if (BSwap.getNode() != 0)
3332     return BSwap;
3333   BSwap = MatchBSwapHWordLow(N, N0, N1);
3334   if (BSwap.getNode() != 0)
3335     return BSwap;
3336
3337   // reassociate or
3338   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3339   if (ROR.getNode() != 0)
3340     return ROR;
3341   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3342   // iff (c1 & c2) == 0.
3343   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3344              isa<ConstantSDNode>(N0.getOperand(1))) {
3345     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3346     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3347       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3348       if (!COR.getNode())
3349         return SDValue();
3350       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3351                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3352                                      N0.getOperand(0), N1), COR);
3353     }
3354   }
3355   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3356   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3357     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3358     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3359
3360     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3361         LL.getValueType().isInteger()) {
3362       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3363       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3364       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3365           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3366         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3367                                      LR.getValueType(), LL, RL);
3368         AddToWorkList(ORNode.getNode());
3369         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3370       }
3371       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3372       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3373       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3374           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3375         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3376                                       LR.getValueType(), LL, RL);
3377         AddToWorkList(ANDNode.getNode());
3378         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3379       }
3380     }
3381     // canonicalize equivalent to ll == rl
3382     if (LL == RR && LR == RL) {
3383       Op1 = ISD::getSetCCSwappedOperands(Op1);
3384       std::swap(RL, RR);
3385     }
3386     if (LL == RL && LR == RR) {
3387       bool isInteger = LL.getValueType().isInteger();
3388       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3389       if (Result != ISD::SETCC_INVALID &&
3390           (!LegalOperations ||
3391            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3392             TLI.isOperationLegal(ISD::SETCC,
3393               getSetCCResultType(N0.getValueType())))))
3394         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3395                             LL, LR, Result);
3396     }
3397   }
3398
3399   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3400   if (N0.getOpcode() == N1.getOpcode()) {
3401     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3402     if (Tmp.getNode()) return Tmp;
3403   }
3404
3405   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3406   if (N0.getOpcode() == ISD::AND &&
3407       N1.getOpcode() == ISD::AND &&
3408       N0.getOperand(1).getOpcode() == ISD::Constant &&
3409       N1.getOperand(1).getOpcode() == ISD::Constant &&
3410       // Don't increase # computations.
3411       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3412     // We can only do this xform if we know that bits from X that are set in C2
3413     // but not in C1 are already zero.  Likewise for Y.
3414     const APInt &LHSMask =
3415       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3416     const APInt &RHSMask =
3417       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3418
3419     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3420         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3421       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3422                               N0.getOperand(0), N1.getOperand(0));
3423       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3424                          DAG.getConstant(LHSMask | RHSMask, VT));
3425     }
3426   }
3427
3428   // See if this is some rotate idiom.
3429   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3430     return SDValue(Rot, 0);
3431
3432   // Simplify the operands using demanded-bits information.
3433   if (!VT.isVector() &&
3434       SimplifyDemandedBits(SDValue(N, 0)))
3435     return SDValue(N, 0);
3436
3437   return SDValue();
3438 }
3439
3440 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3441 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3442   if (Op.getOpcode() == ISD::AND) {
3443     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3444       Mask = Op.getOperand(1);
3445       Op = Op.getOperand(0);
3446     } else {
3447       return false;
3448     }
3449   }
3450
3451   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3452     Shift = Op;
3453     return true;
3454   }
3455
3456   return false;
3457 }
3458
3459 // Return true if we can prove that, whenever Neg and Pos are both in the
3460 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3461 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3462 //
3463 //     (or (shift1 X, Neg), (shift2 X, Pos))
3464 //
3465 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3466 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3467 // to consider shift amounts with defined behavior.
3468 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3469   // If OpSize is a power of 2 then:
3470   //
3471   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3472   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3473   //
3474   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3475   // for the stronger condition:
3476   //
3477   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3478   //
3479   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3480   // we can just replace Neg with Neg' for the rest of the function.
3481   //
3482   // In other cases we check for the even stronger condition:
3483   //
3484   //     Neg == OpSize - Pos                                    [B]
3485   //
3486   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3487   // behavior if Pos == 0 (and consequently Neg == OpSize).
3488   //
3489   // We could actually use [A] whenever OpSize is a power of 2, but the
3490   // only extra cases that it would match are those uninteresting ones
3491   // where Neg and Pos are never in range at the same time.  E.g. for
3492   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3493   // as well as (sub 32, Pos), but:
3494   //
3495   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3496   //
3497   // always invokes undefined behavior for 32-bit X.
3498   //
3499   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3500   unsigned MaskLoBits = 0;
3501   if (Neg.getOpcode() == ISD::AND &&
3502       isPowerOf2_64(OpSize) &&
3503       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3504       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3505     Neg = Neg.getOperand(0);
3506     MaskLoBits = Log2_64(OpSize);
3507   }
3508
3509   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3510   if (Neg.getOpcode() != ISD::SUB)
3511     return 0;
3512   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3513   if (!NegC)
3514     return 0;
3515   SDValue NegOp1 = Neg.getOperand(1);
3516
3517   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3518   // Pos'.  The truncation is redundant for the purpose of the equality.
3519   if (MaskLoBits &&
3520       Pos.getOpcode() == ISD::AND &&
3521       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3522       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3523     Pos = Pos.getOperand(0);
3524
3525   // The condition we need is now:
3526   //
3527   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3528   //
3529   // If NegOp1 == Pos then we need:
3530   //
3531   //              OpSize & Mask == NegC & Mask
3532   //
3533   // (because "x & Mask" is a truncation and distributes through subtraction).
3534   APInt Width;
3535   if (Pos == NegOp1)
3536     Width = NegC->getAPIntValue();
3537   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3538   // Then the condition we want to prove becomes:
3539   //
3540   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3541   //
3542   // which, again because "x & Mask" is a truncation, becomes:
3543   //
3544   //                NegC & Mask == (OpSize - PosC) & Mask
3545   //              OpSize & Mask == (NegC + PosC) & Mask
3546   else if (Pos.getOpcode() == ISD::ADD &&
3547            Pos.getOperand(0) == NegOp1 &&
3548            Pos.getOperand(1).getOpcode() == ISD::Constant)
3549     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3550              NegC->getAPIntValue());
3551   else
3552     return false;
3553
3554   // Now we just need to check that OpSize & Mask == Width & Mask.
3555   if (MaskLoBits)
3556     // Opsize & Mask is 0 since Mask is Opsize - 1.
3557     return Width.getLoBits(MaskLoBits) == 0;
3558   return Width == OpSize;
3559 }
3560
3561 // A subroutine of MatchRotate used once we have found an OR of two opposite
3562 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3563 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3564 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3565 // Neg with outer conversions stripped away.
3566 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3567                                        SDValue Neg, SDValue InnerPos,
3568                                        SDValue InnerNeg, unsigned PosOpcode,
3569                                        unsigned NegOpcode, SDLoc DL) {
3570   // fold (or (shl x, (*ext y)),
3571   //          (srl x, (*ext (sub 32, y)))) ->
3572   //   (rotl x, y) or (rotr x, (sub 32, y))
3573   //
3574   // fold (or (shl x, (*ext (sub 32, y))),
3575   //          (srl x, (*ext y))) ->
3576   //   (rotr x, y) or (rotl x, (sub 32, y))
3577   EVT VT = Shifted.getValueType();
3578   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3579     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3580     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3581                        HasPos ? Pos : Neg).getNode();
3582   }
3583
3584   // fold (or (shl (*ext x), (*ext y)),
3585   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3586   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3587   //
3588   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3589   //          (srl (*ext x), (*ext y))) ->
3590   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3591   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3592       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3593     SDValue InnerShifted = Shifted.getOperand(0);
3594     EVT InnerVT = InnerShifted.getValueType();
3595     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3596     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3597       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3598         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3599                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3600         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3601       }
3602     }
3603   }
3604
3605   return 0;
3606 }
3607
3608 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3609 // idioms for rotate, and if the target supports rotation instructions, generate
3610 // a rot[lr].
3611 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3612   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3613   EVT VT = LHS.getValueType();
3614   if (!TLI.isTypeLegal(VT)) return 0;
3615
3616   // The target must have at least one rotate flavor.
3617   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3618   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3619   if (!HasROTL && !HasROTR) return 0;
3620
3621   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3622   SDValue LHSShift;   // The shift.
3623   SDValue LHSMask;    // AND value if any.
3624   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3625     return 0; // Not part of a rotate.
3626
3627   SDValue RHSShift;   // The shift.
3628   SDValue RHSMask;    // AND value if any.
3629   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3630     return 0; // Not part of a rotate.
3631
3632   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3633     return 0;   // Not shifting the same value.
3634
3635   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3636     return 0;   // Shifts must disagree.
3637
3638   // Canonicalize shl to left side in a shl/srl pair.
3639   if (RHSShift.getOpcode() == ISD::SHL) {
3640     std::swap(LHS, RHS);
3641     std::swap(LHSShift, RHSShift);
3642     std::swap(LHSMask , RHSMask );
3643   }
3644
3645   unsigned OpSizeInBits = VT.getSizeInBits();
3646   SDValue LHSShiftArg = LHSShift.getOperand(0);
3647   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3648   SDValue RHSShiftArg = RHSShift.getOperand(0);
3649   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3650
3651   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3652   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3653   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3654       RHSShiftAmt.getOpcode() == ISD::Constant) {
3655     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3656     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3657     if ((LShVal + RShVal) != OpSizeInBits)
3658       return 0;
3659
3660     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3661                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3662
3663     // If there is an AND of either shifted operand, apply it to the result.
3664     if (LHSMask.getNode() || RHSMask.getNode()) {
3665       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3666
3667       if (LHSMask.getNode()) {
3668         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3669         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3670       }
3671       if (RHSMask.getNode()) {
3672         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3673         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3674       }
3675
3676       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3677     }
3678
3679     return Rot.getNode();
3680   }
3681
3682   // If there is a mask here, and we have a variable shift, we can't be sure
3683   // that we're masking out the right stuff.
3684   if (LHSMask.getNode() || RHSMask.getNode())
3685     return 0;
3686
3687   // If the shift amount is sign/zext/any-extended just peel it off.
3688   SDValue LExtOp0 = LHSShiftAmt;
3689   SDValue RExtOp0 = RHSShiftAmt;
3690   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3691        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3692        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3693        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3694       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3695        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3696        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3697        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3698     LExtOp0 = LHSShiftAmt.getOperand(0);
3699     RExtOp0 = RHSShiftAmt.getOperand(0);
3700   }
3701
3702   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3703                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3704   if (TryL)
3705     return TryL;
3706
3707   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3708                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3709   if (TryR)
3710     return TryR;
3711
3712   return 0;
3713 }
3714
3715 SDValue DAGCombiner::visitXOR(SDNode *N) {
3716   SDValue N0 = N->getOperand(0);
3717   SDValue N1 = N->getOperand(1);
3718   SDValue LHS, RHS, CC;
3719   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3720   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3721   EVT VT = N0.getValueType();
3722
3723   // fold vector ops
3724   if (VT.isVector()) {
3725     SDValue FoldedVOp = SimplifyVBinOp(N);
3726     if (FoldedVOp.getNode()) return FoldedVOp;
3727
3728     // fold (xor x, 0) -> x, vector edition
3729     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3730       return N1;
3731     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3732       return N0;
3733   }
3734
3735   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3736   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3737     return DAG.getConstant(0, VT);
3738   // fold (xor x, undef) -> undef
3739   if (N0.getOpcode() == ISD::UNDEF)
3740     return N0;
3741   if (N1.getOpcode() == ISD::UNDEF)
3742     return N1;
3743   // fold (xor c1, c2) -> c1^c2
3744   if (N0C && N1C)
3745     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3746   // canonicalize constant to RHS
3747   if (N0C && !N1C)
3748     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3749   // fold (xor x, 0) -> x
3750   if (N1C && N1C->isNullValue())
3751     return N0;
3752   // reassociate xor
3753   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3754   if (RXOR.getNode() != 0)
3755     return RXOR;
3756
3757   // fold !(x cc y) -> (x !cc y)
3758   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3759     bool isInt = LHS.getValueType().isInteger();
3760     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3761                                                isInt);
3762
3763     if (!LegalOperations ||
3764         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3765       switch (N0.getOpcode()) {
3766       default:
3767         llvm_unreachable("Unhandled SetCC Equivalent!");
3768       case ISD::SETCC:
3769         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3770       case ISD::SELECT_CC:
3771         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3772                                N0.getOperand(3), NotCC);
3773       }
3774     }
3775   }
3776
3777   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3778   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3779       N0.getNode()->hasOneUse() &&
3780       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3781     SDValue V = N0.getOperand(0);
3782     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3783                     DAG.getConstant(1, V.getValueType()));
3784     AddToWorkList(V.getNode());
3785     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3786   }
3787
3788   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3789   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3790       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3791     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3792     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3793       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3794       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3795       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3796       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3797       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3798     }
3799   }
3800   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3801   if (N1C && N1C->isAllOnesValue() &&
3802       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3803     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3804     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3805       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3806       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3807       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3808       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3809       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3810     }
3811   }
3812   // fold (xor (and x, y), y) -> (and (not x), y)
3813   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3814       N0->getOperand(1) == N1) {
3815     SDValue X = N0->getOperand(0);
3816     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3817     AddToWorkList(NotX.getNode());
3818     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3819   }
3820   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3821   if (N1C && N0.getOpcode() == ISD::XOR) {
3822     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3823     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3824     if (N00C)
3825       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3826                          DAG.getConstant(N1C->getAPIntValue() ^
3827                                          N00C->getAPIntValue(), VT));
3828     if (N01C)
3829       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3830                          DAG.getConstant(N1C->getAPIntValue() ^
3831                                          N01C->getAPIntValue(), VT));
3832   }
3833   // fold (xor x, x) -> 0
3834   if (N0 == N1)
3835     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3836
3837   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3838   if (N0.getOpcode() == N1.getOpcode()) {
3839     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3840     if (Tmp.getNode()) return Tmp;
3841   }
3842
3843   // Simplify the expression using non-local knowledge.
3844   if (!VT.isVector() &&
3845       SimplifyDemandedBits(SDValue(N, 0)))
3846     return SDValue(N, 0);
3847
3848   return SDValue();
3849 }
3850
3851 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3852 /// the shift amount is a constant.
3853 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3854   // We can't and shouldn't fold opaque constants.
3855   if (Amt->isOpaque())
3856     return SDValue();
3857
3858   SDNode *LHS = N->getOperand(0).getNode();
3859   if (!LHS->hasOneUse()) return SDValue();
3860
3861   // We want to pull some binops through shifts, so that we have (and (shift))
3862   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3863   // thing happens with address calculations, so it's important to canonicalize
3864   // it.
3865   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3866
3867   switch (LHS->getOpcode()) {
3868   default: return SDValue();
3869   case ISD::OR:
3870   case ISD::XOR:
3871     HighBitSet = false; // We can only transform sra if the high bit is clear.
3872     break;
3873   case ISD::AND:
3874     HighBitSet = true;  // We can only transform sra if the high bit is set.
3875     break;
3876   case ISD::ADD:
3877     if (N->getOpcode() != ISD::SHL)
3878       return SDValue(); // only shl(add) not sr[al](add).
3879     HighBitSet = false; // We can only transform sra if the high bit is clear.
3880     break;
3881   }
3882
3883   // We require the RHS of the binop to be a constant and not opaque as well.
3884   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3885   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3886
3887   // FIXME: disable this unless the input to the binop is a shift by a constant.
3888   // If it is not a shift, it pessimizes some common cases like:
3889   //
3890   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3891   //    int bar(int *X, int i) { return X[i & 255]; }
3892   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3893   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3894        BinOpLHSVal->getOpcode() != ISD::SRA &&
3895        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3896       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3897     return SDValue();
3898
3899   EVT VT = N->getValueType(0);
3900
3901   // If this is a signed shift right, and the high bit is modified by the
3902   // logical operation, do not perform the transformation. The highBitSet
3903   // boolean indicates the value of the high bit of the constant which would
3904   // cause it to be modified for this operation.
3905   if (N->getOpcode() == ISD::SRA) {
3906     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3907     if (BinOpRHSSignSet != HighBitSet)
3908       return SDValue();
3909   }
3910
3911   // Fold the constants, shifting the binop RHS by the shift amount.
3912   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3913                                N->getValueType(0),
3914                                LHS->getOperand(1), N->getOperand(1));
3915   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3916
3917   // Create the new shift.
3918   SDValue NewShift = DAG.getNode(N->getOpcode(),
3919                                  SDLoc(LHS->getOperand(0)),
3920                                  VT, LHS->getOperand(0), N->getOperand(1));
3921
3922   // Create the new binop.
3923   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3924 }
3925
3926 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3927   assert(N->getOpcode() == ISD::TRUNCATE);
3928   assert(N->getOperand(0).getOpcode() == ISD::AND);
3929
3930   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3931   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3932     SDValue N01 = N->getOperand(0).getOperand(1);
3933
3934     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3935       EVT TruncVT = N->getValueType(0);
3936       SDValue N00 = N->getOperand(0).getOperand(0);
3937       APInt TruncC = N01C->getAPIntValue();
3938       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3939
3940       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3941                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3942                          DAG.getConstant(TruncC, TruncVT));
3943     }
3944   }
3945
3946   return SDValue();
3947 }
3948
3949 SDValue DAGCombiner::visitRotate(SDNode *N) {
3950   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3951   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3952       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3953     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3954     if (NewOp1.getNode())
3955       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3956                          N->getOperand(0), NewOp1);
3957   }
3958   return SDValue();
3959 }
3960
3961 SDValue DAGCombiner::visitSHL(SDNode *N) {
3962   SDValue N0 = N->getOperand(0);
3963   SDValue N1 = N->getOperand(1);
3964   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3965   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3966   EVT VT = N0.getValueType();
3967   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3968
3969   // fold vector ops
3970   if (VT.isVector()) {
3971     SDValue FoldedVOp = SimplifyVBinOp(N);
3972     if (FoldedVOp.getNode()) return FoldedVOp;
3973
3974     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3975     // If setcc produces all-one true value then:
3976     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3977     if (N1CV && N1CV->isConstant()) {
3978       if (N0.getOpcode() == ISD::AND &&
3979           TLI.getBooleanContents(true) ==
3980           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3981         SDValue N00 = N0->getOperand(0);
3982         SDValue N01 = N0->getOperand(1);
3983         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3984
3985         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3986           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3987           if (C.getNode())
3988             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3989         }
3990       } else {
3991         N1C = isConstOrConstSplat(N1);
3992       }
3993     }
3994   }
3995
3996   // fold (shl c1, c2) -> c1<<c2
3997   if (N0C && N1C)
3998     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3999   // fold (shl 0, x) -> 0
4000   if (N0C && N0C->isNullValue())
4001     return N0;
4002   // fold (shl x, c >= size(x)) -> undef
4003   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4004     return DAG.getUNDEF(VT);
4005   // fold (shl x, 0) -> x
4006   if (N1C && N1C->isNullValue())
4007     return N0;
4008   // fold (shl undef, x) -> 0
4009   if (N0.getOpcode() == ISD::UNDEF)
4010     return DAG.getConstant(0, VT);
4011   // if (shl x, c) is known to be zero, return 0
4012   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4013                             APInt::getAllOnesValue(OpSizeInBits)))
4014     return DAG.getConstant(0, VT);
4015   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4016   if (N1.getOpcode() == ISD::TRUNCATE &&
4017       N1.getOperand(0).getOpcode() == ISD::AND) {
4018     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4019     if (NewOp1.getNode())
4020       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4021   }
4022
4023   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4024     return SDValue(N, 0);
4025
4026   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4027   if (N1C && N0.getOpcode() == ISD::SHL) {
4028     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4029       uint64_t c1 = N0C1->getZExtValue();
4030       uint64_t c2 = N1C->getZExtValue();
4031       if (c1 + c2 >= OpSizeInBits)
4032         return DAG.getConstant(0, VT);
4033       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4034                          DAG.getConstant(c1 + c2, N1.getValueType()));
4035     }
4036   }
4037
4038   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4039   // For this to be valid, the second form must not preserve any of the bits
4040   // that are shifted out by the inner shift in the first form.  This means
4041   // the outer shift size must be >= the number of bits added by the ext.
4042   // As a corollary, we don't care what kind of ext it is.
4043   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4044               N0.getOpcode() == ISD::ANY_EXTEND ||
4045               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4046       N0.getOperand(0).getOpcode() == ISD::SHL) {
4047     SDValue N0Op0 = N0.getOperand(0);
4048     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4049       uint64_t c1 = N0Op0C1->getZExtValue();
4050       uint64_t c2 = N1C->getZExtValue();
4051       EVT InnerShiftVT = N0Op0.getValueType();
4052       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4053       if (c2 >= OpSizeInBits - InnerShiftSize) {
4054         if (c1 + c2 >= OpSizeInBits)
4055           return DAG.getConstant(0, VT);
4056         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4057                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4058                                        N0Op0->getOperand(0)),
4059                            DAG.getConstant(c1 + c2, N1.getValueType()));
4060       }
4061     }
4062   }
4063
4064   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4065   // Only fold this if the inner zext has no other uses to avoid increasing
4066   // the total number of instructions.
4067   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4068       N0.getOperand(0).getOpcode() == ISD::SRL) {
4069     SDValue N0Op0 = N0.getOperand(0);
4070     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4071       uint64_t c1 = N0Op0C1->getZExtValue();
4072       if (c1 < VT.getScalarSizeInBits()) {
4073         uint64_t c2 = N1C->getZExtValue();
4074         if (c1 == c2) {
4075           SDValue NewOp0 = N0.getOperand(0);
4076           EVT CountVT = NewOp0.getOperand(1).getValueType();
4077           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4078                                        NewOp0, DAG.getConstant(c2, CountVT));
4079           AddToWorkList(NewSHL.getNode());
4080           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4081         }
4082       }
4083     }
4084   }
4085
4086   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4087   //                               (and (srl x, (sub c1, c2), MASK)
4088   // Only fold this if the inner shift has no other uses -- if it does, folding
4089   // this will increase the total number of instructions.
4090   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4091     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4092       uint64_t c1 = N0C1->getZExtValue();
4093       if (c1 < OpSizeInBits) {
4094         uint64_t c2 = N1C->getZExtValue();
4095         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4096         SDValue Shift;
4097         if (c2 > c1) {
4098           Mask = Mask.shl(c2 - c1);
4099           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4100                               DAG.getConstant(c2 - c1, N1.getValueType()));
4101         } else {
4102           Mask = Mask.lshr(c1 - c2);
4103           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4104                               DAG.getConstant(c1 - c2, N1.getValueType()));
4105         }
4106         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4107                            DAG.getConstant(Mask, VT));
4108       }
4109     }
4110   }
4111   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4112   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4113     unsigned BitSize = VT.getScalarSizeInBits();
4114     SDValue HiBitsMask =
4115       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4116                                             BitSize - N1C->getZExtValue()), VT);
4117     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4118                        HiBitsMask);
4119   }
4120
4121   if (N1C) {
4122     SDValue NewSHL = visitShiftByConstant(N, N1C);
4123     if (NewSHL.getNode())
4124       return NewSHL;
4125   }
4126
4127   return SDValue();
4128 }
4129
4130 SDValue DAGCombiner::visitSRA(SDNode *N) {
4131   SDValue N0 = N->getOperand(0);
4132   SDValue N1 = N->getOperand(1);
4133   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4134   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4135   EVT VT = N0.getValueType();
4136   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4137
4138   // fold vector ops
4139   if (VT.isVector()) {
4140     SDValue FoldedVOp = SimplifyVBinOp(N);
4141     if (FoldedVOp.getNode()) return FoldedVOp;
4142
4143     N1C = isConstOrConstSplat(N1);
4144   }
4145
4146   // fold (sra c1, c2) -> (sra c1, c2)
4147   if (N0C && N1C)
4148     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4149   // fold (sra 0, x) -> 0
4150   if (N0C && N0C->isNullValue())
4151     return N0;
4152   // fold (sra -1, x) -> -1
4153   if (N0C && N0C->isAllOnesValue())
4154     return N0;
4155   // fold (sra x, (setge c, size(x))) -> undef
4156   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4157     return DAG.getUNDEF(VT);
4158   // fold (sra x, 0) -> x
4159   if (N1C && N1C->isNullValue())
4160     return N0;
4161   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4162   // sext_inreg.
4163   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4164     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4165     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4166     if (VT.isVector())
4167       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4168                                ExtVT, VT.getVectorNumElements());
4169     if ((!LegalOperations ||
4170          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4171       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4172                          N0.getOperand(0), DAG.getValueType(ExtVT));
4173   }
4174
4175   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4176   if (N1C && N0.getOpcode() == ISD::SRA) {
4177     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4178       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4179       if (Sum >= OpSizeInBits)
4180         Sum = OpSizeInBits - 1;
4181       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4182                          DAG.getConstant(Sum, N1.getValueType()));
4183     }
4184   }
4185
4186   // fold (sra (shl X, m), (sub result_size, n))
4187   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4188   // result_size - n != m.
4189   // If truncate is free for the target sext(shl) is likely to result in better
4190   // code.
4191   if (N0.getOpcode() == ISD::SHL && N1C) {
4192     // Get the two constanst of the shifts, CN0 = m, CN = n.
4193     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4194     if (N01C) {
4195       LLVMContext &Ctx = *DAG.getContext();
4196       // Determine what the truncate's result bitsize and type would be.
4197       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4198
4199       if (VT.isVector())
4200         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4201
4202       // Determine the residual right-shift amount.
4203       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4204
4205       // If the shift is not a no-op (in which case this should be just a sign
4206       // extend already), the truncated to type is legal, sign_extend is legal
4207       // on that type, and the truncate to that type is both legal and free,
4208       // perform the transform.
4209       if ((ShiftAmt > 0) &&
4210           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4211           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4212           TLI.isTruncateFree(VT, TruncVT)) {
4213
4214           SDValue Amt = DAG.getConstant(ShiftAmt,
4215               getShiftAmountTy(N0.getOperand(0).getValueType()));
4216           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4217                                       N0.getOperand(0), Amt);
4218           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4219                                       Shift);
4220           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4221                              N->getValueType(0), Trunc);
4222       }
4223     }
4224   }
4225
4226   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4227   if (N1.getOpcode() == ISD::TRUNCATE &&
4228       N1.getOperand(0).getOpcode() == ISD::AND) {
4229     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4230     if (NewOp1.getNode())
4231       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4232   }
4233
4234   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4235   //      if c1 is equal to the number of bits the trunc removes
4236   if (N0.getOpcode() == ISD::TRUNCATE &&
4237       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4238        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4239       N0.getOperand(0).hasOneUse() &&
4240       N0.getOperand(0).getOperand(1).hasOneUse() &&
4241       N1C) {
4242     SDValue N0Op0 = N0.getOperand(0);
4243     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4244       unsigned LargeShiftVal = LargeShift->getZExtValue();
4245       EVT LargeVT = N0Op0.getValueType();
4246
4247       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4248         SDValue Amt =
4249           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4250                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4251         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4252                                   N0Op0.getOperand(0), Amt);
4253         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4254       }
4255     }
4256   }
4257
4258   // Simplify, based on bits shifted out of the LHS.
4259   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4260     return SDValue(N, 0);
4261
4262
4263   // If the sign bit is known to be zero, switch this to a SRL.
4264   if (DAG.SignBitIsZero(N0))
4265     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4266
4267   if (N1C) {
4268     SDValue NewSRA = visitShiftByConstant(N, N1C);
4269     if (NewSRA.getNode())
4270       return NewSRA;
4271   }
4272
4273   return SDValue();
4274 }
4275
4276 SDValue DAGCombiner::visitSRL(SDNode *N) {
4277   SDValue N0 = N->getOperand(0);
4278   SDValue N1 = N->getOperand(1);
4279   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4280   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4281   EVT VT = N0.getValueType();
4282   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4283
4284   // fold vector ops
4285   if (VT.isVector()) {
4286     SDValue FoldedVOp = SimplifyVBinOp(N);
4287     if (FoldedVOp.getNode()) return FoldedVOp;
4288
4289     N1C = isConstOrConstSplat(N1);
4290   }
4291
4292   // fold (srl c1, c2) -> c1 >>u c2
4293   if (N0C && N1C)
4294     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4295   // fold (srl 0, x) -> 0
4296   if (N0C && N0C->isNullValue())
4297     return N0;
4298   // fold (srl x, c >= size(x)) -> undef
4299   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4300     return DAG.getUNDEF(VT);
4301   // fold (srl x, 0) -> x
4302   if (N1C && N1C->isNullValue())
4303     return N0;
4304   // if (srl x, c) is known to be zero, return 0
4305   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4306                                    APInt::getAllOnesValue(OpSizeInBits)))
4307     return DAG.getConstant(0, VT);
4308
4309   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4310   if (N1C && N0.getOpcode() == ISD::SRL) {
4311     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4312       uint64_t c1 = N01C->getZExtValue();
4313       uint64_t c2 = N1C->getZExtValue();
4314       if (c1 + c2 >= OpSizeInBits)
4315         return DAG.getConstant(0, VT);
4316       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4317                          DAG.getConstant(c1 + c2, N1.getValueType()));
4318     }
4319   }
4320
4321   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4322   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4323       N0.getOperand(0).getOpcode() == ISD::SRL &&
4324       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4325     uint64_t c1 =
4326       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4327     uint64_t c2 = N1C->getZExtValue();
4328     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4329     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4330     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4331     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4332     if (c1 + OpSizeInBits == InnerShiftSize) {
4333       if (c1 + c2 >= InnerShiftSize)
4334         return DAG.getConstant(0, VT);
4335       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4336                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4337                                      N0.getOperand(0)->getOperand(0),
4338                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4339     }
4340   }
4341
4342   // fold (srl (shl x, c), c) -> (and x, cst2)
4343   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4344     unsigned BitSize = N0.getScalarValueSizeInBits();
4345     if (BitSize <= 64) {
4346       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4347       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4348                          DAG.getConstant(~0ULL >> ShAmt, VT));
4349     }
4350   }
4351
4352   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4353   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4354     // Shifting in all undef bits?
4355     EVT SmallVT = N0.getOperand(0).getValueType();
4356     unsigned BitSize = SmallVT.getScalarSizeInBits();
4357     if (N1C->getZExtValue() >= BitSize)
4358       return DAG.getUNDEF(VT);
4359
4360     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4361       uint64_t ShiftAmt = N1C->getZExtValue();
4362       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4363                                        N0.getOperand(0),
4364                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4365       AddToWorkList(SmallShift.getNode());
4366       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4367       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4368                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4369                          DAG.getConstant(Mask, VT));
4370     }
4371   }
4372
4373   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4374   // bit, which is unmodified by sra.
4375   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4376     if (N0.getOpcode() == ISD::SRA)
4377       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4378   }
4379
4380   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4381   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4382       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4383     APInt KnownZero, KnownOne;
4384     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4385
4386     // If any of the input bits are KnownOne, then the input couldn't be all
4387     // zeros, thus the result of the srl will always be zero.
4388     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4389
4390     // If all of the bits input the to ctlz node are known to be zero, then
4391     // the result of the ctlz is "32" and the result of the shift is one.
4392     APInt UnknownBits = ~KnownZero;
4393     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4394
4395     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4396     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4397       // Okay, we know that only that the single bit specified by UnknownBits
4398       // could be set on input to the CTLZ node. If this bit is set, the SRL
4399       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4400       // to an SRL/XOR pair, which is likely to simplify more.
4401       unsigned ShAmt = UnknownBits.countTrailingZeros();
4402       SDValue Op = N0.getOperand(0);
4403
4404       if (ShAmt) {
4405         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4406                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4407         AddToWorkList(Op.getNode());
4408       }
4409
4410       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4411                          Op, DAG.getConstant(1, VT));
4412     }
4413   }
4414
4415   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4416   if (N1.getOpcode() == ISD::TRUNCATE &&
4417       N1.getOperand(0).getOpcode() == ISD::AND) {
4418     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4419     if (NewOp1.getNode())
4420       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4421   }
4422
4423   // fold operands of srl based on knowledge that the low bits are not
4424   // demanded.
4425   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4426     return SDValue(N, 0);
4427
4428   if (N1C) {
4429     SDValue NewSRL = visitShiftByConstant(N, N1C);
4430     if (NewSRL.getNode())
4431       return NewSRL;
4432   }
4433
4434   // Attempt to convert a srl of a load into a narrower zero-extending load.
4435   SDValue NarrowLoad = ReduceLoadWidth(N);
4436   if (NarrowLoad.getNode())
4437     return NarrowLoad;
4438
4439   // Here is a common situation. We want to optimize:
4440   //
4441   //   %a = ...
4442   //   %b = and i32 %a, 2
4443   //   %c = srl i32 %b, 1
4444   //   brcond i32 %c ...
4445   //
4446   // into
4447   //
4448   //   %a = ...
4449   //   %b = and %a, 2
4450   //   %c = setcc eq %b, 0
4451   //   brcond %c ...
4452   //
4453   // However when after the source operand of SRL is optimized into AND, the SRL
4454   // itself may not be optimized further. Look for it and add the BRCOND into
4455   // the worklist.
4456   if (N->hasOneUse()) {
4457     SDNode *Use = *N->use_begin();
4458     if (Use->getOpcode() == ISD::BRCOND)
4459       AddToWorkList(Use);
4460     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4461       // Also look pass the truncate.
4462       Use = *Use->use_begin();
4463       if (Use->getOpcode() == ISD::BRCOND)
4464         AddToWorkList(Use);
4465     }
4466   }
4467
4468   return SDValue();
4469 }
4470
4471 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4472   SDValue N0 = N->getOperand(0);
4473   EVT VT = N->getValueType(0);
4474
4475   // fold (ctlz c1) -> c2
4476   if (isa<ConstantSDNode>(N0))
4477     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4478   return SDValue();
4479 }
4480
4481 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4482   SDValue N0 = N->getOperand(0);
4483   EVT VT = N->getValueType(0);
4484
4485   // fold (ctlz_zero_undef c1) -> c2
4486   if (isa<ConstantSDNode>(N0))
4487     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4488   return SDValue();
4489 }
4490
4491 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4492   SDValue N0 = N->getOperand(0);
4493   EVT VT = N->getValueType(0);
4494
4495   // fold (cttz c1) -> c2
4496   if (isa<ConstantSDNode>(N0))
4497     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4498   return SDValue();
4499 }
4500
4501 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4502   SDValue N0 = N->getOperand(0);
4503   EVT VT = N->getValueType(0);
4504
4505   // fold (cttz_zero_undef c1) -> c2
4506   if (isa<ConstantSDNode>(N0))
4507     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4508   return SDValue();
4509 }
4510
4511 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4512   SDValue N0 = N->getOperand(0);
4513   EVT VT = N->getValueType(0);
4514
4515   // fold (ctpop c1) -> c2
4516   if (isa<ConstantSDNode>(N0))
4517     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4518   return SDValue();
4519 }
4520
4521 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4522   SDValue N0 = N->getOperand(0);
4523   SDValue N1 = N->getOperand(1);
4524   SDValue N2 = N->getOperand(2);
4525   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4526   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4527   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4528   EVT VT = N->getValueType(0);
4529   EVT VT0 = N0.getValueType();
4530
4531   // fold (select C, X, X) -> X
4532   if (N1 == N2)
4533     return N1;
4534   // fold (select true, X, Y) -> X
4535   if (N0C && !N0C->isNullValue())
4536     return N1;
4537   // fold (select false, X, Y) -> Y
4538   if (N0C && N0C->isNullValue())
4539     return N2;
4540   // fold (select C, 1, X) -> (or C, X)
4541   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4542     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4543   // fold (select C, 0, 1) -> (xor C, 1)
4544   if (VT.isInteger() &&
4545       (VT0 == MVT::i1 ||
4546        (VT0.isInteger() &&
4547         TLI.getBooleanContents(false) ==
4548         TargetLowering::ZeroOrOneBooleanContent)) &&
4549       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4550     SDValue XORNode;
4551     if (VT == VT0)
4552       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4553                          N0, DAG.getConstant(1, VT0));
4554     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4555                           N0, DAG.getConstant(1, VT0));
4556     AddToWorkList(XORNode.getNode());
4557     if (VT.bitsGT(VT0))
4558       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4559     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4560   }
4561   // fold (select C, 0, X) -> (and (not C), X)
4562   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4563     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4564     AddToWorkList(NOTNode.getNode());
4565     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4566   }
4567   // fold (select C, X, 1) -> (or (not C), X)
4568   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4569     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4570     AddToWorkList(NOTNode.getNode());
4571     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4572   }
4573   // fold (select C, X, 0) -> (and C, X)
4574   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4575     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4576   // fold (select X, X, Y) -> (or X, Y)
4577   // fold (select X, 1, Y) -> (or X, Y)
4578   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4579     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4580   // fold (select X, Y, X) -> (and X, Y)
4581   // fold (select X, Y, 0) -> (and X, Y)
4582   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4583     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4584
4585   // If we can fold this based on the true/false value, do so.
4586   if (SimplifySelectOps(N, N1, N2))
4587     return SDValue(N, 0);  // Don't revisit N.
4588
4589   // fold selects based on a setcc into other things, such as min/max/abs
4590   if (N0.getOpcode() == ISD::SETCC) {
4591     // FIXME:
4592     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4593     // having to say they don't support SELECT_CC on every type the DAG knows
4594     // about, since there is no way to mark an opcode illegal at all value types
4595     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4596         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4597       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4598                          N0.getOperand(0), N0.getOperand(1),
4599                          N1, N2, N0.getOperand(2));
4600     return SimplifySelect(SDLoc(N), N0, N1, N2);
4601   }
4602
4603   return SDValue();
4604 }
4605
4606 static
4607 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4608   SDLoc DL(N);
4609   EVT LoVT, HiVT;
4610   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4611
4612   // Split the inputs.
4613   SDValue Lo, Hi, LL, LH, RL, RH;
4614   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4615   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4616
4617   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4618   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4619
4620   return std::make_pair(Lo, Hi);
4621 }
4622
4623 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4624   SDValue N0 = N->getOperand(0);
4625   SDValue N1 = N->getOperand(1);
4626   SDValue N2 = N->getOperand(2);
4627   SDLoc DL(N);
4628
4629   // Canonicalize integer abs.
4630   // vselect (setg[te] X,  0),  X, -X ->
4631   // vselect (setgt    X, -1),  X, -X ->
4632   // vselect (setl[te] X,  0), -X,  X ->
4633   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4634   if (N0.getOpcode() == ISD::SETCC) {
4635     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4636     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4637     bool isAbs = false;
4638     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4639
4640     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4641          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4642         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4643       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4644     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4645              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4646       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4647
4648     if (isAbs) {
4649       EVT VT = LHS.getValueType();
4650       SDValue Shift = DAG.getNode(
4651           ISD::SRA, DL, VT, LHS,
4652           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4653       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4654       AddToWorkList(Shift.getNode());
4655       AddToWorkList(Add.getNode());
4656       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4657     }
4658   }
4659
4660   // If the VSELECT result requires splitting and the mask is provided by a
4661   // SETCC, then split both nodes and its operands before legalization. This
4662   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4663   // and enables future optimizations (e.g. min/max pattern matching on X86).
4664   if (N0.getOpcode() == ISD::SETCC) {
4665     EVT VT = N->getValueType(0);
4666
4667     // Check if any splitting is required.
4668     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4669         TargetLowering::TypeSplitVector)
4670       return SDValue();
4671
4672     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4673     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4674     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4675     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4676
4677     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4678     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4679
4680     // Add the new VSELECT nodes to the work list in case they need to be split
4681     // again.
4682     AddToWorkList(Lo.getNode());
4683     AddToWorkList(Hi.getNode());
4684
4685     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4686   }
4687
4688   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4689   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4690     return N1;
4691   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4692   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4693     return N2;
4694
4695   return SDValue();
4696 }
4697
4698 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4699   SDValue N0 = N->getOperand(0);
4700   SDValue N1 = N->getOperand(1);
4701   SDValue N2 = N->getOperand(2);
4702   SDValue N3 = N->getOperand(3);
4703   SDValue N4 = N->getOperand(4);
4704   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4705
4706   // fold select_cc lhs, rhs, x, x, cc -> x
4707   if (N2 == N3)
4708     return N2;
4709
4710   // Determine if the condition we're dealing with is constant
4711   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4712                               N0, N1, CC, SDLoc(N), false);
4713   if (SCC.getNode()) {
4714     AddToWorkList(SCC.getNode());
4715
4716     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4717       if (!SCCC->isNullValue())
4718         return N2;    // cond always true -> true val
4719       else
4720         return N3;    // cond always false -> false val
4721     }
4722
4723     // Fold to a simpler select_cc
4724     if (SCC.getOpcode() == ISD::SETCC)
4725       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4726                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4727                          SCC.getOperand(2));
4728   }
4729
4730   // If we can fold this based on the true/false value, do so.
4731   if (SimplifySelectOps(N, N2, N3))
4732     return SDValue(N, 0);  // Don't revisit N.
4733
4734   // fold select_cc into other things, such as min/max/abs
4735   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4736 }
4737
4738 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4739   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4740                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4741                        SDLoc(N));
4742 }
4743
4744 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4745 // dag node into a ConstantSDNode or a build_vector of constants.
4746 // This function is called by the DAGCombiner when visiting sext/zext/aext
4747 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4748 // Vector extends are not folded if operations are legal; this is to
4749 // avoid introducing illegal build_vector dag nodes.
4750 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4751                                          SelectionDAG &DAG, bool LegalTypes,
4752                                          bool LegalOperations) {
4753   unsigned Opcode = N->getOpcode();
4754   SDValue N0 = N->getOperand(0);
4755   EVT VT = N->getValueType(0);
4756
4757   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4758          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4759
4760   // fold (sext c1) -> c1
4761   // fold (zext c1) -> c1
4762   // fold (aext c1) -> c1
4763   if (isa<ConstantSDNode>(N0))
4764     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4765
4766   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4767   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4768   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4769   EVT SVT = VT.getScalarType();
4770   if (!(VT.isVector() &&
4771       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4772       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4773     return 0;
4774   
4775   // We can fold this node into a build_vector.
4776   unsigned VTBits = SVT.getSizeInBits();
4777   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4778   unsigned ShAmt = VTBits - EVTBits;
4779   SmallVector<SDValue, 8> Elts;
4780   unsigned NumElts = N0->getNumOperands();
4781   SDLoc DL(N);
4782
4783   for (unsigned i=0; i != NumElts; ++i) {
4784     SDValue Op = N0->getOperand(i);
4785     if (Op->getOpcode() == ISD::UNDEF) {
4786       Elts.push_back(DAG.getUNDEF(SVT));
4787       continue;
4788     }
4789
4790     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4791     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4792     if (Opcode == ISD::SIGN_EXTEND)
4793       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4794                                      SVT));
4795     else
4796       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4797                                      SVT));
4798   }
4799
4800   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4801 }
4802
4803 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4804 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4805 // transformation. Returns true if extension are possible and the above
4806 // mentioned transformation is profitable.
4807 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4808                                     unsigned ExtOpc,
4809                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4810                                     const TargetLowering &TLI) {
4811   bool HasCopyToRegUses = false;
4812   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4813   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4814                             UE = N0.getNode()->use_end();
4815        UI != UE; ++UI) {
4816     SDNode *User = *UI;
4817     if (User == N)
4818       continue;
4819     if (UI.getUse().getResNo() != N0.getResNo())
4820       continue;
4821     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4822     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4823       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4824       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4825         // Sign bits will be lost after a zext.
4826         return false;
4827       bool Add = false;
4828       for (unsigned i = 0; i != 2; ++i) {
4829         SDValue UseOp = User->getOperand(i);
4830         if (UseOp == N0)
4831           continue;
4832         if (!isa<ConstantSDNode>(UseOp))
4833           return false;
4834         Add = true;
4835       }
4836       if (Add)
4837         ExtendNodes.push_back(User);
4838       continue;
4839     }
4840     // If truncates aren't free and there are users we can't
4841     // extend, it isn't worthwhile.
4842     if (!isTruncFree)
4843       return false;
4844     // Remember if this value is live-out.
4845     if (User->getOpcode() == ISD::CopyToReg)
4846       HasCopyToRegUses = true;
4847   }
4848
4849   if (HasCopyToRegUses) {
4850     bool BothLiveOut = false;
4851     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4852          UI != UE; ++UI) {
4853       SDUse &Use = UI.getUse();
4854       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4855         BothLiveOut = true;
4856         break;
4857       }
4858     }
4859     if (BothLiveOut)
4860       // Both unextended and extended values are live out. There had better be
4861       // a good reason for the transformation.
4862       return ExtendNodes.size();
4863   }
4864   return true;
4865 }
4866
4867 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4868                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4869                                   ISD::NodeType ExtType) {
4870   // Extend SetCC uses if necessary.
4871   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4872     SDNode *SetCC = SetCCs[i];
4873     SmallVector<SDValue, 4> Ops;
4874
4875     for (unsigned j = 0; j != 2; ++j) {
4876       SDValue SOp = SetCC->getOperand(j);
4877       if (SOp == Trunc)
4878         Ops.push_back(ExtLoad);
4879       else
4880         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4881     }
4882
4883     Ops.push_back(SetCC->getOperand(2));
4884     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4885                                  &Ops[0], Ops.size()));
4886   }
4887 }
4888
4889 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4890   SDValue N0 = N->getOperand(0);
4891   EVT VT = N->getValueType(0);
4892
4893   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4894                                               LegalOperations))
4895     return SDValue(Res, 0);
4896
4897   // fold (sext (sext x)) -> (sext x)
4898   // fold (sext (aext x)) -> (sext x)
4899   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4900     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4901                        N0.getOperand(0));
4902
4903   if (N0.getOpcode() == ISD::TRUNCATE) {
4904     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4905     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4906     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4907     if (NarrowLoad.getNode()) {
4908       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4909       if (NarrowLoad.getNode() != N0.getNode()) {
4910         CombineTo(N0.getNode(), NarrowLoad);
4911         // CombineTo deleted the truncate, if needed, but not what's under it.
4912         AddToWorkList(oye);
4913       }
4914       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4915     }
4916
4917     // See if the value being truncated is already sign extended.  If so, just
4918     // eliminate the trunc/sext pair.
4919     SDValue Op = N0.getOperand(0);
4920     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4921     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4922     unsigned DestBits = VT.getScalarType().getSizeInBits();
4923     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4924
4925     if (OpBits == DestBits) {
4926       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4927       // bits, it is already ready.
4928       if (NumSignBits > DestBits-MidBits)
4929         return Op;
4930     } else if (OpBits < DestBits) {
4931       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4932       // bits, just sext from i32.
4933       if (NumSignBits > OpBits-MidBits)
4934         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4935     } else {
4936       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4937       // bits, just truncate to i32.
4938       if (NumSignBits > OpBits-MidBits)
4939         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4940     }
4941
4942     // fold (sext (truncate x)) -> (sextinreg x).
4943     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4944                                                  N0.getValueType())) {
4945       if (OpBits < DestBits)
4946         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4947       else if (OpBits > DestBits)
4948         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4949       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4950                          DAG.getValueType(N0.getValueType()));
4951     }
4952   }
4953
4954   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4955   // None of the supported targets knows how to perform load and sign extend
4956   // on vectors in one instruction.  We only perform this transformation on
4957   // scalars.
4958   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4959       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4960       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4961        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4962     bool DoXform = true;
4963     SmallVector<SDNode*, 4> SetCCs;
4964     if (!N0.hasOneUse())
4965       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4966     if (DoXform) {
4967       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4968       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4969                                        LN0->getChain(),
4970                                        LN0->getBasePtr(), N0.getValueType(),
4971                                        LN0->getMemOperand());
4972       CombineTo(N, ExtLoad);
4973       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4974                                   N0.getValueType(), ExtLoad);
4975       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4976       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4977                       ISD::SIGN_EXTEND);
4978       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4979     }
4980   }
4981
4982   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4983   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4984   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4985       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4986     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4987     EVT MemVT = LN0->getMemoryVT();
4988     if ((!LegalOperations && !LN0->isVolatile()) ||
4989         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4990       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4991                                        LN0->getChain(),
4992                                        LN0->getBasePtr(), MemVT,
4993                                        LN0->getMemOperand());
4994       CombineTo(N, ExtLoad);
4995       CombineTo(N0.getNode(),
4996                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4997                             N0.getValueType(), ExtLoad),
4998                 ExtLoad.getValue(1));
4999       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5000     }
5001   }
5002
5003   // fold (sext (and/or/xor (load x), cst)) ->
5004   //      (and/or/xor (sextload x), (sext cst))
5005   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5006        N0.getOpcode() == ISD::XOR) &&
5007       isa<LoadSDNode>(N0.getOperand(0)) &&
5008       N0.getOperand(1).getOpcode() == ISD::Constant &&
5009       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5010       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5011     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5012     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5013       bool DoXform = true;
5014       SmallVector<SDNode*, 4> SetCCs;
5015       if (!N0.hasOneUse())
5016         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5017                                           SetCCs, TLI);
5018       if (DoXform) {
5019         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5020                                          LN0->getChain(), LN0->getBasePtr(),
5021                                          LN0->getMemoryVT(),
5022                                          LN0->getMemOperand());
5023         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5024         Mask = Mask.sext(VT.getSizeInBits());
5025         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5026                                   ExtLoad, DAG.getConstant(Mask, VT));
5027         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5028                                     SDLoc(N0.getOperand(0)),
5029                                     N0.getOperand(0).getValueType(), ExtLoad);
5030         CombineTo(N, And);
5031         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5032         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5033                         ISD::SIGN_EXTEND);
5034         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5035       }
5036     }
5037   }
5038
5039   if (N0.getOpcode() == ISD::SETCC) {
5040     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5041     // Only do this before legalize for now.
5042     if (VT.isVector() && !LegalOperations &&
5043         TLI.getBooleanContents(true) ==
5044           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5045       EVT N0VT = N0.getOperand(0).getValueType();
5046       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5047       // of the same size as the compared operands. Only optimize sext(setcc())
5048       // if this is the case.
5049       EVT SVT = getSetCCResultType(N0VT);
5050
5051       // We know that the # elements of the results is the same as the
5052       // # elements of the compare (and the # elements of the compare result
5053       // for that matter).  Check to see that they are the same size.  If so,
5054       // we know that the element size of the sext'd result matches the
5055       // element size of the compare operands.
5056       if (VT.getSizeInBits() == SVT.getSizeInBits())
5057         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5058                              N0.getOperand(1),
5059                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5060
5061       // If the desired elements are smaller or larger than the source
5062       // elements we can use a matching integer vector type and then
5063       // truncate/sign extend
5064       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5065       if (SVT == MatchingVectorType) {
5066         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5067                                N0.getOperand(0), N0.getOperand(1),
5068                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5069         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5070       }
5071     }
5072
5073     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5074     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5075     SDValue NegOne =
5076       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5077     SDValue SCC =
5078       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5079                        NegOne, DAG.getConstant(0, VT),
5080                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5081     if (SCC.getNode()) return SCC;
5082
5083     if (!VT.isVector()) {
5084       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5085       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5086         SDLoc DL(N);
5087         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5088         SDValue SetCC = DAG.getSetCC(DL,
5089                                      SetCCVT,
5090                                      N0.getOperand(0), N0.getOperand(1), CC);
5091         EVT SelectVT = getSetCCResultType(VT);
5092         return DAG.getSelect(DL, VT,
5093                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5094                              NegOne, DAG.getConstant(0, VT));
5095
5096       }
5097     }
5098   }
5099
5100   // fold (sext x) -> (zext x) if the sign bit is known zero.
5101   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5102       DAG.SignBitIsZero(N0))
5103     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5104
5105   return SDValue();
5106 }
5107
5108 // isTruncateOf - If N is a truncate of some other value, return true, record
5109 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5110 // This function computes KnownZero to avoid a duplicated call to
5111 // ComputeMaskedBits in the caller.
5112 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5113                          APInt &KnownZero) {
5114   APInt KnownOne;
5115   if (N->getOpcode() == ISD::TRUNCATE) {
5116     Op = N->getOperand(0);
5117     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5118     return true;
5119   }
5120
5121   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5122       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5123     return false;
5124
5125   SDValue Op0 = N->getOperand(0);
5126   SDValue Op1 = N->getOperand(1);
5127   assert(Op0.getValueType() == Op1.getValueType());
5128
5129   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5130   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5131   if (COp0 && COp0->isNullValue())
5132     Op = Op1;
5133   else if (COp1 && COp1->isNullValue())
5134     Op = Op0;
5135   else
5136     return false;
5137
5138   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5139
5140   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5141     return false;
5142
5143   return true;
5144 }
5145
5146 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5147   SDValue N0 = N->getOperand(0);
5148   EVT VT = N->getValueType(0);
5149
5150   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5151                                               LegalOperations))
5152     return SDValue(Res, 0);
5153
5154   // fold (zext (zext x)) -> (zext x)
5155   // fold (zext (aext x)) -> (zext x)
5156   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5157     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5158                        N0.getOperand(0));
5159
5160   // fold (zext (truncate x)) -> (zext x) or
5161   //      (zext (truncate x)) -> (truncate x)
5162   // This is valid when the truncated bits of x are already zero.
5163   // FIXME: We should extend this to work for vectors too.
5164   SDValue Op;
5165   APInt KnownZero;
5166   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5167     APInt TruncatedBits =
5168       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5169       APInt(Op.getValueSizeInBits(), 0) :
5170       APInt::getBitsSet(Op.getValueSizeInBits(),
5171                         N0.getValueSizeInBits(),
5172                         std::min(Op.getValueSizeInBits(),
5173                                  VT.getSizeInBits()));
5174     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5175       if (VT.bitsGT(Op.getValueType()))
5176         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5177       if (VT.bitsLT(Op.getValueType()))
5178         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5179
5180       return Op;
5181     }
5182   }
5183
5184   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5185   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5186   if (N0.getOpcode() == ISD::TRUNCATE) {
5187     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5188     if (NarrowLoad.getNode()) {
5189       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5190       if (NarrowLoad.getNode() != N0.getNode()) {
5191         CombineTo(N0.getNode(), NarrowLoad);
5192         // CombineTo deleted the truncate, if needed, but not what's under it.
5193         AddToWorkList(oye);
5194       }
5195       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5196     }
5197   }
5198
5199   // fold (zext (truncate x)) -> (and x, mask)
5200   if (N0.getOpcode() == ISD::TRUNCATE &&
5201       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5202
5203     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5204     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5205     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5206     if (NarrowLoad.getNode()) {
5207       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5208       if (NarrowLoad.getNode() != N0.getNode()) {
5209         CombineTo(N0.getNode(), NarrowLoad);
5210         // CombineTo deleted the truncate, if needed, but not what's under it.
5211         AddToWorkList(oye);
5212       }
5213       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5214     }
5215
5216     SDValue Op = N0.getOperand(0);
5217     if (Op.getValueType().bitsLT(VT)) {
5218       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5219       AddToWorkList(Op.getNode());
5220     } else if (Op.getValueType().bitsGT(VT)) {
5221       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5222       AddToWorkList(Op.getNode());
5223     }
5224     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5225                                   N0.getValueType().getScalarType());
5226   }
5227
5228   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5229   // if either of the casts is not free.
5230   if (N0.getOpcode() == ISD::AND &&
5231       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5232       N0.getOperand(1).getOpcode() == ISD::Constant &&
5233       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5234                            N0.getValueType()) ||
5235        !TLI.isZExtFree(N0.getValueType(), VT))) {
5236     SDValue X = N0.getOperand(0).getOperand(0);
5237     if (X.getValueType().bitsLT(VT)) {
5238       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5239     } else if (X.getValueType().bitsGT(VT)) {
5240       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5241     }
5242     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5243     Mask = Mask.zext(VT.getSizeInBits());
5244     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5245                        X, DAG.getConstant(Mask, VT));
5246   }
5247
5248   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5249   // None of the supported targets knows how to perform load and vector_zext
5250   // on vectors in one instruction.  We only perform this transformation on
5251   // scalars.
5252   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5253       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5254       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5255        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5256     bool DoXform = true;
5257     SmallVector<SDNode*, 4> SetCCs;
5258     if (!N0.hasOneUse())
5259       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5260     if (DoXform) {
5261       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5262       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5263                                        LN0->getChain(),
5264                                        LN0->getBasePtr(), N0.getValueType(),
5265                                        LN0->getMemOperand());
5266       CombineTo(N, ExtLoad);
5267       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5268                                   N0.getValueType(), ExtLoad);
5269       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5270
5271       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5272                       ISD::ZERO_EXTEND);
5273       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5274     }
5275   }
5276
5277   // fold (zext (and/or/xor (load x), cst)) ->
5278   //      (and/or/xor (zextload x), (zext cst))
5279   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5280        N0.getOpcode() == ISD::XOR) &&
5281       isa<LoadSDNode>(N0.getOperand(0)) &&
5282       N0.getOperand(1).getOpcode() == ISD::Constant &&
5283       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5284       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5285     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5286     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5287       bool DoXform = true;
5288       SmallVector<SDNode*, 4> SetCCs;
5289       if (!N0.hasOneUse())
5290         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5291                                           SetCCs, TLI);
5292       if (DoXform) {
5293         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5294                                          LN0->getChain(), LN0->getBasePtr(),
5295                                          LN0->getMemoryVT(),
5296                                          LN0->getMemOperand());
5297         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5298         Mask = Mask.zext(VT.getSizeInBits());
5299         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5300                                   ExtLoad, DAG.getConstant(Mask, VT));
5301         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5302                                     SDLoc(N0.getOperand(0)),
5303                                     N0.getOperand(0).getValueType(), ExtLoad);
5304         CombineTo(N, And);
5305         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5306         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5307                         ISD::ZERO_EXTEND);
5308         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5309       }
5310     }
5311   }
5312
5313   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5314   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5315   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5316       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5317     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5318     EVT MemVT = LN0->getMemoryVT();
5319     if ((!LegalOperations && !LN0->isVolatile()) ||
5320         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5321       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5322                                        LN0->getChain(),
5323                                        LN0->getBasePtr(), MemVT,
5324                                        LN0->getMemOperand());
5325       CombineTo(N, ExtLoad);
5326       CombineTo(N0.getNode(),
5327                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5328                             ExtLoad),
5329                 ExtLoad.getValue(1));
5330       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5331     }
5332   }
5333
5334   if (N0.getOpcode() == ISD::SETCC) {
5335     if (!LegalOperations && VT.isVector() &&
5336         N0.getValueType().getVectorElementType() == MVT::i1) {
5337       EVT N0VT = N0.getOperand(0).getValueType();
5338       if (getSetCCResultType(N0VT) == N0.getValueType())
5339         return SDValue();
5340
5341       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5342       // Only do this before legalize for now.
5343       EVT EltVT = VT.getVectorElementType();
5344       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5345                                     DAG.getConstant(1, EltVT));
5346       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5347         // We know that the # elements of the results is the same as the
5348         // # elements of the compare (and the # elements of the compare result
5349         // for that matter).  Check to see that they are the same size.  If so,
5350         // we know that the element size of the sext'd result matches the
5351         // element size of the compare operands.
5352         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5353                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5354                                          N0.getOperand(1),
5355                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5356                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5357                                        &OneOps[0], OneOps.size()));
5358
5359       // If the desired elements are smaller or larger than the source
5360       // elements we can use a matching integer vector type and then
5361       // truncate/sign extend
5362       EVT MatchingElementType =
5363         EVT::getIntegerVT(*DAG.getContext(),
5364                           N0VT.getScalarType().getSizeInBits());
5365       EVT MatchingVectorType =
5366         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5367                          N0VT.getVectorNumElements());
5368       SDValue VsetCC =
5369         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5370                       N0.getOperand(1),
5371                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5372       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5373                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5374                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5375                                      &OneOps[0], OneOps.size()));
5376     }
5377
5378     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5379     SDValue SCC =
5380       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5381                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5382                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5383     if (SCC.getNode()) return SCC;
5384   }
5385
5386   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5387   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5388       isa<ConstantSDNode>(N0.getOperand(1)) &&
5389       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5390       N0.hasOneUse()) {
5391     SDValue ShAmt = N0.getOperand(1);
5392     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5393     if (N0.getOpcode() == ISD::SHL) {
5394       SDValue InnerZExt = N0.getOperand(0);
5395       // If the original shl may be shifting out bits, do not perform this
5396       // transformation.
5397       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5398         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5399       if (ShAmtVal > KnownZeroBits)
5400         return SDValue();
5401     }
5402
5403     SDLoc DL(N);
5404
5405     // Ensure that the shift amount is wide enough for the shifted value.
5406     if (VT.getSizeInBits() >= 256)
5407       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5408
5409     return DAG.getNode(N0.getOpcode(), DL, VT,
5410                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5411                        ShAmt);
5412   }
5413
5414   return SDValue();
5415 }
5416
5417 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5418   SDValue N0 = N->getOperand(0);
5419   EVT VT = N->getValueType(0);
5420
5421   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5422                                               LegalOperations))
5423     return SDValue(Res, 0);
5424
5425   // fold (aext (aext x)) -> (aext x)
5426   // fold (aext (zext x)) -> (zext x)
5427   // fold (aext (sext x)) -> (sext x)
5428   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5429       N0.getOpcode() == ISD::ZERO_EXTEND ||
5430       N0.getOpcode() == ISD::SIGN_EXTEND)
5431     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5432
5433   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5434   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5435   if (N0.getOpcode() == ISD::TRUNCATE) {
5436     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5437     if (NarrowLoad.getNode()) {
5438       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5439       if (NarrowLoad.getNode() != N0.getNode()) {
5440         CombineTo(N0.getNode(), NarrowLoad);
5441         // CombineTo deleted the truncate, if needed, but not what's under it.
5442         AddToWorkList(oye);
5443       }
5444       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5445     }
5446   }
5447
5448   // fold (aext (truncate x))
5449   if (N0.getOpcode() == ISD::TRUNCATE) {
5450     SDValue TruncOp = N0.getOperand(0);
5451     if (TruncOp.getValueType() == VT)
5452       return TruncOp; // x iff x size == zext size.
5453     if (TruncOp.getValueType().bitsGT(VT))
5454       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5455     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5456   }
5457
5458   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5459   // if the trunc is not free.
5460   if (N0.getOpcode() == ISD::AND &&
5461       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5462       N0.getOperand(1).getOpcode() == ISD::Constant &&
5463       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5464                           N0.getValueType())) {
5465     SDValue X = N0.getOperand(0).getOperand(0);
5466     if (X.getValueType().bitsLT(VT)) {
5467       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5468     } else if (X.getValueType().bitsGT(VT)) {
5469       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5470     }
5471     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5472     Mask = Mask.zext(VT.getSizeInBits());
5473     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5474                        X, DAG.getConstant(Mask, VT));
5475   }
5476
5477   // fold (aext (load x)) -> (aext (truncate (extload x)))
5478   // None of the supported targets knows how to perform load and any_ext
5479   // on vectors in one instruction.  We only perform this transformation on
5480   // scalars.
5481   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5482       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5483       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5484        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5485     bool DoXform = true;
5486     SmallVector<SDNode*, 4> SetCCs;
5487     if (!N0.hasOneUse())
5488       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5489     if (DoXform) {
5490       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5491       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5492                                        LN0->getChain(),
5493                                        LN0->getBasePtr(), N0.getValueType(),
5494                                        LN0->getMemOperand());
5495       CombineTo(N, ExtLoad);
5496       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5497                                   N0.getValueType(), ExtLoad);
5498       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5499       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5500                       ISD::ANY_EXTEND);
5501       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5502     }
5503   }
5504
5505   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5506   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5507   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5508   if (N0.getOpcode() == ISD::LOAD &&
5509       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5510       N0.hasOneUse()) {
5511     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5512     ISD::LoadExtType ExtType = LN0->getExtensionType();
5513     EVT MemVT = LN0->getMemoryVT();
5514     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5515       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5516                                        VT, LN0->getChain(), LN0->getBasePtr(),
5517                                        MemVT, LN0->getMemOperand());
5518       CombineTo(N, ExtLoad);
5519       CombineTo(N0.getNode(),
5520                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5521                             N0.getValueType(), ExtLoad),
5522                 ExtLoad.getValue(1));
5523       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5524     }
5525   }
5526
5527   if (N0.getOpcode() == ISD::SETCC) {
5528     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5529     // Only do this before legalize for now.
5530     if (VT.isVector() && !LegalOperations) {
5531       EVT N0VT = N0.getOperand(0).getValueType();
5532         // We know that the # elements of the results is the same as the
5533         // # elements of the compare (and the # elements of the compare result
5534         // for that matter).  Check to see that they are the same size.  If so,
5535         // we know that the element size of the sext'd result matches the
5536         // element size of the compare operands.
5537       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5538         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5539                              N0.getOperand(1),
5540                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5541       // If the desired elements are smaller or larger than the source
5542       // elements we can use a matching integer vector type and then
5543       // truncate/sign extend
5544       else {
5545         EVT MatchingElementType =
5546           EVT::getIntegerVT(*DAG.getContext(),
5547                             N0VT.getScalarType().getSizeInBits());
5548         EVT MatchingVectorType =
5549           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5550                            N0VT.getVectorNumElements());
5551         SDValue VsetCC =
5552           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5553                         N0.getOperand(1),
5554                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5555         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5556       }
5557     }
5558
5559     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5560     SDValue SCC =
5561       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5562                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5563                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5564     if (SCC.getNode())
5565       return SCC;
5566   }
5567
5568   return SDValue();
5569 }
5570
5571 /// GetDemandedBits - See if the specified operand can be simplified with the
5572 /// knowledge that only the bits specified by Mask are used.  If so, return the
5573 /// simpler operand, otherwise return a null SDValue.
5574 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5575   switch (V.getOpcode()) {
5576   default: break;
5577   case ISD::Constant: {
5578     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5579     assert(CV != 0 && "Const value should be ConstSDNode.");
5580     const APInt &CVal = CV->getAPIntValue();
5581     APInt NewVal = CVal & Mask;
5582     if (NewVal != CVal)
5583       return DAG.getConstant(NewVal, V.getValueType());
5584     break;
5585   }
5586   case ISD::OR:
5587   case ISD::XOR:
5588     // If the LHS or RHS don't contribute bits to the or, drop them.
5589     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5590       return V.getOperand(1);
5591     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5592       return V.getOperand(0);
5593     break;
5594   case ISD::SRL:
5595     // Only look at single-use SRLs.
5596     if (!V.getNode()->hasOneUse())
5597       break;
5598     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5599       // See if we can recursively simplify the LHS.
5600       unsigned Amt = RHSC->getZExtValue();
5601
5602       // Watch out for shift count overflow though.
5603       if (Amt >= Mask.getBitWidth()) break;
5604       APInt NewMask = Mask << Amt;
5605       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5606       if (SimplifyLHS.getNode())
5607         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5608                            SimplifyLHS, V.getOperand(1));
5609     }
5610   }
5611   return SDValue();
5612 }
5613
5614 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5615 /// bits and then truncated to a narrower type and where N is a multiple
5616 /// of number of bits of the narrower type, transform it to a narrower load
5617 /// from address + N / num of bits of new type. If the result is to be
5618 /// extended, also fold the extension to form a extending load.
5619 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5620   unsigned Opc = N->getOpcode();
5621
5622   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5623   SDValue N0 = N->getOperand(0);
5624   EVT VT = N->getValueType(0);
5625   EVT ExtVT = VT;
5626
5627   // This transformation isn't valid for vector loads.
5628   if (VT.isVector())
5629     return SDValue();
5630
5631   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5632   // extended to VT.
5633   if (Opc == ISD::SIGN_EXTEND_INREG) {
5634     ExtType = ISD::SEXTLOAD;
5635     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5636   } else if (Opc == ISD::SRL) {
5637     // Another special-case: SRL is basically zero-extending a narrower value.
5638     ExtType = ISD::ZEXTLOAD;
5639     N0 = SDValue(N, 0);
5640     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5641     if (!N01) return SDValue();
5642     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5643                               VT.getSizeInBits() - N01->getZExtValue());
5644   }
5645   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5646     return SDValue();
5647
5648   unsigned EVTBits = ExtVT.getSizeInBits();
5649
5650   // Do not generate loads of non-round integer types since these can
5651   // be expensive (and would be wrong if the type is not byte sized).
5652   if (!ExtVT.isRound())
5653     return SDValue();
5654
5655   unsigned ShAmt = 0;
5656   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5657     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5658       ShAmt = N01->getZExtValue();
5659       // Is the shift amount a multiple of size of VT?
5660       if ((ShAmt & (EVTBits-1)) == 0) {
5661         N0 = N0.getOperand(0);
5662         // Is the load width a multiple of size of VT?
5663         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5664           return SDValue();
5665       }
5666
5667       // At this point, we must have a load or else we can't do the transform.
5668       if (!isa<LoadSDNode>(N0)) return SDValue();
5669
5670       // Because a SRL must be assumed to *need* to zero-extend the high bits
5671       // (as opposed to anyext the high bits), we can't combine the zextload
5672       // lowering of SRL and an sextload.
5673       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5674         return SDValue();
5675
5676       // If the shift amount is larger than the input type then we're not
5677       // accessing any of the loaded bytes.  If the load was a zextload/extload
5678       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5679       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5680         return SDValue();
5681     }
5682   }
5683
5684   // If the load is shifted left (and the result isn't shifted back right),
5685   // we can fold the truncate through the shift.
5686   unsigned ShLeftAmt = 0;
5687   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5688       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5689     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5690       ShLeftAmt = N01->getZExtValue();
5691       N0 = N0.getOperand(0);
5692     }
5693   }
5694
5695   // If we haven't found a load, we can't narrow it.  Don't transform one with
5696   // multiple uses, this would require adding a new load.
5697   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5698     return SDValue();
5699
5700   // Don't change the width of a volatile load.
5701   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5702   if (LN0->isVolatile())
5703     return SDValue();
5704
5705   // Verify that we are actually reducing a load width here.
5706   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5707     return SDValue();
5708
5709   // For the transform to be legal, the load must produce only two values
5710   // (the value loaded and the chain).  Don't transform a pre-increment
5711   // load, for example, which produces an extra value.  Otherwise the
5712   // transformation is not equivalent, and the downstream logic to replace
5713   // uses gets things wrong.
5714   if (LN0->getNumValues() > 2)
5715     return SDValue();
5716
5717   // If the load that we're shrinking is an extload and we're not just
5718   // discarding the extension we can't simply shrink the load. Bail.
5719   // TODO: It would be possible to merge the extensions in some cases.
5720   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5721       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5722     return SDValue();
5723
5724   EVT PtrType = N0.getOperand(1).getValueType();
5725
5726   if (PtrType == MVT::Untyped || PtrType.isExtended())
5727     // It's not possible to generate a constant of extended or untyped type.
5728     return SDValue();
5729
5730   // For big endian targets, we need to adjust the offset to the pointer to
5731   // load the correct bytes.
5732   if (TLI.isBigEndian()) {
5733     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5734     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5735     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5736   }
5737
5738   uint64_t PtrOff = ShAmt / 8;
5739   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5740   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5741                                PtrType, LN0->getBasePtr(),
5742                                DAG.getConstant(PtrOff, PtrType));
5743   AddToWorkList(NewPtr.getNode());
5744
5745   SDValue Load;
5746   if (ExtType == ISD::NON_EXTLOAD)
5747     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5748                         LN0->getPointerInfo().getWithOffset(PtrOff),
5749                         LN0->isVolatile(), LN0->isNonTemporal(),
5750                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5751   else
5752     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5753                           LN0->getPointerInfo().getWithOffset(PtrOff),
5754                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5755                           NewAlign, LN0->getTBAAInfo());
5756
5757   // Replace the old load's chain with the new load's chain.
5758   WorkListRemover DeadNodes(*this);
5759   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5760
5761   // Shift the result left, if we've swallowed a left shift.
5762   SDValue Result = Load;
5763   if (ShLeftAmt != 0) {
5764     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5765     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5766       ShImmTy = VT;
5767     // If the shift amount is as large as the result size (but, presumably,
5768     // no larger than the source) then the useful bits of the result are
5769     // zero; we can't simply return the shortened shift, because the result
5770     // of that operation is undefined.
5771     if (ShLeftAmt >= VT.getSizeInBits())
5772       Result = DAG.getConstant(0, VT);
5773     else
5774       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5775                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5776   }
5777
5778   // Return the new loaded value.
5779   return Result;
5780 }
5781
5782 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5783   SDValue N0 = N->getOperand(0);
5784   SDValue N1 = N->getOperand(1);
5785   EVT VT = N->getValueType(0);
5786   EVT EVT = cast<VTSDNode>(N1)->getVT();
5787   unsigned VTBits = VT.getScalarType().getSizeInBits();
5788   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5789
5790   // fold (sext_in_reg c1) -> c1
5791   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5792     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5793
5794   // If the input is already sign extended, just drop the extension.
5795   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5796     return N0;
5797
5798   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5799   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5800       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5801     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5802                        N0.getOperand(0), N1);
5803
5804   // fold (sext_in_reg (sext x)) -> (sext x)
5805   // fold (sext_in_reg (aext x)) -> (sext x)
5806   // if x is small enough.
5807   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5808     SDValue N00 = N0.getOperand(0);
5809     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5810         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5811       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5812   }
5813
5814   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5815   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5816     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5817
5818   // fold operands of sext_in_reg based on knowledge that the top bits are not
5819   // demanded.
5820   if (SimplifyDemandedBits(SDValue(N, 0)))
5821     return SDValue(N, 0);
5822
5823   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5824   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5825   SDValue NarrowLoad = ReduceLoadWidth(N);
5826   if (NarrowLoad.getNode())
5827     return NarrowLoad;
5828
5829   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5830   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5831   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5832   if (N0.getOpcode() == ISD::SRL) {
5833     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5834       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5835         // We can turn this into an SRA iff the input to the SRL is already sign
5836         // extended enough.
5837         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5838         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5839           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5840                              N0.getOperand(0), N0.getOperand(1));
5841       }
5842   }
5843
5844   // fold (sext_inreg (extload x)) -> (sextload x)
5845   if (ISD::isEXTLoad(N0.getNode()) &&
5846       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5847       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5848       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5849        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5850     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5851     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5852                                      LN0->getChain(),
5853                                      LN0->getBasePtr(), EVT,
5854                                      LN0->getMemOperand());
5855     CombineTo(N, ExtLoad);
5856     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5857     AddToWorkList(ExtLoad.getNode());
5858     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5859   }
5860   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5861   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5862       N0.hasOneUse() &&
5863       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5864       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5865        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5866     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5867     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5868                                      LN0->getChain(),
5869                                      LN0->getBasePtr(), EVT,
5870                                      LN0->getMemOperand());
5871     CombineTo(N, ExtLoad);
5872     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5873     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5874   }
5875
5876   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5877   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5878     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5879                                        N0.getOperand(1), false);
5880     if (BSwap.getNode() != 0)
5881       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5882                          BSwap, N1);
5883   }
5884
5885   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5886   // into a build_vector.
5887   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5888     SmallVector<SDValue, 8> Elts;
5889     unsigned NumElts = N0->getNumOperands();
5890     unsigned ShAmt = VTBits - EVTBits;
5891
5892     for (unsigned i = 0; i != NumElts; ++i) {
5893       SDValue Op = N0->getOperand(i);
5894       if (Op->getOpcode() == ISD::UNDEF) {
5895         Elts.push_back(Op);
5896         continue;
5897       }
5898
5899       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5900       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5901       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5902                                      Op.getValueType()));
5903     }
5904
5905     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5906   }
5907
5908   return SDValue();
5909 }
5910
5911 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5912   SDValue N0 = N->getOperand(0);
5913   EVT VT = N->getValueType(0);
5914   bool isLE = TLI.isLittleEndian();
5915
5916   // noop truncate
5917   if (N0.getValueType() == N->getValueType(0))
5918     return N0;
5919   // fold (truncate c1) -> c1
5920   if (isa<ConstantSDNode>(N0))
5921     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5922   // fold (truncate (truncate x)) -> (truncate x)
5923   if (N0.getOpcode() == ISD::TRUNCATE)
5924     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5925   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5926   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5927       N0.getOpcode() == ISD::SIGN_EXTEND ||
5928       N0.getOpcode() == ISD::ANY_EXTEND) {
5929     if (N0.getOperand(0).getValueType().bitsLT(VT))
5930       // if the source is smaller than the dest, we still need an extend
5931       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5932                          N0.getOperand(0));
5933     if (N0.getOperand(0).getValueType().bitsGT(VT))
5934       // if the source is larger than the dest, than we just need the truncate
5935       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5936     // if the source and dest are the same type, we can drop both the extend
5937     // and the truncate.
5938     return N0.getOperand(0);
5939   }
5940
5941   // Fold extract-and-trunc into a narrow extract. For example:
5942   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5943   //   i32 y = TRUNCATE(i64 x)
5944   //        -- becomes --
5945   //   v16i8 b = BITCAST (v2i64 val)
5946   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5947   //
5948   // Note: We only run this optimization after type legalization (which often
5949   // creates this pattern) and before operation legalization after which
5950   // we need to be more careful about the vector instructions that we generate.
5951   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5952       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5953
5954     EVT VecTy = N0.getOperand(0).getValueType();
5955     EVT ExTy = N0.getValueType();
5956     EVT TrTy = N->getValueType(0);
5957
5958     unsigned NumElem = VecTy.getVectorNumElements();
5959     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5960
5961     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5962     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5963
5964     SDValue EltNo = N0->getOperand(1);
5965     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5966       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5967       EVT IndexTy = TLI.getVectorIdxTy();
5968       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5969
5970       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5971                               NVT, N0.getOperand(0));
5972
5973       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5974                          SDLoc(N), TrTy, V,
5975                          DAG.getConstant(Index, IndexTy));
5976     }
5977   }
5978
5979   // Fold a series of buildvector, bitcast, and truncate if possible.
5980   // For example fold
5981   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5982   //   (2xi32 (buildvector x, y)).
5983   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5984       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5985       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5986       N0.getOperand(0).hasOneUse()) {
5987
5988     SDValue BuildVect = N0.getOperand(0);
5989     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5990     EVT TruncVecEltTy = VT.getVectorElementType();
5991
5992     // Check that the element types match.
5993     if (BuildVectEltTy == TruncVecEltTy) {
5994       // Now we only need to compute the offset of the truncated elements.
5995       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5996       unsigned TruncVecNumElts = VT.getVectorNumElements();
5997       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5998
5999       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6000              "Invalid number of elements");
6001
6002       SmallVector<SDValue, 8> Opnds;
6003       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6004         Opnds.push_back(BuildVect.getOperand(i));
6005
6006       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
6007                          Opnds.size());
6008     }
6009   }
6010
6011   // See if we can simplify the input to this truncate through knowledge that
6012   // only the low bits are being used.
6013   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6014   // Currently we only perform this optimization on scalars because vectors
6015   // may have different active low bits.
6016   if (!VT.isVector()) {
6017     SDValue Shorter =
6018       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6019                                                VT.getSizeInBits()));
6020     if (Shorter.getNode())
6021       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6022   }
6023   // fold (truncate (load x)) -> (smaller load x)
6024   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6025   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6026     SDValue Reduced = ReduceLoadWidth(N);
6027     if (Reduced.getNode())
6028       return Reduced;
6029     // Handle the case where the load remains an extending load even
6030     // after truncation.
6031     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6032       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6033       if (!LN0->isVolatile() &&
6034           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6035         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6036                                          VT, LN0->getChain(), LN0->getBasePtr(),
6037                                          LN0->getMemoryVT(),
6038                                          LN0->getMemOperand());
6039         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6040         return NewLoad;
6041       }
6042     }
6043   }
6044   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6045   // where ... are all 'undef'.
6046   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6047     SmallVector<EVT, 8> VTs;
6048     SDValue V;
6049     unsigned Idx = 0;
6050     unsigned NumDefs = 0;
6051
6052     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6053       SDValue X = N0.getOperand(i);
6054       if (X.getOpcode() != ISD::UNDEF) {
6055         V = X;
6056         Idx = i;
6057         NumDefs++;
6058       }
6059       // Stop if more than one members are non-undef.
6060       if (NumDefs > 1)
6061         break;
6062       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6063                                      VT.getVectorElementType(),
6064                                      X.getValueType().getVectorNumElements()));
6065     }
6066
6067     if (NumDefs == 0)
6068       return DAG.getUNDEF(VT);
6069
6070     if (NumDefs == 1) {
6071       assert(V.getNode() && "The single defined operand is empty!");
6072       SmallVector<SDValue, 8> Opnds;
6073       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6074         if (i != Idx) {
6075           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6076           continue;
6077         }
6078         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6079         AddToWorkList(NV.getNode());
6080         Opnds.push_back(NV);
6081       }
6082       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6083                          &Opnds[0], Opnds.size());
6084     }
6085   }
6086
6087   // Simplify the operands using demanded-bits information.
6088   if (!VT.isVector() &&
6089       SimplifyDemandedBits(SDValue(N, 0)))
6090     return SDValue(N, 0);
6091
6092   return SDValue();
6093 }
6094
6095 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6096   SDValue Elt = N->getOperand(i);
6097   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6098     return Elt.getNode();
6099   return Elt.getOperand(Elt.getResNo()).getNode();
6100 }
6101
6102 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6103 /// if load locations are consecutive.
6104 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6105   assert(N->getOpcode() == ISD::BUILD_PAIR);
6106
6107   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6108   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6109   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6110       LD1->getAddressSpace() != LD2->getAddressSpace())
6111     return SDValue();
6112   EVT LD1VT = LD1->getValueType(0);
6113
6114   if (ISD::isNON_EXTLoad(LD2) &&
6115       LD2->hasOneUse() &&
6116       // If both are volatile this would reduce the number of volatile loads.
6117       // If one is volatile it might be ok, but play conservative and bail out.
6118       !LD1->isVolatile() &&
6119       !LD2->isVolatile() &&
6120       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6121     unsigned Align = LD1->getAlignment();
6122     unsigned NewAlign = TLI.getDataLayout()->
6123       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6124
6125     if (NewAlign <= Align &&
6126         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6127       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6128                          LD1->getBasePtr(), LD1->getPointerInfo(),
6129                          false, false, false, Align);
6130   }
6131
6132   return SDValue();
6133 }
6134
6135 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6136   SDValue N0 = N->getOperand(0);
6137   EVT VT = N->getValueType(0);
6138
6139   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6140   // Only do this before legalize, since afterward the target may be depending
6141   // on the bitconvert.
6142   // First check to see if this is all constant.
6143   if (!LegalTypes &&
6144       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6145       VT.isVector()) {
6146     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6147
6148     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6149     assert(!DestEltVT.isVector() &&
6150            "Element type of vector ValueType must not be vector!");
6151     if (isSimple)
6152       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6153   }
6154
6155   // If the input is a constant, let getNode fold it.
6156   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6157     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6158     if (Res.getNode() != N) {
6159       if (!LegalOperations ||
6160           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6161         return Res;
6162
6163       // Folding it resulted in an illegal node, and it's too late to
6164       // do that. Clean up the old node and forego the transformation.
6165       // Ideally this won't happen very often, because instcombine
6166       // and the earlier dagcombine runs (where illegal nodes are
6167       // permitted) should have folded most of them already.
6168       DAG.DeleteNode(Res.getNode());
6169     }
6170   }
6171
6172   // (conv (conv x, t1), t2) -> (conv x, t2)
6173   if (N0.getOpcode() == ISD::BITCAST)
6174     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6175                        N0.getOperand(0));
6176
6177   // fold (conv (load x)) -> (load (conv*)x)
6178   // If the resultant load doesn't need a higher alignment than the original!
6179   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6180       // Do not change the width of a volatile load.
6181       !cast<LoadSDNode>(N0)->isVolatile() &&
6182       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6183       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6184     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6185     unsigned Align = TLI.getDataLayout()->
6186       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6187     unsigned OrigAlign = LN0->getAlignment();
6188
6189     if (Align <= OrigAlign) {
6190       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6191                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6192                                  LN0->isVolatile(), LN0->isNonTemporal(),
6193                                  LN0->isInvariant(), OrigAlign,
6194                                  LN0->getTBAAInfo());
6195       AddToWorkList(N);
6196       CombineTo(N0.getNode(),
6197                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6198                             N0.getValueType(), Load),
6199                 Load.getValue(1));
6200       return Load;
6201     }
6202   }
6203
6204   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6205   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6206   // This often reduces constant pool loads.
6207   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6208        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6209       N0.getNode()->hasOneUse() && VT.isInteger() &&
6210       !VT.isVector() && !N0.getValueType().isVector()) {
6211     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6212                                   N0.getOperand(0));
6213     AddToWorkList(NewConv.getNode());
6214
6215     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6216     if (N0.getOpcode() == ISD::FNEG)
6217       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6218                          NewConv, DAG.getConstant(SignBit, VT));
6219     assert(N0.getOpcode() == ISD::FABS);
6220     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6221                        NewConv, DAG.getConstant(~SignBit, VT));
6222   }
6223
6224   // fold (bitconvert (fcopysign cst, x)) ->
6225   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6226   // Note that we don't handle (copysign x, cst) because this can always be
6227   // folded to an fneg or fabs.
6228   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6229       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6230       VT.isInteger() && !VT.isVector()) {
6231     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6232     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6233     if (isTypeLegal(IntXVT)) {
6234       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6235                               IntXVT, N0.getOperand(1));
6236       AddToWorkList(X.getNode());
6237
6238       // If X has a different width than the result/lhs, sext it or truncate it.
6239       unsigned VTWidth = VT.getSizeInBits();
6240       if (OrigXWidth < VTWidth) {
6241         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6242         AddToWorkList(X.getNode());
6243       } else if (OrigXWidth > VTWidth) {
6244         // To get the sign bit in the right place, we have to shift it right
6245         // before truncating.
6246         X = DAG.getNode(ISD::SRL, SDLoc(X),
6247                         X.getValueType(), X,
6248                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6249         AddToWorkList(X.getNode());
6250         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6251         AddToWorkList(X.getNode());
6252       }
6253
6254       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6255       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6256                       X, DAG.getConstant(SignBit, VT));
6257       AddToWorkList(X.getNode());
6258
6259       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6260                                 VT, N0.getOperand(0));
6261       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6262                         Cst, DAG.getConstant(~SignBit, VT));
6263       AddToWorkList(Cst.getNode());
6264
6265       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6266     }
6267   }
6268
6269   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6270   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6271     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6272     if (CombineLD.getNode())
6273       return CombineLD;
6274   }
6275
6276   return SDValue();
6277 }
6278
6279 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6280   EVT VT = N->getValueType(0);
6281   return CombineConsecutiveLoads(N, VT);
6282 }
6283
6284 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6285 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6286 /// destination element value type.
6287 SDValue DAGCombiner::
6288 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6289   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6290
6291   // If this is already the right type, we're done.
6292   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6293
6294   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6295   unsigned DstBitSize = DstEltVT.getSizeInBits();
6296
6297   // If this is a conversion of N elements of one type to N elements of another
6298   // type, convert each element.  This handles FP<->INT cases.
6299   if (SrcBitSize == DstBitSize) {
6300     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6301                               BV->getValueType(0).getVectorNumElements());
6302
6303     // Due to the FP element handling below calling this routine recursively,
6304     // we can end up with a scalar-to-vector node here.
6305     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6306       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6307                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6308                                      DstEltVT, BV->getOperand(0)));
6309
6310     SmallVector<SDValue, 8> Ops;
6311     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6312       SDValue Op = BV->getOperand(i);
6313       // If the vector element type is not legal, the BUILD_VECTOR operands
6314       // are promoted and implicitly truncated.  Make that explicit here.
6315       if (Op.getValueType() != SrcEltVT)
6316         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6317       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6318                                 DstEltVT, Op));
6319       AddToWorkList(Ops.back().getNode());
6320     }
6321     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6322                        &Ops[0], Ops.size());
6323   }
6324
6325   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6326   // handle annoying details of growing/shrinking FP values, we convert them to
6327   // int first.
6328   if (SrcEltVT.isFloatingPoint()) {
6329     // Convert the input float vector to a int vector where the elements are the
6330     // same sizes.
6331     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6332     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6333     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6334     SrcEltVT = IntVT;
6335   }
6336
6337   // Now we know the input is an integer vector.  If the output is a FP type,
6338   // convert to integer first, then to FP of the right size.
6339   if (DstEltVT.isFloatingPoint()) {
6340     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6341     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6342     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6343
6344     // Next, convert to FP elements of the same size.
6345     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6346   }
6347
6348   // Okay, we know the src/dst types are both integers of differing types.
6349   // Handling growing first.
6350   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6351   if (SrcBitSize < DstBitSize) {
6352     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6353
6354     SmallVector<SDValue, 8> Ops;
6355     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6356          i += NumInputsPerOutput) {
6357       bool isLE = TLI.isLittleEndian();
6358       APInt NewBits = APInt(DstBitSize, 0);
6359       bool EltIsUndef = true;
6360       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6361         // Shift the previously computed bits over.
6362         NewBits <<= SrcBitSize;
6363         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6364         if (Op.getOpcode() == ISD::UNDEF) continue;
6365         EltIsUndef = false;
6366
6367         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6368                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6369       }
6370
6371       if (EltIsUndef)
6372         Ops.push_back(DAG.getUNDEF(DstEltVT));
6373       else
6374         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6375     }
6376
6377     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6378     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6379                        &Ops[0], Ops.size());
6380   }
6381
6382   // Finally, this must be the case where we are shrinking elements: each input
6383   // turns into multiple outputs.
6384   bool isS2V = ISD::isScalarToVector(BV);
6385   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6386   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6387                             NumOutputsPerInput*BV->getNumOperands());
6388   SmallVector<SDValue, 8> Ops;
6389
6390   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6391     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6392       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6393         Ops.push_back(DAG.getUNDEF(DstEltVT));
6394       continue;
6395     }
6396
6397     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6398                   getAPIntValue().zextOrTrunc(SrcBitSize);
6399
6400     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6401       APInt ThisVal = OpVal.trunc(DstBitSize);
6402       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6403       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6404         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6405         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6406                            Ops[0]);
6407       OpVal = OpVal.lshr(DstBitSize);
6408     }
6409
6410     // For big endian targets, swap the order of the pieces of each element.
6411     if (TLI.isBigEndian())
6412       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6413   }
6414
6415   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6416                      &Ops[0], Ops.size());
6417 }
6418
6419 SDValue DAGCombiner::visitFADD(SDNode *N) {
6420   SDValue N0 = N->getOperand(0);
6421   SDValue N1 = N->getOperand(1);
6422   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6423   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6424   EVT VT = N->getValueType(0);
6425
6426   // fold vector ops
6427   if (VT.isVector()) {
6428     SDValue FoldedVOp = SimplifyVBinOp(N);
6429     if (FoldedVOp.getNode()) return FoldedVOp;
6430   }
6431
6432   // fold (fadd c1, c2) -> c1 + c2
6433   if (N0CFP && N1CFP)
6434     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6435   // canonicalize constant to RHS
6436   if (N0CFP && !N1CFP)
6437     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6438   // fold (fadd A, 0) -> A
6439   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6440       N1CFP->getValueAPF().isZero())
6441     return N0;
6442   // fold (fadd A, (fneg B)) -> (fsub A, B)
6443   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6444     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6445     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6446                        GetNegatedExpression(N1, DAG, LegalOperations));
6447   // fold (fadd (fneg A), B) -> (fsub B, A)
6448   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6449     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6450     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6451                        GetNegatedExpression(N0, DAG, LegalOperations));
6452
6453   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6454   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6455       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6456       isa<ConstantFPSDNode>(N0.getOperand(1)))
6457     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6458                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6459                                    N0.getOperand(1), N1));
6460
6461   // No FP constant should be created after legalization as Instruction
6462   // Selection pass has hard time in dealing with FP constant.
6463   //
6464   // We don't need test this condition for transformation like following, as
6465   // the DAG being transformed implies it is legal to take FP constant as
6466   // operand.
6467   //
6468   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6469   //
6470   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6471
6472   // If allow, fold (fadd (fneg x), x) -> 0.0
6473   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6474       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6475     return DAG.getConstantFP(0.0, VT);
6476
6477     // If allow, fold (fadd x, (fneg x)) -> 0.0
6478   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6479       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6480     return DAG.getConstantFP(0.0, VT);
6481
6482   // In unsafe math mode, we can fold chains of FADD's of the same value
6483   // into multiplications.  This transform is not safe in general because
6484   // we are reducing the number of rounding steps.
6485   if (DAG.getTarget().Options.UnsafeFPMath &&
6486       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6487       !N0CFP && !N1CFP) {
6488     if (N0.getOpcode() == ISD::FMUL) {
6489       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6490       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6491
6492       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6493       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6494         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6495                                      SDValue(CFP00, 0),
6496                                      DAG.getConstantFP(1.0, VT));
6497         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6498                            N1, NewCFP);
6499       }
6500
6501       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6502       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6503         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6504                                      SDValue(CFP01, 0),
6505                                      DAG.getConstantFP(1.0, VT));
6506         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6507                            N1, NewCFP);
6508       }
6509
6510       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6511       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6512           N1.getOperand(0) == N1.getOperand(1) &&
6513           N0.getOperand(1) == N1.getOperand(0)) {
6514         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6515                                      SDValue(CFP00, 0),
6516                                      DAG.getConstantFP(2.0, VT));
6517         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6518                            N0.getOperand(1), NewCFP);
6519       }
6520
6521       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6522       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6523           N1.getOperand(0) == N1.getOperand(1) &&
6524           N0.getOperand(0) == N1.getOperand(0)) {
6525         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6526                                      SDValue(CFP01, 0),
6527                                      DAG.getConstantFP(2.0, VT));
6528         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6529                            N0.getOperand(0), NewCFP);
6530       }
6531     }
6532
6533     if (N1.getOpcode() == ISD::FMUL) {
6534       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6535       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6536
6537       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6538       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6539         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6540                                      SDValue(CFP10, 0),
6541                                      DAG.getConstantFP(1.0, VT));
6542         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6543                            N0, NewCFP);
6544       }
6545
6546       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6547       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6548         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6549                                      SDValue(CFP11, 0),
6550                                      DAG.getConstantFP(1.0, VT));
6551         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6552                            N0, NewCFP);
6553       }
6554
6555
6556       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6557       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6558           N0.getOperand(0) == N0.getOperand(1) &&
6559           N1.getOperand(1) == N0.getOperand(0)) {
6560         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6561                                      SDValue(CFP10, 0),
6562                                      DAG.getConstantFP(2.0, VT));
6563         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6564                            N1.getOperand(1), NewCFP);
6565       }
6566
6567       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6568       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6569           N0.getOperand(0) == N0.getOperand(1) &&
6570           N1.getOperand(0) == N0.getOperand(0)) {
6571         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6572                                      SDValue(CFP11, 0),
6573                                      DAG.getConstantFP(2.0, VT));
6574         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6575                            N1.getOperand(0), NewCFP);
6576       }
6577     }
6578
6579     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6580       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6581       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6582       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6583           (N0.getOperand(0) == N1))
6584         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6585                            N1, DAG.getConstantFP(3.0, VT));
6586     }
6587
6588     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6589       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6590       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6591       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6592           N1.getOperand(0) == N0)
6593         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6594                            N0, DAG.getConstantFP(3.0, VT));
6595     }
6596
6597     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6598     if (AllowNewFpConst &&
6599         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6600         N0.getOperand(0) == N0.getOperand(1) &&
6601         N1.getOperand(0) == N1.getOperand(1) &&
6602         N0.getOperand(0) == N1.getOperand(0))
6603       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6604                          N0.getOperand(0),
6605                          DAG.getConstantFP(4.0, VT));
6606   }
6607
6608   // FADD -> FMA combines:
6609   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6610        DAG.getTarget().Options.UnsafeFPMath) &&
6611       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6612       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6613
6614     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6615     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6616       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6617                          N0.getOperand(0), N0.getOperand(1), N1);
6618
6619     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6620     // Note: Commutes FADD operands.
6621     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6622       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6623                          N1.getOperand(0), N1.getOperand(1), N0);
6624   }
6625
6626   return SDValue();
6627 }
6628
6629 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6630   SDValue N0 = N->getOperand(0);
6631   SDValue N1 = N->getOperand(1);
6632   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6633   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6634   EVT VT = N->getValueType(0);
6635   SDLoc dl(N);
6636
6637   // fold vector ops
6638   if (VT.isVector()) {
6639     SDValue FoldedVOp = SimplifyVBinOp(N);
6640     if (FoldedVOp.getNode()) return FoldedVOp;
6641   }
6642
6643   // fold (fsub c1, c2) -> c1-c2
6644   if (N0CFP && N1CFP)
6645     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6646   // fold (fsub A, 0) -> A
6647   if (DAG.getTarget().Options.UnsafeFPMath &&
6648       N1CFP && N1CFP->getValueAPF().isZero())
6649     return N0;
6650   // fold (fsub 0, B) -> -B
6651   if (DAG.getTarget().Options.UnsafeFPMath &&
6652       N0CFP && N0CFP->getValueAPF().isZero()) {
6653     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6654       return GetNegatedExpression(N1, DAG, LegalOperations);
6655     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6656       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6657   }
6658   // fold (fsub A, (fneg B)) -> (fadd A, B)
6659   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6660     return DAG.getNode(ISD::FADD, dl, VT, N0,
6661                        GetNegatedExpression(N1, DAG, LegalOperations));
6662
6663   // If 'unsafe math' is enabled, fold
6664   //    (fsub x, x) -> 0.0 &
6665   //    (fsub x, (fadd x, y)) -> (fneg y) &
6666   //    (fsub x, (fadd y, x)) -> (fneg y)
6667   if (DAG.getTarget().Options.UnsafeFPMath) {
6668     if (N0 == N1)
6669       return DAG.getConstantFP(0.0f, VT);
6670
6671     if (N1.getOpcode() == ISD::FADD) {
6672       SDValue N10 = N1->getOperand(0);
6673       SDValue N11 = N1->getOperand(1);
6674
6675       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6676                                           &DAG.getTarget().Options))
6677         return GetNegatedExpression(N11, DAG, LegalOperations);
6678
6679       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6680                                           &DAG.getTarget().Options))
6681         return GetNegatedExpression(N10, DAG, LegalOperations);
6682     }
6683   }
6684
6685   // FSUB -> FMA combines:
6686   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6687        DAG.getTarget().Options.UnsafeFPMath) &&
6688       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6689       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6690
6691     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6692     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6693       return DAG.getNode(ISD::FMA, dl, VT,
6694                          N0.getOperand(0), N0.getOperand(1),
6695                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6696
6697     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6698     // Note: Commutes FSUB operands.
6699     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6700       return DAG.getNode(ISD::FMA, dl, VT,
6701                          DAG.getNode(ISD::FNEG, dl, VT,
6702                          N1.getOperand(0)),
6703                          N1.getOperand(1), N0);
6704
6705     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6706     if (N0.getOpcode() == ISD::FNEG &&
6707         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6708         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6709       SDValue N00 = N0.getOperand(0).getOperand(0);
6710       SDValue N01 = N0.getOperand(0).getOperand(1);
6711       return DAG.getNode(ISD::FMA, dl, VT,
6712                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6713                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6714     }
6715   }
6716
6717   return SDValue();
6718 }
6719
6720 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6721   SDValue N0 = N->getOperand(0);
6722   SDValue N1 = N->getOperand(1);
6723   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6724   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6725   EVT VT = N->getValueType(0);
6726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6727
6728   // fold vector ops
6729   if (VT.isVector()) {
6730     SDValue FoldedVOp = SimplifyVBinOp(N);
6731     if (FoldedVOp.getNode()) return FoldedVOp;
6732   }
6733
6734   // fold (fmul c1, c2) -> c1*c2
6735   if (N0CFP && N1CFP)
6736     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6737   // canonicalize constant to RHS
6738   if (N0CFP && !N1CFP)
6739     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6740   // fold (fmul A, 0) -> 0
6741   if (DAG.getTarget().Options.UnsafeFPMath &&
6742       N1CFP && N1CFP->getValueAPF().isZero())
6743     return N1;
6744   // fold (fmul A, 0) -> 0, vector edition.
6745   if (DAG.getTarget().Options.UnsafeFPMath &&
6746       ISD::isBuildVectorAllZeros(N1.getNode()))
6747     return N1;
6748   // fold (fmul A, 1.0) -> A
6749   if (N1CFP && N1CFP->isExactlyValue(1.0))
6750     return N0;
6751   // fold (fmul X, 2.0) -> (fadd X, X)
6752   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6753     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6754   // fold (fmul X, -1.0) -> (fneg X)
6755   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6756     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6757       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6758
6759   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6760   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6761                                        &DAG.getTarget().Options)) {
6762     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6763                                          &DAG.getTarget().Options)) {
6764       // Both can be negated for free, check to see if at least one is cheaper
6765       // negated.
6766       if (LHSNeg == 2 || RHSNeg == 2)
6767         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6768                            GetNegatedExpression(N0, DAG, LegalOperations),
6769                            GetNegatedExpression(N1, DAG, LegalOperations));
6770     }
6771   }
6772
6773   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6774   if (DAG.getTarget().Options.UnsafeFPMath &&
6775       N1CFP && N0.getOpcode() == ISD::FMUL &&
6776       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6777     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6778                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6779                                    N0.getOperand(1), N1));
6780
6781   return SDValue();
6782 }
6783
6784 SDValue DAGCombiner::visitFMA(SDNode *N) {
6785   SDValue N0 = N->getOperand(0);
6786   SDValue N1 = N->getOperand(1);
6787   SDValue N2 = N->getOperand(2);
6788   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6789   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6790   EVT VT = N->getValueType(0);
6791   SDLoc dl(N);
6792
6793   if (DAG.getTarget().Options.UnsafeFPMath) {
6794     if (N0CFP && N0CFP->isZero())
6795       return N2;
6796     if (N1CFP && N1CFP->isZero())
6797       return N2;
6798   }
6799   if (N0CFP && N0CFP->isExactlyValue(1.0))
6800     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6801   if (N1CFP && N1CFP->isExactlyValue(1.0))
6802     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6803
6804   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6805   if (N0CFP && !N1CFP)
6806     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6807
6808   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6809   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6810       N2.getOpcode() == ISD::FMUL &&
6811       N0 == N2.getOperand(0) &&
6812       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6813     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6814                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6815   }
6816
6817
6818   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6819   if (DAG.getTarget().Options.UnsafeFPMath &&
6820       N0.getOpcode() == ISD::FMUL && N1CFP &&
6821       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6822     return DAG.getNode(ISD::FMA, dl, VT,
6823                        N0.getOperand(0),
6824                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6825                        N2);
6826   }
6827
6828   // (fma x, 1, y) -> (fadd x, y)
6829   // (fma x, -1, y) -> (fadd (fneg x), y)
6830   if (N1CFP) {
6831     if (N1CFP->isExactlyValue(1.0))
6832       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6833
6834     if (N1CFP->isExactlyValue(-1.0) &&
6835         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6836       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6837       AddToWorkList(RHSNeg.getNode());
6838       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6839     }
6840   }
6841
6842   // (fma x, c, x) -> (fmul x, (c+1))
6843   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6844     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6845                        DAG.getNode(ISD::FADD, dl, VT,
6846                                    N1, DAG.getConstantFP(1.0, VT)));
6847
6848   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6849   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6850       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6851     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6852                        DAG.getNode(ISD::FADD, dl, VT,
6853                                    N1, DAG.getConstantFP(-1.0, VT)));
6854
6855
6856   return SDValue();
6857 }
6858
6859 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6860   SDValue N0 = N->getOperand(0);
6861   SDValue N1 = N->getOperand(1);
6862   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6863   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6864   EVT VT = N->getValueType(0);
6865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6866
6867   // fold vector ops
6868   if (VT.isVector()) {
6869     SDValue FoldedVOp = SimplifyVBinOp(N);
6870     if (FoldedVOp.getNode()) return FoldedVOp;
6871   }
6872
6873   // fold (fdiv c1, c2) -> c1/c2
6874   if (N0CFP && N1CFP)
6875     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6876
6877   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6878   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6879     // Compute the reciprocal 1.0 / c2.
6880     APFloat N1APF = N1CFP->getValueAPF();
6881     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6882     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6883     // Only do the transform if the reciprocal is a legal fp immediate that
6884     // isn't too nasty (eg NaN, denormal, ...).
6885     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6886         (!LegalOperations ||
6887          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6888          // backend)... we should handle this gracefully after Legalize.
6889          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6890          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6891          TLI.isFPImmLegal(Recip, VT)))
6892       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6893                          DAG.getConstantFP(Recip, VT));
6894   }
6895
6896   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6897   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6898                                        &DAG.getTarget().Options)) {
6899     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6900                                          &DAG.getTarget().Options)) {
6901       // Both can be negated for free, check to see if at least one is cheaper
6902       // negated.
6903       if (LHSNeg == 2 || RHSNeg == 2)
6904         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6905                            GetNegatedExpression(N0, DAG, LegalOperations),
6906                            GetNegatedExpression(N1, DAG, LegalOperations));
6907     }
6908   }
6909
6910   return SDValue();
6911 }
6912
6913 SDValue DAGCombiner::visitFREM(SDNode *N) {
6914   SDValue N0 = N->getOperand(0);
6915   SDValue N1 = N->getOperand(1);
6916   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6917   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6918   EVT VT = N->getValueType(0);
6919
6920   // fold (frem c1, c2) -> fmod(c1,c2)
6921   if (N0CFP && N1CFP)
6922     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6923
6924   return SDValue();
6925 }
6926
6927 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6928   SDValue N0 = N->getOperand(0);
6929   SDValue N1 = N->getOperand(1);
6930   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6931   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6932   EVT VT = N->getValueType(0);
6933
6934   if (N0CFP && N1CFP)  // Constant fold
6935     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6936
6937   if (N1CFP) {
6938     const APFloat& V = N1CFP->getValueAPF();
6939     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6940     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6941     if (!V.isNegative()) {
6942       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6943         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6944     } else {
6945       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6946         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6947                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6948     }
6949   }
6950
6951   // copysign(fabs(x), y) -> copysign(x, y)
6952   // copysign(fneg(x), y) -> copysign(x, y)
6953   // copysign(copysign(x,z), y) -> copysign(x, y)
6954   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6955       N0.getOpcode() == ISD::FCOPYSIGN)
6956     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6957                        N0.getOperand(0), N1);
6958
6959   // copysign(x, abs(y)) -> abs(x)
6960   if (N1.getOpcode() == ISD::FABS)
6961     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6962
6963   // copysign(x, copysign(y,z)) -> copysign(x, z)
6964   if (N1.getOpcode() == ISD::FCOPYSIGN)
6965     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6966                        N0, N1.getOperand(1));
6967
6968   // copysign(x, fp_extend(y)) -> copysign(x, y)
6969   // copysign(x, fp_round(y)) -> copysign(x, y)
6970   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6971     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6972                        N0, N1.getOperand(0));
6973
6974   return SDValue();
6975 }
6976
6977 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6978   SDValue N0 = N->getOperand(0);
6979   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6980   EVT VT = N->getValueType(0);
6981   EVT OpVT = N0.getValueType();
6982
6983   // fold (sint_to_fp c1) -> c1fp
6984   if (N0C &&
6985       // ...but only if the target supports immediate floating-point values
6986       (!LegalOperations ||
6987        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6988     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6989
6990   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6991   // but UINT_TO_FP is legal on this target, try to convert.
6992   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6993       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6994     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6995     if (DAG.SignBitIsZero(N0))
6996       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6997   }
6998
6999   // The next optimizations are desirable only if SELECT_CC can be lowered.
7000   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7001   // having to say they don't support SELECT_CC on every type the DAG knows
7002   // about, since there is no way to mark an opcode illegal at all value types
7003   // (See also visitSELECT)
7004   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7005     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7006     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7007         !VT.isVector() &&
7008         (!LegalOperations ||
7009          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7010       SDValue Ops[] =
7011         { N0.getOperand(0), N0.getOperand(1),
7012           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7013           N0.getOperand(2) };
7014       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7015     }
7016
7017     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7018     //      (select_cc x, y, 1.0, 0.0,, cc)
7019     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7020         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7021         (!LegalOperations ||
7022          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7023       SDValue Ops[] =
7024         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7025           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7026           N0.getOperand(0).getOperand(2) };
7027       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7028     }
7029   }
7030
7031   return SDValue();
7032 }
7033
7034 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7035   SDValue N0 = N->getOperand(0);
7036   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7037   EVT VT = N->getValueType(0);
7038   EVT OpVT = N0.getValueType();
7039
7040   // fold (uint_to_fp c1) -> c1fp
7041   if (N0C &&
7042       // ...but only if the target supports immediate floating-point values
7043       (!LegalOperations ||
7044        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7045     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7046
7047   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7048   // but SINT_TO_FP is legal on this target, try to convert.
7049   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7050       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7051     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7052     if (DAG.SignBitIsZero(N0))
7053       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7054   }
7055
7056   // The next optimizations are desirable only if SELECT_CC can be lowered.
7057   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7058   // having to say they don't support SELECT_CC on every type the DAG knows
7059   // about, since there is no way to mark an opcode illegal at all value types
7060   // (See also visitSELECT)
7061   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7062     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7063
7064     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7065         (!LegalOperations ||
7066          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7067       SDValue Ops[] =
7068         { N0.getOperand(0), N0.getOperand(1),
7069           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7070           N0.getOperand(2) };
7071       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7072     }
7073   }
7074
7075   return SDValue();
7076 }
7077
7078 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7079   SDValue N0 = N->getOperand(0);
7080   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7081   EVT VT = N->getValueType(0);
7082
7083   // fold (fp_to_sint c1fp) -> c1
7084   if (N0CFP)
7085     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7086
7087   return SDValue();
7088 }
7089
7090 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7091   SDValue N0 = N->getOperand(0);
7092   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7093   EVT VT = N->getValueType(0);
7094
7095   // fold (fp_to_uint c1fp) -> c1
7096   if (N0CFP)
7097     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7098
7099   return SDValue();
7100 }
7101
7102 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7103   SDValue N0 = N->getOperand(0);
7104   SDValue N1 = N->getOperand(1);
7105   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7106   EVT VT = N->getValueType(0);
7107
7108   // fold (fp_round c1fp) -> c1fp
7109   if (N0CFP)
7110     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7111
7112   // fold (fp_round (fp_extend x)) -> x
7113   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7114     return N0.getOperand(0);
7115
7116   // fold (fp_round (fp_round x)) -> (fp_round x)
7117   if (N0.getOpcode() == ISD::FP_ROUND) {
7118     // This is a value preserving truncation if both round's are.
7119     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7120                    N0.getNode()->getConstantOperandVal(1) == 1;
7121     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7122                        DAG.getIntPtrConstant(IsTrunc));
7123   }
7124
7125   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7126   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7127     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7128                               N0.getOperand(0), N1);
7129     AddToWorkList(Tmp.getNode());
7130     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7131                        Tmp, N0.getOperand(1));
7132   }
7133
7134   return SDValue();
7135 }
7136
7137 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7138   SDValue N0 = N->getOperand(0);
7139   EVT VT = N->getValueType(0);
7140   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7141   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7142
7143   // fold (fp_round_inreg c1fp) -> c1fp
7144   if (N0CFP && isTypeLegal(EVT)) {
7145     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7146     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7147   }
7148
7149   return SDValue();
7150 }
7151
7152 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7153   SDValue N0 = N->getOperand(0);
7154   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7155   EVT VT = N->getValueType(0);
7156
7157   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7158   if (N->hasOneUse() &&
7159       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7160     return SDValue();
7161
7162   // fold (fp_extend c1fp) -> c1fp
7163   if (N0CFP)
7164     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7165
7166   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7167   // value of X.
7168   if (N0.getOpcode() == ISD::FP_ROUND
7169       && N0.getNode()->getConstantOperandVal(1) == 1) {
7170     SDValue In = N0.getOperand(0);
7171     if (In.getValueType() == VT) return In;
7172     if (VT.bitsLT(In.getValueType()))
7173       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7174                          In, N0.getOperand(1));
7175     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7176   }
7177
7178   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7179   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7180       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7181        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7182     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7183     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7184                                      LN0->getChain(),
7185                                      LN0->getBasePtr(), N0.getValueType(),
7186                                      LN0->getMemOperand());
7187     CombineTo(N, ExtLoad);
7188     CombineTo(N0.getNode(),
7189               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7190                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7191               ExtLoad.getValue(1));
7192     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7193   }
7194
7195   return SDValue();
7196 }
7197
7198 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7199   SDValue N0 = N->getOperand(0);
7200   EVT VT = N->getValueType(0);
7201
7202   if (VT.isVector()) {
7203     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7204     if (FoldedVOp.getNode()) return FoldedVOp;
7205   }
7206
7207   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7208                          &DAG.getTarget().Options))
7209     return GetNegatedExpression(N0, DAG, LegalOperations);
7210
7211   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7212   // constant pool values.
7213   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7214       !VT.isVector() &&
7215       N0.getNode()->hasOneUse() &&
7216       N0.getOperand(0).getValueType().isInteger()) {
7217     SDValue Int = N0.getOperand(0);
7218     EVT IntVT = Int.getValueType();
7219     if (IntVT.isInteger() && !IntVT.isVector()) {
7220       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7221               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7222       AddToWorkList(Int.getNode());
7223       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7224                          VT, Int);
7225     }
7226   }
7227
7228   // (fneg (fmul c, x)) -> (fmul -c, x)
7229   if (N0.getOpcode() == ISD::FMUL) {
7230     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7231     if (CFP1)
7232       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7233                          N0.getOperand(0),
7234                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7235                                      N0.getOperand(1)));
7236   }
7237
7238   return SDValue();
7239 }
7240
7241 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7242   SDValue N0 = N->getOperand(0);
7243   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7244   EVT VT = N->getValueType(0);
7245
7246   // fold (fceil c1) -> fceil(c1)
7247   if (N0CFP)
7248     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7249
7250   return SDValue();
7251 }
7252
7253 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7254   SDValue N0 = N->getOperand(0);
7255   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7256   EVT VT = N->getValueType(0);
7257
7258   // fold (ftrunc c1) -> ftrunc(c1)
7259   if (N0CFP)
7260     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7261
7262   return SDValue();
7263 }
7264
7265 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7266   SDValue N0 = N->getOperand(0);
7267   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7268   EVT VT = N->getValueType(0);
7269
7270   // fold (ffloor c1) -> ffloor(c1)
7271   if (N0CFP)
7272     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7273
7274   return SDValue();
7275 }
7276
7277 SDValue DAGCombiner::visitFABS(SDNode *N) {
7278   SDValue N0 = N->getOperand(0);
7279   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7280   EVT VT = N->getValueType(0);
7281
7282   if (VT.isVector()) {
7283     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7284     if (FoldedVOp.getNode()) return FoldedVOp;
7285   }
7286
7287   // fold (fabs c1) -> fabs(c1)
7288   if (N0CFP)
7289     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7290   // fold (fabs (fabs x)) -> (fabs x)
7291   if (N0.getOpcode() == ISD::FABS)
7292     return N->getOperand(0);
7293   // fold (fabs (fneg x)) -> (fabs x)
7294   // fold (fabs (fcopysign x, y)) -> (fabs x)
7295   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7296     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7297
7298   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7299   // constant pool values.
7300   if (!TLI.isFAbsFree(VT) &&
7301       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7302       N0.getOperand(0).getValueType().isInteger() &&
7303       !N0.getOperand(0).getValueType().isVector()) {
7304     SDValue Int = N0.getOperand(0);
7305     EVT IntVT = Int.getValueType();
7306     if (IntVT.isInteger() && !IntVT.isVector()) {
7307       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7308              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7309       AddToWorkList(Int.getNode());
7310       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7311                          N->getValueType(0), Int);
7312     }
7313   }
7314
7315   return SDValue();
7316 }
7317
7318 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7319   SDValue Chain = N->getOperand(0);
7320   SDValue N1 = N->getOperand(1);
7321   SDValue N2 = N->getOperand(2);
7322
7323   // If N is a constant we could fold this into a fallthrough or unconditional
7324   // branch. However that doesn't happen very often in normal code, because
7325   // Instcombine/SimplifyCFG should have handled the available opportunities.
7326   // If we did this folding here, it would be necessary to update the
7327   // MachineBasicBlock CFG, which is awkward.
7328
7329   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7330   // on the target.
7331   if (N1.getOpcode() == ISD::SETCC &&
7332       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7333                                    N1.getOperand(0).getValueType())) {
7334     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7335                        Chain, N1.getOperand(2),
7336                        N1.getOperand(0), N1.getOperand(1), N2);
7337   }
7338
7339   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7340       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7341        (N1.getOperand(0).hasOneUse() &&
7342         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7343     SDNode *Trunc = 0;
7344     if (N1.getOpcode() == ISD::TRUNCATE) {
7345       // Look pass the truncate.
7346       Trunc = N1.getNode();
7347       N1 = N1.getOperand(0);
7348     }
7349
7350     // Match this pattern so that we can generate simpler code:
7351     //
7352     //   %a = ...
7353     //   %b = and i32 %a, 2
7354     //   %c = srl i32 %b, 1
7355     //   brcond i32 %c ...
7356     //
7357     // into
7358     //
7359     //   %a = ...
7360     //   %b = and i32 %a, 2
7361     //   %c = setcc eq %b, 0
7362     //   brcond %c ...
7363     //
7364     // This applies only when the AND constant value has one bit set and the
7365     // SRL constant is equal to the log2 of the AND constant. The back-end is
7366     // smart enough to convert the result into a TEST/JMP sequence.
7367     SDValue Op0 = N1.getOperand(0);
7368     SDValue Op1 = N1.getOperand(1);
7369
7370     if (Op0.getOpcode() == ISD::AND &&
7371         Op1.getOpcode() == ISD::Constant) {
7372       SDValue AndOp1 = Op0.getOperand(1);
7373
7374       if (AndOp1.getOpcode() == ISD::Constant) {
7375         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7376
7377         if (AndConst.isPowerOf2() &&
7378             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7379           SDValue SetCC =
7380             DAG.getSetCC(SDLoc(N),
7381                          getSetCCResultType(Op0.getValueType()),
7382                          Op0, DAG.getConstant(0, Op0.getValueType()),
7383                          ISD::SETNE);
7384
7385           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7386                                           MVT::Other, Chain, SetCC, N2);
7387           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7388           // will convert it back to (X & C1) >> C2.
7389           CombineTo(N, NewBRCond, false);
7390           // Truncate is dead.
7391           if (Trunc) {
7392             removeFromWorkList(Trunc);
7393             DAG.DeleteNode(Trunc);
7394           }
7395           // Replace the uses of SRL with SETCC
7396           WorkListRemover DeadNodes(*this);
7397           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7398           removeFromWorkList(N1.getNode());
7399           DAG.DeleteNode(N1.getNode());
7400           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7401         }
7402       }
7403     }
7404
7405     if (Trunc)
7406       // Restore N1 if the above transformation doesn't match.
7407       N1 = N->getOperand(1);
7408   }
7409
7410   // Transform br(xor(x, y)) -> br(x != y)
7411   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7412   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7413     SDNode *TheXor = N1.getNode();
7414     SDValue Op0 = TheXor->getOperand(0);
7415     SDValue Op1 = TheXor->getOperand(1);
7416     if (Op0.getOpcode() == Op1.getOpcode()) {
7417       // Avoid missing important xor optimizations.
7418       SDValue Tmp = visitXOR(TheXor);
7419       if (Tmp.getNode()) {
7420         if (Tmp.getNode() != TheXor) {
7421           DEBUG(dbgs() << "\nReplacing.8 ";
7422                 TheXor->dump(&DAG);
7423                 dbgs() << "\nWith: ";
7424                 Tmp.getNode()->dump(&DAG);
7425                 dbgs() << '\n');
7426           WorkListRemover DeadNodes(*this);
7427           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7428           removeFromWorkList(TheXor);
7429           DAG.DeleteNode(TheXor);
7430           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7431                              MVT::Other, Chain, Tmp, N2);
7432         }
7433
7434         // visitXOR has changed XOR's operands or replaced the XOR completely,
7435         // bail out.
7436         return SDValue(N, 0);
7437       }
7438     }
7439
7440     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7441       bool Equal = false;
7442       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7443         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7444             Op0.getOpcode() == ISD::XOR) {
7445           TheXor = Op0.getNode();
7446           Equal = true;
7447         }
7448
7449       EVT SetCCVT = N1.getValueType();
7450       if (LegalTypes)
7451         SetCCVT = getSetCCResultType(SetCCVT);
7452       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7453                                    SetCCVT,
7454                                    Op0, Op1,
7455                                    Equal ? ISD::SETEQ : ISD::SETNE);
7456       // Replace the uses of XOR with SETCC
7457       WorkListRemover DeadNodes(*this);
7458       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7459       removeFromWorkList(N1.getNode());
7460       DAG.DeleteNode(N1.getNode());
7461       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7462                          MVT::Other, Chain, SetCC, N2);
7463     }
7464   }
7465
7466   return SDValue();
7467 }
7468
7469 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7470 //
7471 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7472   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7473   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7474
7475   // If N is a constant we could fold this into a fallthrough or unconditional
7476   // branch. However that doesn't happen very often in normal code, because
7477   // Instcombine/SimplifyCFG should have handled the available opportunities.
7478   // If we did this folding here, it would be necessary to update the
7479   // MachineBasicBlock CFG, which is awkward.
7480
7481   // Use SimplifySetCC to simplify SETCC's.
7482   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7483                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7484                                false);
7485   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7486
7487   // fold to a simpler setcc
7488   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7489     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7490                        N->getOperand(0), Simp.getOperand(2),
7491                        Simp.getOperand(0), Simp.getOperand(1),
7492                        N->getOperand(4));
7493
7494   return SDValue();
7495 }
7496
7497 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7498 /// uses N as its base pointer and that N may be folded in the load / store
7499 /// addressing mode.
7500 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7501                                     SelectionDAG &DAG,
7502                                     const TargetLowering &TLI) {
7503   EVT VT;
7504   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7505     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7506       return false;
7507     VT = Use->getValueType(0);
7508   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7509     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7510       return false;
7511     VT = ST->getValue().getValueType();
7512   } else
7513     return false;
7514
7515   TargetLowering::AddrMode AM;
7516   if (N->getOpcode() == ISD::ADD) {
7517     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7518     if (Offset)
7519       // [reg +/- imm]
7520       AM.BaseOffs = Offset->getSExtValue();
7521     else
7522       // [reg +/- reg]
7523       AM.Scale = 1;
7524   } else if (N->getOpcode() == ISD::SUB) {
7525     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7526     if (Offset)
7527       // [reg +/- imm]
7528       AM.BaseOffs = -Offset->getSExtValue();
7529     else
7530       // [reg +/- reg]
7531       AM.Scale = 1;
7532   } else
7533     return false;
7534
7535   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7536 }
7537
7538 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7539 /// pre-indexed load / store when the base pointer is an add or subtract
7540 /// and it has other uses besides the load / store. After the
7541 /// transformation, the new indexed load / store has effectively folded
7542 /// the add / subtract in and all of its other uses are redirected to the
7543 /// new load / store.
7544 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7545   if (Level < AfterLegalizeDAG)
7546     return false;
7547
7548   bool isLoad = true;
7549   SDValue Ptr;
7550   EVT VT;
7551   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7552     if (LD->isIndexed())
7553       return false;
7554     VT = LD->getMemoryVT();
7555     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7556         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7557       return false;
7558     Ptr = LD->getBasePtr();
7559   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7560     if (ST->isIndexed())
7561       return false;
7562     VT = ST->getMemoryVT();
7563     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7564         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7565       return false;
7566     Ptr = ST->getBasePtr();
7567     isLoad = false;
7568   } else {
7569     return false;
7570   }
7571
7572   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7573   // out.  There is no reason to make this a preinc/predec.
7574   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7575       Ptr.getNode()->hasOneUse())
7576     return false;
7577
7578   // Ask the target to do addressing mode selection.
7579   SDValue BasePtr;
7580   SDValue Offset;
7581   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7582   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7583     return false;
7584
7585   // Backends without true r+i pre-indexed forms may need to pass a
7586   // constant base with a variable offset so that constant coercion
7587   // will work with the patterns in canonical form.
7588   bool Swapped = false;
7589   if (isa<ConstantSDNode>(BasePtr)) {
7590     std::swap(BasePtr, Offset);
7591     Swapped = true;
7592   }
7593
7594   // Don't create a indexed load / store with zero offset.
7595   if (isa<ConstantSDNode>(Offset) &&
7596       cast<ConstantSDNode>(Offset)->isNullValue())
7597     return false;
7598
7599   // Try turning it into a pre-indexed load / store except when:
7600   // 1) The new base ptr is a frame index.
7601   // 2) If N is a store and the new base ptr is either the same as or is a
7602   //    predecessor of the value being stored.
7603   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7604   //    that would create a cycle.
7605   // 4) All uses are load / store ops that use it as old base ptr.
7606
7607   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7608   // (plus the implicit offset) to a register to preinc anyway.
7609   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7610     return false;
7611
7612   // Check #2.
7613   if (!isLoad) {
7614     SDValue Val = cast<StoreSDNode>(N)->getValue();
7615     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7616       return false;
7617   }
7618
7619   // If the offset is a constant, there may be other adds of constants that
7620   // can be folded with this one. We should do this to avoid having to keep
7621   // a copy of the original base pointer.
7622   SmallVector<SDNode *, 16> OtherUses;
7623   if (isa<ConstantSDNode>(Offset))
7624     for (SDNode *Use : BasePtr.getNode()->uses()) {
7625       if (Use == Ptr.getNode())
7626         continue;
7627
7628       if (Use->isPredecessorOf(N))
7629         continue;
7630
7631       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7632         OtherUses.clear();
7633         break;
7634       }
7635
7636       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7637       if (Op1.getNode() == BasePtr.getNode())
7638         std::swap(Op0, Op1);
7639       assert(Op0.getNode() == BasePtr.getNode() &&
7640              "Use of ADD/SUB but not an operand");
7641
7642       if (!isa<ConstantSDNode>(Op1)) {
7643         OtherUses.clear();
7644         break;
7645       }
7646
7647       // FIXME: In some cases, we can be smarter about this.
7648       if (Op1.getValueType() != Offset.getValueType()) {
7649         OtherUses.clear();
7650         break;
7651       }
7652
7653       OtherUses.push_back(Use);
7654     }
7655
7656   if (Swapped)
7657     std::swap(BasePtr, Offset);
7658
7659   // Now check for #3 and #4.
7660   bool RealUse = false;
7661
7662   // Caches for hasPredecessorHelper
7663   SmallPtrSet<const SDNode *, 32> Visited;
7664   SmallVector<const SDNode *, 16> Worklist;
7665
7666   for (SDNode *Use : Ptr.getNode()->uses()) {
7667     if (Use == N)
7668       continue;
7669     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7670       return false;
7671
7672     // If Ptr may be folded in addressing mode of other use, then it's
7673     // not profitable to do this transformation.
7674     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7675       RealUse = true;
7676   }
7677
7678   if (!RealUse)
7679     return false;
7680
7681   SDValue Result;
7682   if (isLoad)
7683     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7684                                 BasePtr, Offset, AM);
7685   else
7686     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7687                                  BasePtr, Offset, AM);
7688   ++PreIndexedNodes;
7689   ++NodesCombined;
7690   DEBUG(dbgs() << "\nReplacing.4 ";
7691         N->dump(&DAG);
7692         dbgs() << "\nWith: ";
7693         Result.getNode()->dump(&DAG);
7694         dbgs() << '\n');
7695   WorkListRemover DeadNodes(*this);
7696   if (isLoad) {
7697     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7698     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7699   } else {
7700     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7701   }
7702
7703   // Finally, since the node is now dead, remove it from the graph.
7704   DAG.DeleteNode(N);
7705
7706   if (Swapped)
7707     std::swap(BasePtr, Offset);
7708
7709   // Replace other uses of BasePtr that can be updated to use Ptr
7710   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7711     unsigned OffsetIdx = 1;
7712     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7713       OffsetIdx = 0;
7714     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7715            BasePtr.getNode() && "Expected BasePtr operand");
7716
7717     // We need to replace ptr0 in the following expression:
7718     //   x0 * offset0 + y0 * ptr0 = t0
7719     // knowing that
7720     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7721     //
7722     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7723     // indexed load/store and the expresion that needs to be re-written.
7724     //
7725     // Therefore, we have:
7726     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7727
7728     ConstantSDNode *CN =
7729       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7730     int X0, X1, Y0, Y1;
7731     APInt Offset0 = CN->getAPIntValue();
7732     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7733
7734     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7735     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7736     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7737     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7738
7739     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7740
7741     APInt CNV = Offset0;
7742     if (X0 < 0) CNV = -CNV;
7743     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7744     else CNV = CNV - Offset1;
7745
7746     // We can now generate the new expression.
7747     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7748     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7749
7750     SDValue NewUse = DAG.getNode(Opcode,
7751                                  SDLoc(OtherUses[i]),
7752                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7753     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7754     removeFromWorkList(OtherUses[i]);
7755     DAG.DeleteNode(OtherUses[i]);
7756   }
7757
7758   // Replace the uses of Ptr with uses of the updated base value.
7759   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7760   removeFromWorkList(Ptr.getNode());
7761   DAG.DeleteNode(Ptr.getNode());
7762
7763   return true;
7764 }
7765
7766 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7767 /// add / sub of the base pointer node into a post-indexed load / store.
7768 /// The transformation folded the add / subtract into the new indexed
7769 /// load / store effectively and all of its uses are redirected to the
7770 /// new load / store.
7771 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7772   if (Level < AfterLegalizeDAG)
7773     return false;
7774
7775   bool isLoad = true;
7776   SDValue Ptr;
7777   EVT VT;
7778   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7779     if (LD->isIndexed())
7780       return false;
7781     VT = LD->getMemoryVT();
7782     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7783         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7784       return false;
7785     Ptr = LD->getBasePtr();
7786   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7787     if (ST->isIndexed())
7788       return false;
7789     VT = ST->getMemoryVT();
7790     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7791         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7792       return false;
7793     Ptr = ST->getBasePtr();
7794     isLoad = false;
7795   } else {
7796     return false;
7797   }
7798
7799   if (Ptr.getNode()->hasOneUse())
7800     return false;
7801
7802   for (SDNode *Op : Ptr.getNode()->uses()) {
7803     if (Op == N ||
7804         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7805       continue;
7806
7807     SDValue BasePtr;
7808     SDValue Offset;
7809     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7810     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7811       // Don't create a indexed load / store with zero offset.
7812       if (isa<ConstantSDNode>(Offset) &&
7813           cast<ConstantSDNode>(Offset)->isNullValue())
7814         continue;
7815
7816       // Try turning it into a post-indexed load / store except when
7817       // 1) All uses are load / store ops that use it as base ptr (and
7818       //    it may be folded as addressing mmode).
7819       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7820       //    nor a successor of N. Otherwise, if Op is folded that would
7821       //    create a cycle.
7822
7823       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7824         continue;
7825
7826       // Check for #1.
7827       bool TryNext = false;
7828       for (SDNode *Use : BasePtr.getNode()->uses()) {
7829         if (Use == Ptr.getNode())
7830           continue;
7831
7832         // If all the uses are load / store addresses, then don't do the
7833         // transformation.
7834         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7835           bool RealUse = false;
7836           for (SDNode *UseUse : Use->uses()) {
7837             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7838               RealUse = true;
7839           }
7840
7841           if (!RealUse) {
7842             TryNext = true;
7843             break;
7844           }
7845         }
7846       }
7847
7848       if (TryNext)
7849         continue;
7850
7851       // Check for #2
7852       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7853         SDValue Result = isLoad
7854           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7855                                BasePtr, Offset, AM)
7856           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7857                                 BasePtr, Offset, AM);
7858         ++PostIndexedNodes;
7859         ++NodesCombined;
7860         DEBUG(dbgs() << "\nReplacing.5 ";
7861               N->dump(&DAG);
7862               dbgs() << "\nWith: ";
7863               Result.getNode()->dump(&DAG);
7864               dbgs() << '\n');
7865         WorkListRemover DeadNodes(*this);
7866         if (isLoad) {
7867           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7868           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7869         } else {
7870           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7871         }
7872
7873         // Finally, since the node is now dead, remove it from the graph.
7874         DAG.DeleteNode(N);
7875
7876         // Replace the uses of Use with uses of the updated base value.
7877         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7878                                       Result.getValue(isLoad ? 1 : 0));
7879         removeFromWorkList(Op);
7880         DAG.DeleteNode(Op);
7881         return true;
7882       }
7883     }
7884   }
7885
7886   return false;
7887 }
7888
7889 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7890   LoadSDNode *LD  = cast<LoadSDNode>(N);
7891   SDValue Chain = LD->getChain();
7892   SDValue Ptr   = LD->getBasePtr();
7893
7894   // If load is not volatile and there are no uses of the loaded value (and
7895   // the updated indexed value in case of indexed loads), change uses of the
7896   // chain value into uses of the chain input (i.e. delete the dead load).
7897   if (!LD->isVolatile()) {
7898     if (N->getValueType(1) == MVT::Other) {
7899       // Unindexed loads.
7900       if (!N->hasAnyUseOfValue(0)) {
7901         // It's not safe to use the two value CombineTo variant here. e.g.
7902         // v1, chain2 = load chain1, loc
7903         // v2, chain3 = load chain2, loc
7904         // v3         = add v2, c
7905         // Now we replace use of chain2 with chain1.  This makes the second load
7906         // isomorphic to the one we are deleting, and thus makes this load live.
7907         DEBUG(dbgs() << "\nReplacing.6 ";
7908               N->dump(&DAG);
7909               dbgs() << "\nWith chain: ";
7910               Chain.getNode()->dump(&DAG);
7911               dbgs() << "\n");
7912         WorkListRemover DeadNodes(*this);
7913         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7914
7915         if (N->use_empty()) {
7916           removeFromWorkList(N);
7917           DAG.DeleteNode(N);
7918         }
7919
7920         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7921       }
7922     } else {
7923       // Indexed loads.
7924       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7925       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7926         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7927         DEBUG(dbgs() << "\nReplacing.7 ";
7928               N->dump(&DAG);
7929               dbgs() << "\nWith: ";
7930               Undef.getNode()->dump(&DAG);
7931               dbgs() << " and 2 other values\n");
7932         WorkListRemover DeadNodes(*this);
7933         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7934         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7935                                       DAG.getUNDEF(N->getValueType(1)));
7936         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7937         removeFromWorkList(N);
7938         DAG.DeleteNode(N);
7939         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7940       }
7941     }
7942   }
7943
7944   // If this load is directly stored, replace the load value with the stored
7945   // value.
7946   // TODO: Handle store large -> read small portion.
7947   // TODO: Handle TRUNCSTORE/LOADEXT
7948   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7949     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7950       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7951       if (PrevST->getBasePtr() == Ptr &&
7952           PrevST->getValue().getValueType() == N->getValueType(0))
7953       return CombineTo(N, Chain.getOperand(1), Chain);
7954     }
7955   }
7956
7957   // Try to infer better alignment information than the load already has.
7958   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7959     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7960       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7961         SDValue NewLoad =
7962                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7963                               LD->getValueType(0),
7964                               Chain, Ptr, LD->getPointerInfo(),
7965                               LD->getMemoryVT(),
7966                               LD->isVolatile(), LD->isNonTemporal(), Align,
7967                               LD->getTBAAInfo());
7968         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7969       }
7970     }
7971   }
7972
7973   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7974     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7975 #ifndef NDEBUG
7976   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7977       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7978     UseAA = false;
7979 #endif
7980   if (UseAA && LD->isUnindexed()) {
7981     // Walk up chain skipping non-aliasing memory nodes.
7982     SDValue BetterChain = FindBetterChain(N, Chain);
7983
7984     // If there is a better chain.
7985     if (Chain != BetterChain) {
7986       SDValue ReplLoad;
7987
7988       // Replace the chain to void dependency.
7989       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7990         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7991                                BetterChain, Ptr, LD->getMemOperand());
7992       } else {
7993         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7994                                   LD->getValueType(0),
7995                                   BetterChain, Ptr, LD->getMemoryVT(),
7996                                   LD->getMemOperand());
7997       }
7998
7999       // Create token factor to keep old chain connected.
8000       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8001                                   MVT::Other, Chain, ReplLoad.getValue(1));
8002
8003       // Make sure the new and old chains are cleaned up.
8004       AddToWorkList(Token.getNode());
8005
8006       // Replace uses with load result and token factor. Don't add users
8007       // to work list.
8008       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8009     }
8010   }
8011
8012   // Try transforming N to an indexed load.
8013   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8014     return SDValue(N, 0);
8015
8016   // Try to slice up N to more direct loads if the slices are mapped to
8017   // different register banks or pairing can take place.
8018   if (SliceUpLoad(N))
8019     return SDValue(N, 0);
8020
8021   return SDValue();
8022 }
8023
8024 namespace {
8025 /// \brief Helper structure used to slice a load in smaller loads.
8026 /// Basically a slice is obtained from the following sequence:
8027 /// Origin = load Ty1, Base
8028 /// Shift = srl Ty1 Origin, CstTy Amount
8029 /// Inst = trunc Shift to Ty2
8030 ///
8031 /// Then, it will be rewriten into:
8032 /// Slice = load SliceTy, Base + SliceOffset
8033 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8034 ///
8035 /// SliceTy is deduced from the number of bits that are actually used to
8036 /// build Inst.
8037 struct LoadedSlice {
8038   /// \brief Helper structure used to compute the cost of a slice.
8039   struct Cost {
8040     /// Are we optimizing for code size.
8041     bool ForCodeSize;
8042     /// Various cost.
8043     unsigned Loads;
8044     unsigned Truncates;
8045     unsigned CrossRegisterBanksCopies;
8046     unsigned ZExts;
8047     unsigned Shift;
8048
8049     Cost(bool ForCodeSize = false)
8050         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8051           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8052
8053     /// \brief Get the cost of one isolated slice.
8054     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8055         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8056           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8057       EVT TruncType = LS.Inst->getValueType(0);
8058       EVT LoadedType = LS.getLoadedType();
8059       if (TruncType != LoadedType &&
8060           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8061         ZExts = 1;
8062     }
8063
8064     /// \brief Account for slicing gain in the current cost.
8065     /// Slicing provide a few gains like removing a shift or a
8066     /// truncate. This method allows to grow the cost of the original
8067     /// load with the gain from this slice.
8068     void addSliceGain(const LoadedSlice &LS) {
8069       // Each slice saves a truncate.
8070       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8071       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8072                               LS.Inst->getOperand(0).getValueType()))
8073         ++Truncates;
8074       // If there is a shift amount, this slice gets rid of it.
8075       if (LS.Shift)
8076         ++Shift;
8077       // If this slice can merge a cross register bank copy, account for it.
8078       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8079         ++CrossRegisterBanksCopies;
8080     }
8081
8082     Cost &operator+=(const Cost &RHS) {
8083       Loads += RHS.Loads;
8084       Truncates += RHS.Truncates;
8085       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8086       ZExts += RHS.ZExts;
8087       Shift += RHS.Shift;
8088       return *this;
8089     }
8090
8091     bool operator==(const Cost &RHS) const {
8092       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8093              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8094              ZExts == RHS.ZExts && Shift == RHS.Shift;
8095     }
8096
8097     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8098
8099     bool operator<(const Cost &RHS) const {
8100       // Assume cross register banks copies are as expensive as loads.
8101       // FIXME: Do we want some more target hooks?
8102       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8103       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8104       // Unless we are optimizing for code size, consider the
8105       // expensive operation first.
8106       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8107         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8108       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8109              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8110     }
8111
8112     bool operator>(const Cost &RHS) const { return RHS < *this; }
8113
8114     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8115
8116     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8117   };
8118   // The last instruction that represent the slice. This should be a
8119   // truncate instruction.
8120   SDNode *Inst;
8121   // The original load instruction.
8122   LoadSDNode *Origin;
8123   // The right shift amount in bits from the original load.
8124   unsigned Shift;
8125   // The DAG from which Origin came from.
8126   // This is used to get some contextual information about legal types, etc.
8127   SelectionDAG *DAG;
8128
8129   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8130               unsigned Shift = 0, SelectionDAG *DAG = NULL)
8131       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8132
8133   LoadedSlice(const LoadedSlice &LS)
8134       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8135
8136   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8137   /// \return Result is \p BitWidth and has used bits set to 1 and
8138   ///         not used bits set to 0.
8139   APInt getUsedBits() const {
8140     // Reproduce the trunc(lshr) sequence:
8141     // - Start from the truncated value.
8142     // - Zero extend to the desired bit width.
8143     // - Shift left.
8144     assert(Origin && "No original load to compare against.");
8145     unsigned BitWidth = Origin->getValueSizeInBits(0);
8146     assert(Inst && "This slice is not bound to an instruction");
8147     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8148            "Extracted slice is bigger than the whole type!");
8149     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8150     UsedBits.setAllBits();
8151     UsedBits = UsedBits.zext(BitWidth);
8152     UsedBits <<= Shift;
8153     return UsedBits;
8154   }
8155
8156   /// \brief Get the size of the slice to be loaded in bytes.
8157   unsigned getLoadedSize() const {
8158     unsigned SliceSize = getUsedBits().countPopulation();
8159     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8160     return SliceSize / 8;
8161   }
8162
8163   /// \brief Get the type that will be loaded for this slice.
8164   /// Note: This may not be the final type for the slice.
8165   EVT getLoadedType() const {
8166     assert(DAG && "Missing context");
8167     LLVMContext &Ctxt = *DAG->getContext();
8168     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8169   }
8170
8171   /// \brief Get the alignment of the load used for this slice.
8172   unsigned getAlignment() const {
8173     unsigned Alignment = Origin->getAlignment();
8174     unsigned Offset = getOffsetFromBase();
8175     if (Offset != 0)
8176       Alignment = MinAlign(Alignment, Alignment + Offset);
8177     return Alignment;
8178   }
8179
8180   /// \brief Check if this slice can be rewritten with legal operations.
8181   bool isLegal() const {
8182     // An invalid slice is not legal.
8183     if (!Origin || !Inst || !DAG)
8184       return false;
8185
8186     // Offsets are for indexed load only, we do not handle that.
8187     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8188       return false;
8189
8190     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8191
8192     // Check that the type is legal.
8193     EVT SliceType = getLoadedType();
8194     if (!TLI.isTypeLegal(SliceType))
8195       return false;
8196
8197     // Check that the load is legal for this type.
8198     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8199       return false;
8200
8201     // Check that the offset can be computed.
8202     // 1. Check its type.
8203     EVT PtrType = Origin->getBasePtr().getValueType();
8204     if (PtrType == MVT::Untyped || PtrType.isExtended())
8205       return false;
8206
8207     // 2. Check that it fits in the immediate.
8208     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8209       return false;
8210
8211     // 3. Check that the computation is legal.
8212     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8213       return false;
8214
8215     // Check that the zext is legal if it needs one.
8216     EVT TruncateType = Inst->getValueType(0);
8217     if (TruncateType != SliceType &&
8218         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8219       return false;
8220
8221     return true;
8222   }
8223
8224   /// \brief Get the offset in bytes of this slice in the original chunk of
8225   /// bits.
8226   /// \pre DAG != NULL.
8227   uint64_t getOffsetFromBase() const {
8228     assert(DAG && "Missing context.");
8229     bool IsBigEndian =
8230         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8231     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8232     uint64_t Offset = Shift / 8;
8233     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8234     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8235            "The size of the original loaded type is not a multiple of a"
8236            " byte.");
8237     // If Offset is bigger than TySizeInBytes, it means we are loading all
8238     // zeros. This should have been optimized before in the process.
8239     assert(TySizeInBytes > Offset &&
8240            "Invalid shift amount for given loaded size");
8241     if (IsBigEndian)
8242       Offset = TySizeInBytes - Offset - getLoadedSize();
8243     return Offset;
8244   }
8245
8246   /// \brief Generate the sequence of instructions to load the slice
8247   /// represented by this object and redirect the uses of this slice to
8248   /// this new sequence of instructions.
8249   /// \pre this->Inst && this->Origin are valid Instructions and this
8250   /// object passed the legal check: LoadedSlice::isLegal returned true.
8251   /// \return The last instruction of the sequence used to load the slice.
8252   SDValue loadSlice() const {
8253     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8254     const SDValue &OldBaseAddr = Origin->getBasePtr();
8255     SDValue BaseAddr = OldBaseAddr;
8256     // Get the offset in that chunk of bytes w.r.t. the endianess.
8257     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8258     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8259     if (Offset) {
8260       // BaseAddr = BaseAddr + Offset.
8261       EVT ArithType = BaseAddr.getValueType();
8262       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8263                               DAG->getConstant(Offset, ArithType));
8264     }
8265
8266     // Create the type of the loaded slice according to its size.
8267     EVT SliceType = getLoadedType();
8268
8269     // Create the load for the slice.
8270     SDValue LastInst = DAG->getLoad(
8271         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8272         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8273         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8274     // If the final type is not the same as the loaded type, this means that
8275     // we have to pad with zero. Create a zero extend for that.
8276     EVT FinalType = Inst->getValueType(0);
8277     if (SliceType != FinalType)
8278       LastInst =
8279           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8280     return LastInst;
8281   }
8282
8283   /// \brief Check if this slice can be merged with an expensive cross register
8284   /// bank copy. E.g.,
8285   /// i = load i32
8286   /// f = bitcast i32 i to float
8287   bool canMergeExpensiveCrossRegisterBankCopy() const {
8288     if (!Inst || !Inst->hasOneUse())
8289       return false;
8290     SDNode *Use = *Inst->use_begin();
8291     if (Use->getOpcode() != ISD::BITCAST)
8292       return false;
8293     assert(DAG && "Missing context");
8294     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8295     EVT ResVT = Use->getValueType(0);
8296     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8297     const TargetRegisterClass *ArgRC =
8298         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8299     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8300       return false;
8301
8302     // At this point, we know that we perform a cross-register-bank copy.
8303     // Check if it is expensive.
8304     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8305     // Assume bitcasts are cheap, unless both register classes do not
8306     // explicitly share a common sub class.
8307     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8308       return false;
8309
8310     // Check if it will be merged with the load.
8311     // 1. Check the alignment constraint.
8312     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8313         ResVT.getTypeForEVT(*DAG->getContext()));
8314
8315     if (RequiredAlignment > getAlignment())
8316       return false;
8317
8318     // 2. Check that the load is a legal operation for that type.
8319     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8320       return false;
8321
8322     // 3. Check that we do not have a zext in the way.
8323     if (Inst->getValueType(0) != getLoadedType())
8324       return false;
8325
8326     return true;
8327   }
8328 };
8329 }
8330
8331 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8332 /// \p UsedBits looks like 0..0 1..1 0..0.
8333 static bool areUsedBitsDense(const APInt &UsedBits) {
8334   // If all the bits are one, this is dense!
8335   if (UsedBits.isAllOnesValue())
8336     return true;
8337
8338   // Get rid of the unused bits on the right.
8339   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8340   // Get rid of the unused bits on the left.
8341   if (NarrowedUsedBits.countLeadingZeros())
8342     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8343   // Check that the chunk of bits is completely used.
8344   return NarrowedUsedBits.isAllOnesValue();
8345 }
8346
8347 /// \brief Check whether or not \p First and \p Second are next to each other
8348 /// in memory. This means that there is no hole between the bits loaded
8349 /// by \p First and the bits loaded by \p Second.
8350 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8351                                      const LoadedSlice &Second) {
8352   assert(First.Origin == Second.Origin && First.Origin &&
8353          "Unable to match different memory origins.");
8354   APInt UsedBits = First.getUsedBits();
8355   assert((UsedBits & Second.getUsedBits()) == 0 &&
8356          "Slices are not supposed to overlap.");
8357   UsedBits |= Second.getUsedBits();
8358   return areUsedBitsDense(UsedBits);
8359 }
8360
8361 /// \brief Adjust the \p GlobalLSCost according to the target
8362 /// paring capabilities and the layout of the slices.
8363 /// \pre \p GlobalLSCost should account for at least as many loads as
8364 /// there is in the slices in \p LoadedSlices.
8365 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8366                                  LoadedSlice::Cost &GlobalLSCost) {
8367   unsigned NumberOfSlices = LoadedSlices.size();
8368   // If there is less than 2 elements, no pairing is possible.
8369   if (NumberOfSlices < 2)
8370     return;
8371
8372   // Sort the slices so that elements that are likely to be next to each
8373   // other in memory are next to each other in the list.
8374   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8375             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8376     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8377     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8378   });
8379   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8380   // First (resp. Second) is the first (resp. Second) potentially candidate
8381   // to be placed in a paired load.
8382   const LoadedSlice *First = NULL;
8383   const LoadedSlice *Second = NULL;
8384   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8385                 // Set the beginning of the pair.
8386                                                            First = Second) {
8387
8388     Second = &LoadedSlices[CurrSlice];
8389
8390     // If First is NULL, it means we start a new pair.
8391     // Get to the next slice.
8392     if (!First)
8393       continue;
8394
8395     EVT LoadedType = First->getLoadedType();
8396
8397     // If the types of the slices are different, we cannot pair them.
8398     if (LoadedType != Second->getLoadedType())
8399       continue;
8400
8401     // Check if the target supplies paired loads for this type.
8402     unsigned RequiredAlignment = 0;
8403     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8404       // move to the next pair, this type is hopeless.
8405       Second = NULL;
8406       continue;
8407     }
8408     // Check if we meet the alignment requirement.
8409     if (RequiredAlignment > First->getAlignment())
8410       continue;
8411
8412     // Check that both loads are next to each other in memory.
8413     if (!areSlicesNextToEachOther(*First, *Second))
8414       continue;
8415
8416     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8417     --GlobalLSCost.Loads;
8418     // Move to the next pair.
8419     Second = NULL;
8420   }
8421 }
8422
8423 /// \brief Check the profitability of all involved LoadedSlice.
8424 /// Currently, it is considered profitable if there is exactly two
8425 /// involved slices (1) which are (2) next to each other in memory, and
8426 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8427 ///
8428 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8429 /// the elements themselves.
8430 ///
8431 /// FIXME: When the cost model will be mature enough, we can relax
8432 /// constraints (1) and (2).
8433 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8434                                 const APInt &UsedBits, bool ForCodeSize) {
8435   unsigned NumberOfSlices = LoadedSlices.size();
8436   if (StressLoadSlicing)
8437     return NumberOfSlices > 1;
8438
8439   // Check (1).
8440   if (NumberOfSlices != 2)
8441     return false;
8442
8443   // Check (2).
8444   if (!areUsedBitsDense(UsedBits))
8445     return false;
8446
8447   // Check (3).
8448   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8449   // The original code has one big load.
8450   OrigCost.Loads = 1;
8451   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8452     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8453     // Accumulate the cost of all the slices.
8454     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8455     GlobalSlicingCost += SliceCost;
8456
8457     // Account as cost in the original configuration the gain obtained
8458     // with the current slices.
8459     OrigCost.addSliceGain(LS);
8460   }
8461
8462   // If the target supports paired load, adjust the cost accordingly.
8463   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8464   return OrigCost > GlobalSlicingCost;
8465 }
8466
8467 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8468 /// operations, split it in the various pieces being extracted.
8469 ///
8470 /// This sort of thing is introduced by SROA.
8471 /// This slicing takes care not to insert overlapping loads.
8472 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8473 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8474   if (Level < AfterLegalizeDAG)
8475     return false;
8476
8477   LoadSDNode *LD = cast<LoadSDNode>(N);
8478   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8479       !LD->getValueType(0).isInteger())
8480     return false;
8481
8482   // Keep track of already used bits to detect overlapping values.
8483   // In that case, we will just abort the transformation.
8484   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8485
8486   SmallVector<LoadedSlice, 4> LoadedSlices;
8487
8488   // Check if this load is used as several smaller chunks of bits.
8489   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8490   // of computation for each trunc.
8491   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8492        UI != UIEnd; ++UI) {
8493     // Skip the uses of the chain.
8494     if (UI.getUse().getResNo() != 0)
8495       continue;
8496
8497     SDNode *User = *UI;
8498     unsigned Shift = 0;
8499
8500     // Check if this is a trunc(lshr).
8501     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8502         isa<ConstantSDNode>(User->getOperand(1))) {
8503       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8504       User = *User->use_begin();
8505     }
8506
8507     // At this point, User is a Truncate, iff we encountered, trunc or
8508     // trunc(lshr).
8509     if (User->getOpcode() != ISD::TRUNCATE)
8510       return false;
8511
8512     // The width of the type must be a power of 2 and greater than 8-bits.
8513     // Otherwise the load cannot be represented in LLVM IR.
8514     // Moreover, if we shifted with a non-8-bits multiple, the slice
8515     // will be across several bytes. We do not support that.
8516     unsigned Width = User->getValueSizeInBits(0);
8517     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8518       return 0;
8519
8520     // Build the slice for this chain of computations.
8521     LoadedSlice LS(User, LD, Shift, &DAG);
8522     APInt CurrentUsedBits = LS.getUsedBits();
8523
8524     // Check if this slice overlaps with another.
8525     if ((CurrentUsedBits & UsedBits) != 0)
8526       return false;
8527     // Update the bits used globally.
8528     UsedBits |= CurrentUsedBits;
8529
8530     // Check if the new slice would be legal.
8531     if (!LS.isLegal())
8532       return false;
8533
8534     // Record the slice.
8535     LoadedSlices.push_back(LS);
8536   }
8537
8538   // Abort slicing if it does not seem to be profitable.
8539   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8540     return false;
8541
8542   ++SlicedLoads;
8543
8544   // Rewrite each chain to use an independent load.
8545   // By construction, each chain can be represented by a unique load.
8546
8547   // Prepare the argument for the new token factor for all the slices.
8548   SmallVector<SDValue, 8> ArgChains;
8549   for (SmallVectorImpl<LoadedSlice>::const_iterator
8550            LSIt = LoadedSlices.begin(),
8551            LSItEnd = LoadedSlices.end();
8552        LSIt != LSItEnd; ++LSIt) {
8553     SDValue SliceInst = LSIt->loadSlice();
8554     CombineTo(LSIt->Inst, SliceInst, true);
8555     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8556       SliceInst = SliceInst.getOperand(0);
8557     assert(SliceInst->getOpcode() == ISD::LOAD &&
8558            "It takes more than a zext to get to the loaded slice!!");
8559     ArgChains.push_back(SliceInst.getValue(1));
8560   }
8561
8562   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8563                               &ArgChains[0], ArgChains.size());
8564   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8565   return true;
8566 }
8567
8568 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8569 /// load is having specific bytes cleared out.  If so, return the byte size
8570 /// being masked out and the shift amount.
8571 static std::pair<unsigned, unsigned>
8572 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8573   std::pair<unsigned, unsigned> Result(0, 0);
8574
8575   // Check for the structure we're looking for.
8576   if (V->getOpcode() != ISD::AND ||
8577       !isa<ConstantSDNode>(V->getOperand(1)) ||
8578       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8579     return Result;
8580
8581   // Check the chain and pointer.
8582   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8583   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8584
8585   // The store should be chained directly to the load or be an operand of a
8586   // tokenfactor.
8587   if (LD == Chain.getNode())
8588     ; // ok.
8589   else if (Chain->getOpcode() != ISD::TokenFactor)
8590     return Result; // Fail.
8591   else {
8592     bool isOk = false;
8593     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8594       if (Chain->getOperand(i).getNode() == LD) {
8595         isOk = true;
8596         break;
8597       }
8598     if (!isOk) return Result;
8599   }
8600
8601   // This only handles simple types.
8602   if (V.getValueType() != MVT::i16 &&
8603       V.getValueType() != MVT::i32 &&
8604       V.getValueType() != MVT::i64)
8605     return Result;
8606
8607   // Check the constant mask.  Invert it so that the bits being masked out are
8608   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8609   // follow the sign bit for uniformity.
8610   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8611   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8612   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8613   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8614   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8615   if (NotMaskLZ == 64) return Result;  // All zero mask.
8616
8617   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8618   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8619     return Result;
8620
8621   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8622   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8623     NotMaskLZ -= 64-V.getValueSizeInBits();
8624
8625   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8626   switch (MaskedBytes) {
8627   case 1:
8628   case 2:
8629   case 4: break;
8630   default: return Result; // All one mask, or 5-byte mask.
8631   }
8632
8633   // Verify that the first bit starts at a multiple of mask so that the access
8634   // is aligned the same as the access width.
8635   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8636
8637   Result.first = MaskedBytes;
8638   Result.second = NotMaskTZ/8;
8639   return Result;
8640 }
8641
8642
8643 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8644 /// provides a value as specified by MaskInfo.  If so, replace the specified
8645 /// store with a narrower store of truncated IVal.
8646 static SDNode *
8647 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8648                                 SDValue IVal, StoreSDNode *St,
8649                                 DAGCombiner *DC) {
8650   unsigned NumBytes = MaskInfo.first;
8651   unsigned ByteShift = MaskInfo.second;
8652   SelectionDAG &DAG = DC->getDAG();
8653
8654   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8655   // that uses this.  If not, this is not a replacement.
8656   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8657                                   ByteShift*8, (ByteShift+NumBytes)*8);
8658   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8659
8660   // Check that it is legal on the target to do this.  It is legal if the new
8661   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8662   // legalization.
8663   MVT VT = MVT::getIntegerVT(NumBytes*8);
8664   if (!DC->isTypeLegal(VT))
8665     return 0;
8666
8667   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8668   // shifted by ByteShift and truncated down to NumBytes.
8669   if (ByteShift)
8670     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8671                        DAG.getConstant(ByteShift*8,
8672                                     DC->getShiftAmountTy(IVal.getValueType())));
8673
8674   // Figure out the offset for the store and the alignment of the access.
8675   unsigned StOffset;
8676   unsigned NewAlign = St->getAlignment();
8677
8678   if (DAG.getTargetLoweringInfo().isLittleEndian())
8679     StOffset = ByteShift;
8680   else
8681     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8682
8683   SDValue Ptr = St->getBasePtr();
8684   if (StOffset) {
8685     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8686                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8687     NewAlign = MinAlign(NewAlign, StOffset);
8688   }
8689
8690   // Truncate down to the new size.
8691   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8692
8693   ++OpsNarrowed;
8694   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8695                       St->getPointerInfo().getWithOffset(StOffset),
8696                       false, false, NewAlign).getNode();
8697 }
8698
8699
8700 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8701 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8702 /// of the loaded bits, try narrowing the load and store if it would end up
8703 /// being a win for performance or code size.
8704 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8705   StoreSDNode *ST  = cast<StoreSDNode>(N);
8706   if (ST->isVolatile())
8707     return SDValue();
8708
8709   SDValue Chain = ST->getChain();
8710   SDValue Value = ST->getValue();
8711   SDValue Ptr   = ST->getBasePtr();
8712   EVT VT = Value.getValueType();
8713
8714   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8715     return SDValue();
8716
8717   unsigned Opc = Value.getOpcode();
8718
8719   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8720   // is a byte mask indicating a consecutive number of bytes, check to see if
8721   // Y is known to provide just those bytes.  If so, we try to replace the
8722   // load + replace + store sequence with a single (narrower) store, which makes
8723   // the load dead.
8724   if (Opc == ISD::OR) {
8725     std::pair<unsigned, unsigned> MaskedLoad;
8726     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8727     if (MaskedLoad.first)
8728       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8729                                                   Value.getOperand(1), ST,this))
8730         return SDValue(NewST, 0);
8731
8732     // Or is commutative, so try swapping X and Y.
8733     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8734     if (MaskedLoad.first)
8735       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8736                                                   Value.getOperand(0), ST,this))
8737         return SDValue(NewST, 0);
8738   }
8739
8740   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8741       Value.getOperand(1).getOpcode() != ISD::Constant)
8742     return SDValue();
8743
8744   SDValue N0 = Value.getOperand(0);
8745   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8746       Chain == SDValue(N0.getNode(), 1)) {
8747     LoadSDNode *LD = cast<LoadSDNode>(N0);
8748     if (LD->getBasePtr() != Ptr ||
8749         LD->getPointerInfo().getAddrSpace() !=
8750         ST->getPointerInfo().getAddrSpace())
8751       return SDValue();
8752
8753     // Find the type to narrow it the load / op / store to.
8754     SDValue N1 = Value.getOperand(1);
8755     unsigned BitWidth = N1.getValueSizeInBits();
8756     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8757     if (Opc == ISD::AND)
8758       Imm ^= APInt::getAllOnesValue(BitWidth);
8759     if (Imm == 0 || Imm.isAllOnesValue())
8760       return SDValue();
8761     unsigned ShAmt = Imm.countTrailingZeros();
8762     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8763     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8764     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8765     while (NewBW < BitWidth &&
8766            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8767              TLI.isNarrowingProfitable(VT, NewVT))) {
8768       NewBW = NextPowerOf2(NewBW);
8769       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8770     }
8771     if (NewBW >= BitWidth)
8772       return SDValue();
8773
8774     // If the lsb changed does not start at the type bitwidth boundary,
8775     // start at the previous one.
8776     if (ShAmt % NewBW)
8777       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8778     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8779                                    std::min(BitWidth, ShAmt + NewBW));
8780     if ((Imm & Mask) == Imm) {
8781       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8782       if (Opc == ISD::AND)
8783         NewImm ^= APInt::getAllOnesValue(NewBW);
8784       uint64_t PtrOff = ShAmt / 8;
8785       // For big endian targets, we need to adjust the offset to the pointer to
8786       // load the correct bytes.
8787       if (TLI.isBigEndian())
8788         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8789
8790       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8791       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8792       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8793         return SDValue();
8794
8795       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8796                                    Ptr.getValueType(), Ptr,
8797                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8798       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8799                                   LD->getChain(), NewPtr,
8800                                   LD->getPointerInfo().getWithOffset(PtrOff),
8801                                   LD->isVolatile(), LD->isNonTemporal(),
8802                                   LD->isInvariant(), NewAlign,
8803                                   LD->getTBAAInfo());
8804       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8805                                    DAG.getConstant(NewImm, NewVT));
8806       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8807                                    NewVal, NewPtr,
8808                                    ST->getPointerInfo().getWithOffset(PtrOff),
8809                                    false, false, NewAlign);
8810
8811       AddToWorkList(NewPtr.getNode());
8812       AddToWorkList(NewLD.getNode());
8813       AddToWorkList(NewVal.getNode());
8814       WorkListRemover DeadNodes(*this);
8815       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8816       ++OpsNarrowed;
8817       return NewST;
8818     }
8819   }
8820
8821   return SDValue();
8822 }
8823
8824 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8825 /// if the load value isn't used by any other operations, then consider
8826 /// transforming the pair to integer load / store operations if the target
8827 /// deems the transformation profitable.
8828 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8829   StoreSDNode *ST  = cast<StoreSDNode>(N);
8830   SDValue Chain = ST->getChain();
8831   SDValue Value = ST->getValue();
8832   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8833       Value.hasOneUse() &&
8834       Chain == SDValue(Value.getNode(), 1)) {
8835     LoadSDNode *LD = cast<LoadSDNode>(Value);
8836     EVT VT = LD->getMemoryVT();
8837     if (!VT.isFloatingPoint() ||
8838         VT != ST->getMemoryVT() ||
8839         LD->isNonTemporal() ||
8840         ST->isNonTemporal() ||
8841         LD->getPointerInfo().getAddrSpace() != 0 ||
8842         ST->getPointerInfo().getAddrSpace() != 0)
8843       return SDValue();
8844
8845     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8846     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8847         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8848         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8849         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8850       return SDValue();
8851
8852     unsigned LDAlign = LD->getAlignment();
8853     unsigned STAlign = ST->getAlignment();
8854     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8855     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8856     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8857       return SDValue();
8858
8859     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8860                                 LD->getChain(), LD->getBasePtr(),
8861                                 LD->getPointerInfo(),
8862                                 false, false, false, LDAlign);
8863
8864     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8865                                  NewLD, ST->getBasePtr(),
8866                                  ST->getPointerInfo(),
8867                                  false, false, STAlign);
8868
8869     AddToWorkList(NewLD.getNode());
8870     AddToWorkList(NewST.getNode());
8871     WorkListRemover DeadNodes(*this);
8872     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8873     ++LdStFP2Int;
8874     return NewST;
8875   }
8876
8877   return SDValue();
8878 }
8879
8880 /// Helper struct to parse and store a memory address as base + index + offset.
8881 /// We ignore sign extensions when it is safe to do so.
8882 /// The following two expressions are not equivalent. To differentiate we need
8883 /// to store whether there was a sign extension involved in the index
8884 /// computation.
8885 ///  (load (i64 add (i64 copyfromreg %c)
8886 ///                 (i64 signextend (add (i8 load %index)
8887 ///                                      (i8 1))))
8888 /// vs
8889 ///
8890 /// (load (i64 add (i64 copyfromreg %c)
8891 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8892 ///                                         (i32 1)))))
8893 struct BaseIndexOffset {
8894   SDValue Base;
8895   SDValue Index;
8896   int64_t Offset;
8897   bool IsIndexSignExt;
8898
8899   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8900
8901   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8902                   bool IsIndexSignExt) :
8903     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8904
8905   bool equalBaseIndex(const BaseIndexOffset &Other) {
8906     return Other.Base == Base && Other.Index == Index &&
8907       Other.IsIndexSignExt == IsIndexSignExt;
8908   }
8909
8910   /// Parses tree in Ptr for base, index, offset addresses.
8911   static BaseIndexOffset match(SDValue Ptr) {
8912     bool IsIndexSignExt = false;
8913
8914     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8915     // instruction, then it could be just the BASE or everything else we don't
8916     // know how to handle. Just use Ptr as BASE and give up.
8917     if (Ptr->getOpcode() != ISD::ADD)
8918       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8919
8920     // We know that we have at least an ADD instruction. Try to pattern match
8921     // the simple case of BASE + OFFSET.
8922     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8923       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8924       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8925                               IsIndexSignExt);
8926     }
8927
8928     // Inside a loop the current BASE pointer is calculated using an ADD and a
8929     // MUL instruction. In this case Ptr is the actual BASE pointer.
8930     // (i64 add (i64 %array_ptr)
8931     //          (i64 mul (i64 %induction_var)
8932     //                   (i64 %element_size)))
8933     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8934       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8935
8936     // Look at Base + Index + Offset cases.
8937     SDValue Base = Ptr->getOperand(0);
8938     SDValue IndexOffset = Ptr->getOperand(1);
8939
8940     // Skip signextends.
8941     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8942       IndexOffset = IndexOffset->getOperand(0);
8943       IsIndexSignExt = true;
8944     }
8945
8946     // Either the case of Base + Index (no offset) or something else.
8947     if (IndexOffset->getOpcode() != ISD::ADD)
8948       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8949
8950     // Now we have the case of Base + Index + offset.
8951     SDValue Index = IndexOffset->getOperand(0);
8952     SDValue Offset = IndexOffset->getOperand(1);
8953
8954     if (!isa<ConstantSDNode>(Offset))
8955       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8956
8957     // Ignore signextends.
8958     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8959       Index = Index->getOperand(0);
8960       IsIndexSignExt = true;
8961     } else IsIndexSignExt = false;
8962
8963     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8964     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8965   }
8966 };
8967
8968 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8969 /// is located in a sequence of memory operations connected by a chain.
8970 struct MemOpLink {
8971   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8972     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8973   // Ptr to the mem node.
8974   LSBaseSDNode *MemNode;
8975   // Offset from the base ptr.
8976   int64_t OffsetFromBase;
8977   // What is the sequence number of this mem node.
8978   // Lowest mem operand in the DAG starts at zero.
8979   unsigned SequenceNum;
8980 };
8981
8982 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8983   EVT MemVT = St->getMemoryVT();
8984   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8985   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8986     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8987
8988   // Don't merge vectors into wider inputs.
8989   if (MemVT.isVector() || !MemVT.isSimple())
8990     return false;
8991
8992   // Perform an early exit check. Do not bother looking at stored values that
8993   // are not constants or loads.
8994   SDValue StoredVal = St->getValue();
8995   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8996   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8997       !IsLoadSrc)
8998     return false;
8999
9000   // Only look at ends of store sequences.
9001   SDValue Chain = SDValue(St, 1);
9002   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9003     return false;
9004
9005   // This holds the base pointer, index, and the offset in bytes from the base
9006   // pointer.
9007   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9008
9009   // We must have a base and an offset.
9010   if (!BasePtr.Base.getNode())
9011     return false;
9012
9013   // Do not handle stores to undef base pointers.
9014   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9015     return false;
9016
9017   // Save the LoadSDNodes that we find in the chain.
9018   // We need to make sure that these nodes do not interfere with
9019   // any of the store nodes.
9020   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9021
9022   // Save the StoreSDNodes that we find in the chain.
9023   SmallVector<MemOpLink, 8> StoreNodes;
9024
9025   // Walk up the chain and look for nodes with offsets from the same
9026   // base pointer. Stop when reaching an instruction with a different kind
9027   // or instruction which has a different base pointer.
9028   unsigned Seq = 0;
9029   StoreSDNode *Index = St;
9030   while (Index) {
9031     // If the chain has more than one use, then we can't reorder the mem ops.
9032     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9033       break;
9034
9035     // Find the base pointer and offset for this memory node.
9036     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9037
9038     // Check that the base pointer is the same as the original one.
9039     if (!Ptr.equalBaseIndex(BasePtr))
9040       break;
9041
9042     // Check that the alignment is the same.
9043     if (Index->getAlignment() != St->getAlignment())
9044       break;
9045
9046     // The memory operands must not be volatile.
9047     if (Index->isVolatile() || Index->isIndexed())
9048       break;
9049
9050     // No truncation.
9051     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9052       if (St->isTruncatingStore())
9053         break;
9054
9055     // The stored memory type must be the same.
9056     if (Index->getMemoryVT() != MemVT)
9057       break;
9058
9059     // We do not allow unaligned stores because we want to prevent overriding
9060     // stores.
9061     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9062       break;
9063
9064     // We found a potential memory operand to merge.
9065     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9066
9067     // Find the next memory operand in the chain. If the next operand in the
9068     // chain is a store then move up and continue the scan with the next
9069     // memory operand. If the next operand is a load save it and use alias
9070     // information to check if it interferes with anything.
9071     SDNode *NextInChain = Index->getChain().getNode();
9072     while (1) {
9073       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9074         // We found a store node. Use it for the next iteration.
9075         Index = STn;
9076         break;
9077       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9078         if (Ldn->isVolatile()) {
9079           Index = NULL;
9080           break;
9081         }
9082
9083         // Save the load node for later. Continue the scan.
9084         AliasLoadNodes.push_back(Ldn);
9085         NextInChain = Ldn->getChain().getNode();
9086         continue;
9087       } else {
9088         Index = NULL;
9089         break;
9090       }
9091     }
9092   }
9093
9094   // Check if there is anything to merge.
9095   if (StoreNodes.size() < 2)
9096     return false;
9097
9098   // Sort the memory operands according to their distance from the base pointer.
9099   std::sort(StoreNodes.begin(), StoreNodes.end(),
9100             [](MemOpLink LHS, MemOpLink RHS) {
9101     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9102            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9103             LHS.SequenceNum > RHS.SequenceNum);
9104   });
9105
9106   // Scan the memory operations on the chain and find the first non-consecutive
9107   // store memory address.
9108   unsigned LastConsecutiveStore = 0;
9109   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9110   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9111
9112     // Check that the addresses are consecutive starting from the second
9113     // element in the list of stores.
9114     if (i > 0) {
9115       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9116       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9117         break;
9118     }
9119
9120     bool Alias = false;
9121     // Check if this store interferes with any of the loads that we found.
9122     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9123       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9124         Alias = true;
9125         break;
9126       }
9127     // We found a load that alias with this store. Stop the sequence.
9128     if (Alias)
9129       break;
9130
9131     // Mark this node as useful.
9132     LastConsecutiveStore = i;
9133   }
9134
9135   // The node with the lowest store address.
9136   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9137
9138   // Store the constants into memory as one consecutive store.
9139   if (!IsLoadSrc) {
9140     unsigned LastLegalType = 0;
9141     unsigned LastLegalVectorType = 0;
9142     bool NonZero = false;
9143     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9144       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9145       SDValue StoredVal = St->getValue();
9146
9147       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9148         NonZero |= !C->isNullValue();
9149       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9150         NonZero |= !C->getConstantFPValue()->isNullValue();
9151       } else {
9152         // Non-constant.
9153         break;
9154       }
9155
9156       // Find a legal type for the constant store.
9157       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9158       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9159       if (TLI.isTypeLegal(StoreTy))
9160         LastLegalType = i+1;
9161       // Or check whether a truncstore is legal.
9162       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9163                TargetLowering::TypePromoteInteger) {
9164         EVT LegalizedStoredValueTy =
9165           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9166         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9167           LastLegalType = i+1;
9168       }
9169
9170       // Find a legal type for the vector store.
9171       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9172       if (TLI.isTypeLegal(Ty))
9173         LastLegalVectorType = i + 1;
9174     }
9175
9176     // We only use vectors if the constant is known to be zero and the
9177     // function is not marked with the noimplicitfloat attribute.
9178     if (NonZero || NoVectors)
9179       LastLegalVectorType = 0;
9180
9181     // Check if we found a legal integer type to store.
9182     if (LastLegalType == 0 && LastLegalVectorType == 0)
9183       return false;
9184
9185     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9186     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9187
9188     // Make sure we have something to merge.
9189     if (NumElem < 2)
9190       return false;
9191
9192     unsigned EarliestNodeUsed = 0;
9193     for (unsigned i=0; i < NumElem; ++i) {
9194       // Find a chain for the new wide-store operand. Notice that some
9195       // of the store nodes that we found may not be selected for inclusion
9196       // in the wide store. The chain we use needs to be the chain of the
9197       // earliest store node which is *used* and replaced by the wide store.
9198       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9199         EarliestNodeUsed = i;
9200     }
9201
9202     // The earliest Node in the DAG.
9203     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9204     SDLoc DL(StoreNodes[0].MemNode);
9205
9206     SDValue StoredVal;
9207     if (UseVector) {
9208       // Find a legal type for the vector store.
9209       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9210       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9211       StoredVal = DAG.getConstant(0, Ty);
9212     } else {
9213       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9214       APInt StoreInt(StoreBW, 0);
9215
9216       // Construct a single integer constant which is made of the smaller
9217       // constant inputs.
9218       bool IsLE = TLI.isLittleEndian();
9219       for (unsigned i = 0; i < NumElem ; ++i) {
9220         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9221         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9222         SDValue Val = St->getValue();
9223         StoreInt<<=ElementSizeBytes*8;
9224         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9225           StoreInt|=C->getAPIntValue().zext(StoreBW);
9226         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9227           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9228         } else {
9229           assert(false && "Invalid constant element type");
9230         }
9231       }
9232
9233       // Create the new Load and Store operations.
9234       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9235       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9236     }
9237
9238     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9239                                     FirstInChain->getBasePtr(),
9240                                     FirstInChain->getPointerInfo(),
9241                                     false, false,
9242                                     FirstInChain->getAlignment());
9243
9244     // Replace the first store with the new store
9245     CombineTo(EarliestOp, NewStore);
9246     // Erase all other stores.
9247     for (unsigned i = 0; i < NumElem ; ++i) {
9248       if (StoreNodes[i].MemNode == EarliestOp)
9249         continue;
9250       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9251       // ReplaceAllUsesWith will replace all uses that existed when it was
9252       // called, but graph optimizations may cause new ones to appear. For
9253       // example, the case in pr14333 looks like
9254       //
9255       //  St's chain -> St -> another store -> X
9256       //
9257       // And the only difference from St to the other store is the chain.
9258       // When we change it's chain to be St's chain they become identical,
9259       // get CSEed and the net result is that X is now a use of St.
9260       // Since we know that St is redundant, just iterate.
9261       while (!St->use_empty())
9262         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9263       removeFromWorkList(St);
9264       DAG.DeleteNode(St);
9265     }
9266
9267     return true;
9268   }
9269
9270   // Below we handle the case of multiple consecutive stores that
9271   // come from multiple consecutive loads. We merge them into a single
9272   // wide load and a single wide store.
9273
9274   // Look for load nodes which are used by the stored values.
9275   SmallVector<MemOpLink, 8> LoadNodes;
9276
9277   // Find acceptable loads. Loads need to have the same chain (token factor),
9278   // must not be zext, volatile, indexed, and they must be consecutive.
9279   BaseIndexOffset LdBasePtr;
9280   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9281     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9282     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9283     if (!Ld) break;
9284
9285     // Loads must only have one use.
9286     if (!Ld->hasNUsesOfValue(1, 0))
9287       break;
9288
9289     // Check that the alignment is the same as the stores.
9290     if (Ld->getAlignment() != St->getAlignment())
9291       break;
9292
9293     // The memory operands must not be volatile.
9294     if (Ld->isVolatile() || Ld->isIndexed())
9295       break;
9296
9297     // We do not accept ext loads.
9298     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9299       break;
9300
9301     // The stored memory type must be the same.
9302     if (Ld->getMemoryVT() != MemVT)
9303       break;
9304
9305     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9306     // If this is not the first ptr that we check.
9307     if (LdBasePtr.Base.getNode()) {
9308       // The base ptr must be the same.
9309       if (!LdPtr.equalBaseIndex(LdBasePtr))
9310         break;
9311     } else {
9312       // Check that all other base pointers are the same as this one.
9313       LdBasePtr = LdPtr;
9314     }
9315
9316     // We found a potential memory operand to merge.
9317     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9318   }
9319
9320   if (LoadNodes.size() < 2)
9321     return false;
9322
9323   // Scan the memory operations on the chain and find the first non-consecutive
9324   // load memory address. These variables hold the index in the store node
9325   // array.
9326   unsigned LastConsecutiveLoad = 0;
9327   // This variable refers to the size and not index in the array.
9328   unsigned LastLegalVectorType = 0;
9329   unsigned LastLegalIntegerType = 0;
9330   StartAddress = LoadNodes[0].OffsetFromBase;
9331   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9332   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9333     // All loads much share the same chain.
9334     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9335       break;
9336
9337     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9338     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9339       break;
9340     LastConsecutiveLoad = i;
9341
9342     // Find a legal type for the vector store.
9343     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9344     if (TLI.isTypeLegal(StoreTy))
9345       LastLegalVectorType = i + 1;
9346
9347     // Find a legal type for the integer store.
9348     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9349     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9350     if (TLI.isTypeLegal(StoreTy))
9351       LastLegalIntegerType = i + 1;
9352     // Or check whether a truncstore and extload is legal.
9353     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9354              TargetLowering::TypePromoteInteger) {
9355       EVT LegalizedStoredValueTy =
9356         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9357       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9358           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9359           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9360           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9361         LastLegalIntegerType = i+1;
9362     }
9363   }
9364
9365   // Only use vector types if the vector type is larger than the integer type.
9366   // If they are the same, use integers.
9367   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9368   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9369
9370   // We add +1 here because the LastXXX variables refer to location while
9371   // the NumElem refers to array/index size.
9372   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9373   NumElem = std::min(LastLegalType, NumElem);
9374
9375   if (NumElem < 2)
9376     return false;
9377
9378   // The earliest Node in the DAG.
9379   unsigned EarliestNodeUsed = 0;
9380   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9381   for (unsigned i=1; i<NumElem; ++i) {
9382     // Find a chain for the new wide-store operand. Notice that some
9383     // of the store nodes that we found may not be selected for inclusion
9384     // in the wide store. The chain we use needs to be the chain of the
9385     // earliest store node which is *used* and replaced by the wide store.
9386     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9387       EarliestNodeUsed = i;
9388   }
9389
9390   // Find if it is better to use vectors or integers to load and store
9391   // to memory.
9392   EVT JointMemOpVT;
9393   if (UseVectorTy) {
9394     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9395   } else {
9396     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9397     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9398   }
9399
9400   SDLoc LoadDL(LoadNodes[0].MemNode);
9401   SDLoc StoreDL(StoreNodes[0].MemNode);
9402
9403   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9404   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9405                                 FirstLoad->getChain(),
9406                                 FirstLoad->getBasePtr(),
9407                                 FirstLoad->getPointerInfo(),
9408                                 false, false, false,
9409                                 FirstLoad->getAlignment());
9410
9411   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9412                                   FirstInChain->getBasePtr(),
9413                                   FirstInChain->getPointerInfo(), false, false,
9414                                   FirstInChain->getAlignment());
9415
9416   // Replace one of the loads with the new load.
9417   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9418   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9419                                 SDValue(NewLoad.getNode(), 1));
9420
9421   // Remove the rest of the load chains.
9422   for (unsigned i = 1; i < NumElem ; ++i) {
9423     // Replace all chain users of the old load nodes with the chain of the new
9424     // load node.
9425     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9426     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9427   }
9428
9429   // Replace the first store with the new store.
9430   CombineTo(EarliestOp, NewStore);
9431   // Erase all other stores.
9432   for (unsigned i = 0; i < NumElem ; ++i) {
9433     // Remove all Store nodes.
9434     if (StoreNodes[i].MemNode == EarliestOp)
9435       continue;
9436     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9437     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9438     removeFromWorkList(St);
9439     DAG.DeleteNode(St);
9440   }
9441
9442   return true;
9443 }
9444
9445 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9446   StoreSDNode *ST  = cast<StoreSDNode>(N);
9447   SDValue Chain = ST->getChain();
9448   SDValue Value = ST->getValue();
9449   SDValue Ptr   = ST->getBasePtr();
9450
9451   // If this is a store of a bit convert, store the input value if the
9452   // resultant store does not need a higher alignment than the original.
9453   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9454       ST->isUnindexed()) {
9455     unsigned OrigAlign = ST->getAlignment();
9456     EVT SVT = Value.getOperand(0).getValueType();
9457     unsigned Align = TLI.getDataLayout()->
9458       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9459     if (Align <= OrigAlign &&
9460         ((!LegalOperations && !ST->isVolatile()) ||
9461          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9462       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9463                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9464                           ST->isNonTemporal(), OrigAlign,
9465                           ST->getTBAAInfo());
9466   }
9467
9468   // Turn 'store undef, Ptr' -> nothing.
9469   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9470     return Chain;
9471
9472   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9473   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9474     // NOTE: If the original store is volatile, this transform must not increase
9475     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9476     // processor operation but an i64 (which is not legal) requires two.  So the
9477     // transform should not be done in this case.
9478     if (Value.getOpcode() != ISD::TargetConstantFP) {
9479       SDValue Tmp;
9480       switch (CFP->getSimpleValueType(0).SimpleTy) {
9481       default: llvm_unreachable("Unknown FP type");
9482       case MVT::f16:    // We don't do this for these yet.
9483       case MVT::f80:
9484       case MVT::f128:
9485       case MVT::ppcf128:
9486         break;
9487       case MVT::f32:
9488         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9489             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9490           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9491                               bitcastToAPInt().getZExtValue(), MVT::i32);
9492           return DAG.getStore(Chain, SDLoc(N), Tmp,
9493                               Ptr, ST->getMemOperand());
9494         }
9495         break;
9496       case MVT::f64:
9497         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9498              !ST->isVolatile()) ||
9499             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9500           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9501                                 getZExtValue(), MVT::i64);
9502           return DAG.getStore(Chain, SDLoc(N), Tmp,
9503                               Ptr, ST->getMemOperand());
9504         }
9505
9506         if (!ST->isVolatile() &&
9507             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9508           // Many FP stores are not made apparent until after legalize, e.g. for
9509           // argument passing.  Since this is so common, custom legalize the
9510           // 64-bit integer store into two 32-bit stores.
9511           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9512           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9513           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9514           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9515
9516           unsigned Alignment = ST->getAlignment();
9517           bool isVolatile = ST->isVolatile();
9518           bool isNonTemporal = ST->isNonTemporal();
9519           const MDNode *TBAAInfo = ST->getTBAAInfo();
9520
9521           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9522                                      Ptr, ST->getPointerInfo(),
9523                                      isVolatile, isNonTemporal,
9524                                      ST->getAlignment(), TBAAInfo);
9525           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9526                             DAG.getConstant(4, Ptr.getValueType()));
9527           Alignment = MinAlign(Alignment, 4U);
9528           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9529                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9530                                      isVolatile, isNonTemporal,
9531                                      Alignment, TBAAInfo);
9532           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9533                              St0, St1);
9534         }
9535
9536         break;
9537       }
9538     }
9539   }
9540
9541   // Try to infer better alignment information than the store already has.
9542   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9543     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9544       if (Align > ST->getAlignment())
9545         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9546                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9547                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9548                                  ST->getTBAAInfo());
9549     }
9550   }
9551
9552   // Try transforming a pair floating point load / store ops to integer
9553   // load / store ops.
9554   SDValue NewST = TransformFPLoadStorePair(N);
9555   if (NewST.getNode())
9556     return NewST;
9557
9558   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9559     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9560 #ifndef NDEBUG
9561   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9562       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9563     UseAA = false;
9564 #endif
9565   if (UseAA && ST->isUnindexed()) {
9566     // Walk up chain skipping non-aliasing memory nodes.
9567     SDValue BetterChain = FindBetterChain(N, Chain);
9568
9569     // If there is a better chain.
9570     if (Chain != BetterChain) {
9571       SDValue ReplStore;
9572
9573       // Replace the chain to avoid dependency.
9574       if (ST->isTruncatingStore()) {
9575         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9576                                       ST->getMemoryVT(), ST->getMemOperand());
9577       } else {
9578         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9579                                  ST->getMemOperand());
9580       }
9581
9582       // Create token to keep both nodes around.
9583       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9584                                   MVT::Other, Chain, ReplStore);
9585
9586       // Make sure the new and old chains are cleaned up.
9587       AddToWorkList(Token.getNode());
9588
9589       // Don't add users to work list.
9590       return CombineTo(N, Token, false);
9591     }
9592   }
9593
9594   // Try transforming N to an indexed store.
9595   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9596     return SDValue(N, 0);
9597
9598   // FIXME: is there such a thing as a truncating indexed store?
9599   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9600       Value.getValueType().isInteger()) {
9601     // See if we can simplify the input to this truncstore with knowledge that
9602     // only the low bits are being used.  For example:
9603     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9604     SDValue Shorter =
9605       GetDemandedBits(Value,
9606                       APInt::getLowBitsSet(
9607                         Value.getValueType().getScalarType().getSizeInBits(),
9608                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9609     AddToWorkList(Value.getNode());
9610     if (Shorter.getNode())
9611       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9612                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9613
9614     // Otherwise, see if we can simplify the operation with
9615     // SimplifyDemandedBits, which only works if the value has a single use.
9616     if (SimplifyDemandedBits(Value,
9617                         APInt::getLowBitsSet(
9618                           Value.getValueType().getScalarType().getSizeInBits(),
9619                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9620       return SDValue(N, 0);
9621   }
9622
9623   // If this is a load followed by a store to the same location, then the store
9624   // is dead/noop.
9625   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9626     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9627         ST->isUnindexed() && !ST->isVolatile() &&
9628         // There can't be any side effects between the load and store, such as
9629         // a call or store.
9630         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9631       // The store is dead, remove it.
9632       return Chain;
9633     }
9634   }
9635
9636   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9637   // truncating store.  We can do this even if this is already a truncstore.
9638   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9639       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9640       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9641                             ST->getMemoryVT())) {
9642     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9643                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9644   }
9645
9646   // Only perform this optimization before the types are legal, because we
9647   // don't want to perform this optimization on every DAGCombine invocation.
9648   if (!LegalTypes) {
9649     bool EverChanged = false;
9650
9651     do {
9652       // There can be multiple store sequences on the same chain.
9653       // Keep trying to merge store sequences until we are unable to do so
9654       // or until we merge the last store on the chain.
9655       bool Changed = MergeConsecutiveStores(ST);
9656       EverChanged |= Changed;
9657       if (!Changed) break;
9658     } while (ST->getOpcode() != ISD::DELETED_NODE);
9659
9660     if (EverChanged)
9661       return SDValue(N, 0);
9662   }
9663
9664   return ReduceLoadOpStoreWidth(N);
9665 }
9666
9667 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9668   SDValue InVec = N->getOperand(0);
9669   SDValue InVal = N->getOperand(1);
9670   SDValue EltNo = N->getOperand(2);
9671   SDLoc dl(N);
9672
9673   // If the inserted element is an UNDEF, just use the input vector.
9674   if (InVal.getOpcode() == ISD::UNDEF)
9675     return InVec;
9676
9677   EVT VT = InVec.getValueType();
9678
9679   // If we can't generate a legal BUILD_VECTOR, exit
9680   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9681     return SDValue();
9682
9683   // Check that we know which element is being inserted
9684   if (!isa<ConstantSDNode>(EltNo))
9685     return SDValue();
9686   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9687
9688   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9689   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9690   // vector elements.
9691   SmallVector<SDValue, 8> Ops;
9692   // Do not combine these two vectors if the output vector will not replace
9693   // the input vector.
9694   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9695     Ops.append(InVec.getNode()->op_begin(),
9696                InVec.getNode()->op_end());
9697   } else if (InVec.getOpcode() == ISD::UNDEF) {
9698     unsigned NElts = VT.getVectorNumElements();
9699     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9700   } else {
9701     return SDValue();
9702   }
9703
9704   // Insert the element
9705   if (Elt < Ops.size()) {
9706     // All the operands of BUILD_VECTOR must have the same type;
9707     // we enforce that here.
9708     EVT OpVT = Ops[0].getValueType();
9709     if (InVal.getValueType() != OpVT)
9710       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9711                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9712                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9713     Ops[Elt] = InVal;
9714   }
9715
9716   // Return the new vector
9717   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9718                      VT, &Ops[0], Ops.size());
9719 }
9720
9721 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9722   // (vextract (scalar_to_vector val, 0) -> val
9723   SDValue InVec = N->getOperand(0);
9724   EVT VT = InVec.getValueType();
9725   EVT NVT = N->getValueType(0);
9726
9727   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9728     // Check if the result type doesn't match the inserted element type. A
9729     // SCALAR_TO_VECTOR may truncate the inserted element and the
9730     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9731     SDValue InOp = InVec.getOperand(0);
9732     if (InOp.getValueType() != NVT) {
9733       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9734       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9735     }
9736     return InOp;
9737   }
9738
9739   SDValue EltNo = N->getOperand(1);
9740   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9741
9742   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9743   // We only perform this optimization before the op legalization phase because
9744   // we may introduce new vector instructions which are not backed by TD
9745   // patterns. For example on AVX, extracting elements from a wide vector
9746   // without using extract_subvector. However, if we can find an underlying
9747   // scalar value, then we can always use that.
9748   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9749       && ConstEltNo) {
9750     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9751     int NumElem = VT.getVectorNumElements();
9752     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9753     // Find the new index to extract from.
9754     int OrigElt = SVOp->getMaskElt(Elt);
9755
9756     // Extracting an undef index is undef.
9757     if (OrigElt == -1)
9758       return DAG.getUNDEF(NVT);
9759
9760     // Select the right vector half to extract from.
9761     SDValue SVInVec;
9762     if (OrigElt < NumElem) {
9763       SVInVec = InVec->getOperand(0);
9764     } else {
9765       SVInVec = InVec->getOperand(1);
9766       OrigElt -= NumElem;
9767     }
9768
9769     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9770       SDValue InOp = SVInVec.getOperand(OrigElt);
9771       if (InOp.getValueType() != NVT) {
9772         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9773         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9774       }
9775
9776       return InOp;
9777     }
9778
9779     // FIXME: We should handle recursing on other vector shuffles and
9780     // scalar_to_vector here as well.
9781
9782     if (!LegalOperations) {
9783       EVT IndexTy = TLI.getVectorIdxTy();
9784       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9785                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9786     }
9787   }
9788
9789   // Perform only after legalization to ensure build_vector / vector_shuffle
9790   // optimizations have already been done.
9791   if (!LegalOperations) return SDValue();
9792
9793   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9794   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9795   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9796
9797   if (ConstEltNo) {
9798     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9799     bool NewLoad = false;
9800     bool BCNumEltsChanged = false;
9801     EVT ExtVT = VT.getVectorElementType();
9802     EVT LVT = ExtVT;
9803
9804     // If the result of load has to be truncated, then it's not necessarily
9805     // profitable.
9806     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9807       return SDValue();
9808
9809     if (InVec.getOpcode() == ISD::BITCAST) {
9810       // Don't duplicate a load with other uses.
9811       if (!InVec.hasOneUse())
9812         return SDValue();
9813
9814       EVT BCVT = InVec.getOperand(0).getValueType();
9815       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9816         return SDValue();
9817       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9818         BCNumEltsChanged = true;
9819       InVec = InVec.getOperand(0);
9820       ExtVT = BCVT.getVectorElementType();
9821       NewLoad = true;
9822     }
9823
9824     LoadSDNode *LN0 = NULL;
9825     const ShuffleVectorSDNode *SVN = NULL;
9826     if (ISD::isNormalLoad(InVec.getNode())) {
9827       LN0 = cast<LoadSDNode>(InVec);
9828     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9829                InVec.getOperand(0).getValueType() == ExtVT &&
9830                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9831       // Don't duplicate a load with other uses.
9832       if (!InVec.hasOneUse())
9833         return SDValue();
9834
9835       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9836     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9837       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9838       // =>
9839       // (load $addr+1*size)
9840
9841       // Don't duplicate a load with other uses.
9842       if (!InVec.hasOneUse())
9843         return SDValue();
9844
9845       // If the bit convert changed the number of elements, it is unsafe
9846       // to examine the mask.
9847       if (BCNumEltsChanged)
9848         return SDValue();
9849
9850       // Select the input vector, guarding against out of range extract vector.
9851       unsigned NumElems = VT.getVectorNumElements();
9852       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9853       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9854
9855       if (InVec.getOpcode() == ISD::BITCAST) {
9856         // Don't duplicate a load with other uses.
9857         if (!InVec.hasOneUse())
9858           return SDValue();
9859
9860         InVec = InVec.getOperand(0);
9861       }
9862       if (ISD::isNormalLoad(InVec.getNode())) {
9863         LN0 = cast<LoadSDNode>(InVec);
9864         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9865       }
9866     }
9867
9868     // Make sure we found a non-volatile load and the extractelement is
9869     // the only use.
9870     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9871       return SDValue();
9872
9873     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9874     if (Elt == -1)
9875       return DAG.getUNDEF(LVT);
9876
9877     unsigned Align = LN0->getAlignment();
9878     if (NewLoad) {
9879       // Check the resultant load doesn't need a higher alignment than the
9880       // original load.
9881       unsigned NewAlign =
9882         TLI.getDataLayout()
9883             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9884
9885       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9886         return SDValue();
9887
9888       Align = NewAlign;
9889     }
9890
9891     SDValue NewPtr = LN0->getBasePtr();
9892     unsigned PtrOff = 0;
9893
9894     if (Elt) {
9895       PtrOff = LVT.getSizeInBits() * Elt / 8;
9896       EVT PtrType = NewPtr.getValueType();
9897       if (TLI.isBigEndian())
9898         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9899       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9900                            DAG.getConstant(PtrOff, PtrType));
9901     }
9902
9903     // The replacement we need to do here is a little tricky: we need to
9904     // replace an extractelement of a load with a load.
9905     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9906     // Note that this replacement assumes that the extractvalue is the only
9907     // use of the load; that's okay because we don't want to perform this
9908     // transformation in other cases anyway.
9909     SDValue Load;
9910     SDValue Chain;
9911     if (NVT.bitsGT(LVT)) {
9912       // If the result type of vextract is wider than the load, then issue an
9913       // extending load instead.
9914       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9915         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9916       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9917                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9918                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9919                             Align, LN0->getTBAAInfo());
9920       Chain = Load.getValue(1);
9921     } else {
9922       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9923                          LN0->getPointerInfo().getWithOffset(PtrOff),
9924                          LN0->isVolatile(), LN0->isNonTemporal(),
9925                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9926       Chain = Load.getValue(1);
9927       if (NVT.bitsLT(LVT))
9928         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9929       else
9930         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9931     }
9932     WorkListRemover DeadNodes(*this);
9933     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9934     SDValue To[] = { Load, Chain };
9935     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9936     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9937     // worklist explicitly as well.
9938     AddToWorkList(Load.getNode());
9939     AddUsersToWorkList(Load.getNode()); // Add users too
9940     // Make sure to revisit this node to clean it up; it will usually be dead.
9941     AddToWorkList(N);
9942     return SDValue(N, 0);
9943   }
9944
9945   return SDValue();
9946 }
9947
9948 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9949 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9950   // We perform this optimization post type-legalization because
9951   // the type-legalizer often scalarizes integer-promoted vectors.
9952   // Performing this optimization before may create bit-casts which
9953   // will be type-legalized to complex code sequences.
9954   // We perform this optimization only before the operation legalizer because we
9955   // may introduce illegal operations.
9956   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9957     return SDValue();
9958
9959   unsigned NumInScalars = N->getNumOperands();
9960   SDLoc dl(N);
9961   EVT VT = N->getValueType(0);
9962
9963   // Check to see if this is a BUILD_VECTOR of a bunch of values
9964   // which come from any_extend or zero_extend nodes. If so, we can create
9965   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9966   // optimizations. We do not handle sign-extend because we can't fill the sign
9967   // using shuffles.
9968   EVT SourceType = MVT::Other;
9969   bool AllAnyExt = true;
9970
9971   for (unsigned i = 0; i != NumInScalars; ++i) {
9972     SDValue In = N->getOperand(i);
9973     // Ignore undef inputs.
9974     if (In.getOpcode() == ISD::UNDEF) continue;
9975
9976     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9977     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9978
9979     // Abort if the element is not an extension.
9980     if (!ZeroExt && !AnyExt) {
9981       SourceType = MVT::Other;
9982       break;
9983     }
9984
9985     // The input is a ZeroExt or AnyExt. Check the original type.
9986     EVT InTy = In.getOperand(0).getValueType();
9987
9988     // Check that all of the widened source types are the same.
9989     if (SourceType == MVT::Other)
9990       // First time.
9991       SourceType = InTy;
9992     else if (InTy != SourceType) {
9993       // Multiple income types. Abort.
9994       SourceType = MVT::Other;
9995       break;
9996     }
9997
9998     // Check if all of the extends are ANY_EXTENDs.
9999     AllAnyExt &= AnyExt;
10000   }
10001
10002   // In order to have valid types, all of the inputs must be extended from the
10003   // same source type and all of the inputs must be any or zero extend.
10004   // Scalar sizes must be a power of two.
10005   EVT OutScalarTy = VT.getScalarType();
10006   bool ValidTypes = SourceType != MVT::Other &&
10007                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10008                  isPowerOf2_32(SourceType.getSizeInBits());
10009
10010   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10011   // turn into a single shuffle instruction.
10012   if (!ValidTypes)
10013     return SDValue();
10014
10015   bool isLE = TLI.isLittleEndian();
10016   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10017   assert(ElemRatio > 1 && "Invalid element size ratio");
10018   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10019                                DAG.getConstant(0, SourceType);
10020
10021   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10022   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10023
10024   // Populate the new build_vector
10025   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10026     SDValue Cast = N->getOperand(i);
10027     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10028             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10029             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10030     SDValue In;
10031     if (Cast.getOpcode() == ISD::UNDEF)
10032       In = DAG.getUNDEF(SourceType);
10033     else
10034       In = Cast->getOperand(0);
10035     unsigned Index = isLE ? (i * ElemRatio) :
10036                             (i * ElemRatio + (ElemRatio - 1));
10037
10038     assert(Index < Ops.size() && "Invalid index");
10039     Ops[Index] = In;
10040   }
10041
10042   // The type of the new BUILD_VECTOR node.
10043   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10044   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10045          "Invalid vector size");
10046   // Check if the new vector type is legal.
10047   if (!isTypeLegal(VecVT)) return SDValue();
10048
10049   // Make the new BUILD_VECTOR.
10050   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10051
10052   // The new BUILD_VECTOR node has the potential to be further optimized.
10053   AddToWorkList(BV.getNode());
10054   // Bitcast to the desired type.
10055   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10056 }
10057
10058 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10059   EVT VT = N->getValueType(0);
10060
10061   unsigned NumInScalars = N->getNumOperands();
10062   SDLoc dl(N);
10063
10064   EVT SrcVT = MVT::Other;
10065   unsigned Opcode = ISD::DELETED_NODE;
10066   unsigned NumDefs = 0;
10067
10068   for (unsigned i = 0; i != NumInScalars; ++i) {
10069     SDValue In = N->getOperand(i);
10070     unsigned Opc = In.getOpcode();
10071
10072     if (Opc == ISD::UNDEF)
10073       continue;
10074
10075     // If all scalar values are floats and converted from integers.
10076     if (Opcode == ISD::DELETED_NODE &&
10077         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10078       Opcode = Opc;
10079     }
10080
10081     if (Opc != Opcode)
10082       return SDValue();
10083
10084     EVT InVT = In.getOperand(0).getValueType();
10085
10086     // If all scalar values are typed differently, bail out. It's chosen to
10087     // simplify BUILD_VECTOR of integer types.
10088     if (SrcVT == MVT::Other)
10089       SrcVT = InVT;
10090     if (SrcVT != InVT)
10091       return SDValue();
10092     NumDefs++;
10093   }
10094
10095   // If the vector has just one element defined, it's not worth to fold it into
10096   // a vectorized one.
10097   if (NumDefs < 2)
10098     return SDValue();
10099
10100   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10101          && "Should only handle conversion from integer to float.");
10102   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10103
10104   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10105
10106   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10107     return SDValue();
10108
10109   SmallVector<SDValue, 8> Opnds;
10110   for (unsigned i = 0; i != NumInScalars; ++i) {
10111     SDValue In = N->getOperand(i);
10112
10113     if (In.getOpcode() == ISD::UNDEF)
10114       Opnds.push_back(DAG.getUNDEF(SrcVT));
10115     else
10116       Opnds.push_back(In.getOperand(0));
10117   }
10118   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10119                            &Opnds[0], Opnds.size());
10120   AddToWorkList(BV.getNode());
10121
10122   return DAG.getNode(Opcode, dl, VT, BV);
10123 }
10124
10125 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10126   unsigned NumInScalars = N->getNumOperands();
10127   SDLoc dl(N);
10128   EVT VT = N->getValueType(0);
10129
10130   // A vector built entirely of undefs is undef.
10131   if (ISD::allOperandsUndef(N))
10132     return DAG.getUNDEF(VT);
10133
10134   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10135   if (V.getNode())
10136     return V;
10137
10138   V = reduceBuildVecConvertToConvertBuildVec(N);
10139   if (V.getNode())
10140     return V;
10141
10142   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10143   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10144   // at most two distinct vectors, turn this into a shuffle node.
10145
10146   // May only combine to shuffle after legalize if shuffle is legal.
10147   if (LegalOperations &&
10148       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10149     return SDValue();
10150
10151   SDValue VecIn1, VecIn2;
10152   for (unsigned i = 0; i != NumInScalars; ++i) {
10153     // Ignore undef inputs.
10154     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10155
10156     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10157     // constant index, bail out.
10158     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10159         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10160       VecIn1 = VecIn2 = SDValue(0, 0);
10161       break;
10162     }
10163
10164     // We allow up to two distinct input vectors.
10165     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10166     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10167       continue;
10168
10169     if (VecIn1.getNode() == 0) {
10170       VecIn1 = ExtractedFromVec;
10171     } else if (VecIn2.getNode() == 0) {
10172       VecIn2 = ExtractedFromVec;
10173     } else {
10174       // Too many inputs.
10175       VecIn1 = VecIn2 = SDValue(0, 0);
10176       break;
10177     }
10178   }
10179
10180     // If everything is good, we can make a shuffle operation.
10181   if (VecIn1.getNode()) {
10182     SmallVector<int, 8> Mask;
10183     for (unsigned i = 0; i != NumInScalars; ++i) {
10184       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10185         Mask.push_back(-1);
10186         continue;
10187       }
10188
10189       // If extracting from the first vector, just use the index directly.
10190       SDValue Extract = N->getOperand(i);
10191       SDValue ExtVal = Extract.getOperand(1);
10192       if (Extract.getOperand(0) == VecIn1) {
10193         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10194         if (ExtIndex > VT.getVectorNumElements())
10195           return SDValue();
10196
10197         Mask.push_back(ExtIndex);
10198         continue;
10199       }
10200
10201       // Otherwise, use InIdx + VecSize
10202       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10203       Mask.push_back(Idx+NumInScalars);
10204     }
10205
10206     // We can't generate a shuffle node with mismatched input and output types.
10207     // Attempt to transform a single input vector to the correct type.
10208     if ((VT != VecIn1.getValueType())) {
10209       // We don't support shuffeling between TWO values of different types.
10210       if (VecIn2.getNode() != 0)
10211         return SDValue();
10212
10213       // We only support widening of vectors which are half the size of the
10214       // output registers. For example XMM->YMM widening on X86 with AVX.
10215       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10216         return SDValue();
10217
10218       // If the input vector type has a different base type to the output
10219       // vector type, bail out.
10220       if (VecIn1.getValueType().getVectorElementType() !=
10221           VT.getVectorElementType())
10222         return SDValue();
10223
10224       // Widen the input vector by adding undef values.
10225       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10226                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10227     }
10228
10229     // If VecIn2 is unused then change it to undef.
10230     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10231
10232     // Check that we were able to transform all incoming values to the same
10233     // type.
10234     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10235         VecIn1.getValueType() != VT)
10236           return SDValue();
10237
10238     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10239     if (!isTypeLegal(VT))
10240       return SDValue();
10241
10242     // Return the new VECTOR_SHUFFLE node.
10243     SDValue Ops[2];
10244     Ops[0] = VecIn1;
10245     Ops[1] = VecIn2;
10246     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10247   }
10248
10249   return SDValue();
10250 }
10251
10252 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10253   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10254   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10255   // inputs come from at most two distinct vectors, turn this into a shuffle
10256   // node.
10257
10258   // If we only have one input vector, we don't need to do any concatenation.
10259   if (N->getNumOperands() == 1)
10260     return N->getOperand(0);
10261
10262   // Check if all of the operands are undefs.
10263   EVT VT = N->getValueType(0);
10264   if (ISD::allOperandsUndef(N))
10265     return DAG.getUNDEF(VT);
10266
10267   // Optimize concat_vectors where one of the vectors is undef.
10268   if (N->getNumOperands() == 2 &&
10269       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10270     SDValue In = N->getOperand(0);
10271     assert(In.getValueType().isVector() && "Must concat vectors");
10272
10273     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10274     if (In->getOpcode() == ISD::BITCAST &&
10275         !In->getOperand(0)->getValueType(0).isVector()) {
10276       SDValue Scalar = In->getOperand(0);
10277       EVT SclTy = Scalar->getValueType(0);
10278
10279       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10280         return SDValue();
10281
10282       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10283                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10284       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10285         return SDValue();
10286
10287       SDLoc dl = SDLoc(N);
10288       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10289       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10290     }
10291   }
10292
10293   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10294   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10295   if (N->getNumOperands() == 2 &&
10296       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10297       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10298     EVT VT = N->getValueType(0);
10299     SDValue N0 = N->getOperand(0);
10300     SDValue N1 = N->getOperand(1);
10301     SmallVector<SDValue, 8> Opnds;
10302     unsigned BuildVecNumElts =  N0.getNumOperands();
10303
10304     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10305       Opnds.push_back(N0.getOperand(i));
10306     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10307       Opnds.push_back(N1.getOperand(i));
10308
10309     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10310                        Opnds.size());
10311   }
10312
10313   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10314   // nodes often generate nop CONCAT_VECTOR nodes.
10315   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10316   // place the incoming vectors at the exact same location.
10317   SDValue SingleSource = SDValue();
10318   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10319
10320   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10321     SDValue Op = N->getOperand(i);
10322
10323     if (Op.getOpcode() == ISD::UNDEF)
10324       continue;
10325
10326     // Check if this is the identity extract:
10327     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10328       return SDValue();
10329
10330     // Find the single incoming vector for the extract_subvector.
10331     if (SingleSource.getNode()) {
10332       if (Op.getOperand(0) != SingleSource)
10333         return SDValue();
10334     } else {
10335       SingleSource = Op.getOperand(0);
10336
10337       // Check the source type is the same as the type of the result.
10338       // If not, this concat may extend the vector, so we can not
10339       // optimize it away.
10340       if (SingleSource.getValueType() != N->getValueType(0))
10341         return SDValue();
10342     }
10343
10344     unsigned IdentityIndex = i * PartNumElem;
10345     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10346     // The extract index must be constant.
10347     if (!CS)
10348       return SDValue();
10349
10350     // Check that we are reading from the identity index.
10351     if (CS->getZExtValue() != IdentityIndex)
10352       return SDValue();
10353   }
10354
10355   if (SingleSource.getNode())
10356     return SingleSource;
10357
10358   return SDValue();
10359 }
10360
10361 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10362   EVT NVT = N->getValueType(0);
10363   SDValue V = N->getOperand(0);
10364
10365   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10366     // Combine:
10367     //    (extract_subvec (concat V1, V2, ...), i)
10368     // Into:
10369     //    Vi if possible
10370     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10371     // type.
10372     if (V->getOperand(0).getValueType() != NVT)
10373       return SDValue();
10374     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10375     unsigned NumElems = NVT.getVectorNumElements();
10376     assert((Idx % NumElems) == 0 &&
10377            "IDX in concat is not a multiple of the result vector length.");
10378     return V->getOperand(Idx / NumElems);
10379   }
10380
10381   // Skip bitcasting
10382   if (V->getOpcode() == ISD::BITCAST)
10383     V = V.getOperand(0);
10384
10385   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10386     SDLoc dl(N);
10387     // Handle only simple case where vector being inserted and vector
10388     // being extracted are of same type, and are half size of larger vectors.
10389     EVT BigVT = V->getOperand(0).getValueType();
10390     EVT SmallVT = V->getOperand(1).getValueType();
10391     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10392       return SDValue();
10393
10394     // Only handle cases where both indexes are constants with the same type.
10395     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10396     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10397
10398     if (InsIdx && ExtIdx &&
10399         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10400         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10401       // Combine:
10402       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10403       // Into:
10404       //    indices are equal or bit offsets are equal => V1
10405       //    otherwise => (extract_subvec V1, ExtIdx)
10406       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10407           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10408         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10409       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10410                          DAG.getNode(ISD::BITCAST, dl,
10411                                      N->getOperand(0).getValueType(),
10412                                      V->getOperand(0)), N->getOperand(1));
10413     }
10414   }
10415
10416   return SDValue();
10417 }
10418
10419 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10420 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10421   EVT VT = N->getValueType(0);
10422   unsigned NumElts = VT.getVectorNumElements();
10423
10424   SDValue N0 = N->getOperand(0);
10425   SDValue N1 = N->getOperand(1);
10426   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10427
10428   SmallVector<SDValue, 4> Ops;
10429   EVT ConcatVT = N0.getOperand(0).getValueType();
10430   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10431   unsigned NumConcats = NumElts / NumElemsPerConcat;
10432
10433   // Look at every vector that's inserted. We're looking for exact
10434   // subvector-sized copies from a concatenated vector
10435   for (unsigned I = 0; I != NumConcats; ++I) {
10436     // Make sure we're dealing with a copy.
10437     unsigned Begin = I * NumElemsPerConcat;
10438     bool AllUndef = true, NoUndef = true;
10439     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10440       if (SVN->getMaskElt(J) >= 0)
10441         AllUndef = false;
10442       else
10443         NoUndef = false;
10444     }
10445
10446     if (NoUndef) {
10447       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10448         return SDValue();
10449
10450       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10451         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10452           return SDValue();
10453
10454       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10455       if (FirstElt < N0.getNumOperands())
10456         Ops.push_back(N0.getOperand(FirstElt));
10457       else
10458         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10459
10460     } else if (AllUndef) {
10461       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10462     } else { // Mixed with general masks and undefs, can't do optimization.
10463       return SDValue();
10464     }
10465   }
10466
10467   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10468                      Ops.size());
10469 }
10470
10471 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10472   EVT VT = N->getValueType(0);
10473   unsigned NumElts = VT.getVectorNumElements();
10474
10475   SDValue N0 = N->getOperand(0);
10476   SDValue N1 = N->getOperand(1);
10477
10478   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10479
10480   // Canonicalize shuffle undef, undef -> undef
10481   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10482     return DAG.getUNDEF(VT);
10483
10484   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10485
10486   // Canonicalize shuffle v, v -> v, undef
10487   if (N0 == N1) {
10488     SmallVector<int, 8> NewMask;
10489     for (unsigned i = 0; i != NumElts; ++i) {
10490       int Idx = SVN->getMaskElt(i);
10491       if (Idx >= (int)NumElts) Idx -= NumElts;
10492       NewMask.push_back(Idx);
10493     }
10494     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10495                                 &NewMask[0]);
10496   }
10497
10498   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10499   if (N0.getOpcode() == ISD::UNDEF) {
10500     SmallVector<int, 8> NewMask;
10501     for (unsigned i = 0; i != NumElts; ++i) {
10502       int Idx = SVN->getMaskElt(i);
10503       if (Idx >= 0) {
10504         if (Idx >= (int)NumElts)
10505           Idx -= NumElts;
10506         else
10507           Idx = -1; // remove reference to lhs
10508       }
10509       NewMask.push_back(Idx);
10510     }
10511     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10512                                 &NewMask[0]);
10513   }
10514
10515   // Remove references to rhs if it is undef
10516   if (N1.getOpcode() == ISD::UNDEF) {
10517     bool Changed = false;
10518     SmallVector<int, 8> NewMask;
10519     for (unsigned i = 0; i != NumElts; ++i) {
10520       int Idx = SVN->getMaskElt(i);
10521       if (Idx >= (int)NumElts) {
10522         Idx = -1;
10523         Changed = true;
10524       }
10525       NewMask.push_back(Idx);
10526     }
10527     if (Changed)
10528       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10529   }
10530
10531   // If it is a splat, check if the argument vector is another splat or a
10532   // build_vector with all scalar elements the same.
10533   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10534     SDNode *V = N0.getNode();
10535
10536     // If this is a bit convert that changes the element type of the vector but
10537     // not the number of vector elements, look through it.  Be careful not to
10538     // look though conversions that change things like v4f32 to v2f64.
10539     if (V->getOpcode() == ISD::BITCAST) {
10540       SDValue ConvInput = V->getOperand(0);
10541       if (ConvInput.getValueType().isVector() &&
10542           ConvInput.getValueType().getVectorNumElements() == NumElts)
10543         V = ConvInput.getNode();
10544     }
10545
10546     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10547       assert(V->getNumOperands() == NumElts &&
10548              "BUILD_VECTOR has wrong number of operands");
10549       SDValue Base;
10550       bool AllSame = true;
10551       for (unsigned i = 0; i != NumElts; ++i) {
10552         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10553           Base = V->getOperand(i);
10554           break;
10555         }
10556       }
10557       // Splat of <u, u, u, u>, return <u, u, u, u>
10558       if (!Base.getNode())
10559         return N0;
10560       for (unsigned i = 0; i != NumElts; ++i) {
10561         if (V->getOperand(i) != Base) {
10562           AllSame = false;
10563           break;
10564         }
10565       }
10566       // Splat of <x, x, x, x>, return <x, x, x, x>
10567       if (AllSame)
10568         return N0;
10569     }
10570   }
10571
10572   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10573       Level < AfterLegalizeVectorOps &&
10574       (N1.getOpcode() == ISD::UNDEF ||
10575       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10576        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10577     SDValue V = partitionShuffleOfConcats(N, DAG);
10578
10579     if (V.getNode())
10580       return V;
10581   }
10582
10583   // If this shuffle node is simply a swizzle of another shuffle node,
10584   // and it reverses the swizzle of the previous shuffle then we can
10585   // optimize shuffle(shuffle(x, undef), undef) -> x.
10586   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10587       N1.getOpcode() == ISD::UNDEF) {
10588
10589     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10590
10591     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10592     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10593       return SDValue();
10594
10595     // The incoming shuffle must be of the same type as the result of the
10596     // current shuffle.
10597     assert(OtherSV->getOperand(0).getValueType() == VT &&
10598            "Shuffle types don't match");
10599
10600     for (unsigned i = 0; i != NumElts; ++i) {
10601       int Idx = SVN->getMaskElt(i);
10602       assert(Idx < (int)NumElts && "Index references undef operand");
10603       // Next, this index comes from the first value, which is the incoming
10604       // shuffle. Adopt the incoming index.
10605       if (Idx >= 0)
10606         Idx = OtherSV->getMaskElt(Idx);
10607
10608       // The combined shuffle must map each index to itself.
10609       if (Idx >= 0 && (unsigned)Idx != i)
10610         return SDValue();
10611     }
10612
10613     return OtherSV->getOperand(0);
10614   }
10615
10616   return SDValue();
10617 }
10618
10619 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10620   SDValue N0 = N->getOperand(0);
10621   SDValue N2 = N->getOperand(2);
10622
10623   // If the input vector is a concatenation, and the insert replaces
10624   // one of the halves, we can optimize into a single concat_vectors.
10625   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10626       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10627     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10628     EVT VT = N->getValueType(0);
10629
10630     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10631     // (concat_vectors Z, Y)
10632     if (InsIdx == 0)
10633       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10634                          N->getOperand(1), N0.getOperand(1));
10635
10636     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10637     // (concat_vectors X, Z)
10638     if (InsIdx == VT.getVectorNumElements()/2)
10639       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10640                          N0.getOperand(0), N->getOperand(1));
10641   }
10642
10643   return SDValue();
10644 }
10645
10646 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10647 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10648 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10649 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10650 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10651   EVT VT = N->getValueType(0);
10652   SDLoc dl(N);
10653   SDValue LHS = N->getOperand(0);
10654   SDValue RHS = N->getOperand(1);
10655   if (N->getOpcode() == ISD::AND) {
10656     if (RHS.getOpcode() == ISD::BITCAST)
10657       RHS = RHS.getOperand(0);
10658     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10659       SmallVector<int, 8> Indices;
10660       unsigned NumElts = RHS.getNumOperands();
10661       for (unsigned i = 0; i != NumElts; ++i) {
10662         SDValue Elt = RHS.getOperand(i);
10663         if (!isa<ConstantSDNode>(Elt))
10664           return SDValue();
10665
10666         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10667           Indices.push_back(i);
10668         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10669           Indices.push_back(NumElts);
10670         else
10671           return SDValue();
10672       }
10673
10674       // Let's see if the target supports this vector_shuffle.
10675       EVT RVT = RHS.getValueType();
10676       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10677         return SDValue();
10678
10679       // Return the new VECTOR_SHUFFLE node.
10680       EVT EltVT = RVT.getVectorElementType();
10681       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10682                                      DAG.getConstant(0, EltVT));
10683       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10684                                  RVT, &ZeroOps[0], ZeroOps.size());
10685       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10686       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10687       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10688     }
10689   }
10690
10691   return SDValue();
10692 }
10693
10694 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10695 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10696   assert(N->getValueType(0).isVector() &&
10697          "SimplifyVBinOp only works on vectors!");
10698
10699   SDValue LHS = N->getOperand(0);
10700   SDValue RHS = N->getOperand(1);
10701   SDValue Shuffle = XformToShuffleWithZero(N);
10702   if (Shuffle.getNode()) return Shuffle;
10703
10704   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10705   // this operation.
10706   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10707       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10708     // Check if both vectors are constants. If not bail out.
10709     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10710           cast<BuildVectorSDNode>(RHS)->isConstant()))
10711       return SDValue();
10712
10713     SmallVector<SDValue, 8> Ops;
10714     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10715       SDValue LHSOp = LHS.getOperand(i);
10716       SDValue RHSOp = RHS.getOperand(i);
10717
10718       // Can't fold divide by zero.
10719       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10720           N->getOpcode() == ISD::FDIV) {
10721         if ((RHSOp.getOpcode() == ISD::Constant &&
10722              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10723             (RHSOp.getOpcode() == ISD::ConstantFP &&
10724              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10725           break;
10726       }
10727
10728       EVT VT = LHSOp.getValueType();
10729       EVT RVT = RHSOp.getValueType();
10730       if (RVT != VT) {
10731         // Integer BUILD_VECTOR operands may have types larger than the element
10732         // size (e.g., when the element type is not legal).  Prior to type
10733         // legalization, the types may not match between the two BUILD_VECTORS.
10734         // Truncate one of the operands to make them match.
10735         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10736           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10737         } else {
10738           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10739           VT = RVT;
10740         }
10741       }
10742       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10743                                    LHSOp, RHSOp);
10744       if (FoldOp.getOpcode() != ISD::UNDEF &&
10745           FoldOp.getOpcode() != ISD::Constant &&
10746           FoldOp.getOpcode() != ISD::ConstantFP)
10747         break;
10748       Ops.push_back(FoldOp);
10749       AddToWorkList(FoldOp.getNode());
10750     }
10751
10752     if (Ops.size() == LHS.getNumOperands())
10753       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10754                          LHS.getValueType(), &Ops[0], Ops.size());
10755   }
10756
10757   return SDValue();
10758 }
10759
10760 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10761 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10762   assert(N->getValueType(0).isVector() &&
10763          "SimplifyVUnaryOp only works on vectors!");
10764
10765   SDValue N0 = N->getOperand(0);
10766
10767   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10768     return SDValue();
10769
10770   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10771   SmallVector<SDValue, 8> Ops;
10772   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10773     SDValue Op = N0.getOperand(i);
10774     if (Op.getOpcode() != ISD::UNDEF &&
10775         Op.getOpcode() != ISD::ConstantFP)
10776       break;
10777     EVT EltVT = Op.getValueType();
10778     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10779     if (FoldOp.getOpcode() != ISD::UNDEF &&
10780         FoldOp.getOpcode() != ISD::ConstantFP)
10781       break;
10782     Ops.push_back(FoldOp);
10783     AddToWorkList(FoldOp.getNode());
10784   }
10785
10786   if (Ops.size() != N0.getNumOperands())
10787     return SDValue();
10788
10789   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10790                      N0.getValueType(), &Ops[0], Ops.size());
10791 }
10792
10793 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10794                                     SDValue N1, SDValue N2){
10795   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10796
10797   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10798                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10799
10800   // If we got a simplified select_cc node back from SimplifySelectCC, then
10801   // break it down into a new SETCC node, and a new SELECT node, and then return
10802   // the SELECT node, since we were called with a SELECT node.
10803   if (SCC.getNode()) {
10804     // Check to see if we got a select_cc back (to turn into setcc/select).
10805     // Otherwise, just return whatever node we got back, like fabs.
10806     if (SCC.getOpcode() == ISD::SELECT_CC) {
10807       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10808                                   N0.getValueType(),
10809                                   SCC.getOperand(0), SCC.getOperand(1),
10810                                   SCC.getOperand(4));
10811       AddToWorkList(SETCC.getNode());
10812       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10813                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10814     }
10815
10816     return SCC;
10817   }
10818   return SDValue();
10819 }
10820
10821 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10822 /// are the two values being selected between, see if we can simplify the
10823 /// select.  Callers of this should assume that TheSelect is deleted if this
10824 /// returns true.  As such, they should return the appropriate thing (e.g. the
10825 /// node) back to the top-level of the DAG combiner loop to avoid it being
10826 /// looked at.
10827 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10828                                     SDValue RHS) {
10829
10830   // Cannot simplify select with vector condition
10831   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10832
10833   // If this is a select from two identical things, try to pull the operation
10834   // through the select.
10835   if (LHS.getOpcode() != RHS.getOpcode() ||
10836       !LHS.hasOneUse() || !RHS.hasOneUse())
10837     return false;
10838
10839   // If this is a load and the token chain is identical, replace the select
10840   // of two loads with a load through a select of the address to load from.
10841   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10842   // constants have been dropped into the constant pool.
10843   if (LHS.getOpcode() == ISD::LOAD) {
10844     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10845     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10846
10847     // Token chains must be identical.
10848     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10849         // Do not let this transformation reduce the number of volatile loads.
10850         LLD->isVolatile() || RLD->isVolatile() ||
10851         // If this is an EXTLOAD, the VT's must match.
10852         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10853         // If this is an EXTLOAD, the kind of extension must match.
10854         (LLD->getExtensionType() != RLD->getExtensionType() &&
10855          // The only exception is if one of the extensions is anyext.
10856          LLD->getExtensionType() != ISD::EXTLOAD &&
10857          RLD->getExtensionType() != ISD::EXTLOAD) ||
10858         // FIXME: this discards src value information.  This is
10859         // over-conservative. It would be beneficial to be able to remember
10860         // both potential memory locations.  Since we are discarding
10861         // src value info, don't do the transformation if the memory
10862         // locations are not in the default address space.
10863         LLD->getPointerInfo().getAddrSpace() != 0 ||
10864         RLD->getPointerInfo().getAddrSpace() != 0 ||
10865         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10866                                       LLD->getBasePtr().getValueType()))
10867       return false;
10868
10869     // Check that the select condition doesn't reach either load.  If so,
10870     // folding this will induce a cycle into the DAG.  If not, this is safe to
10871     // xform, so create a select of the addresses.
10872     SDValue Addr;
10873     if (TheSelect->getOpcode() == ISD::SELECT) {
10874       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10875       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10876           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10877         return false;
10878       // The loads must not depend on one another.
10879       if (LLD->isPredecessorOf(RLD) ||
10880           RLD->isPredecessorOf(LLD))
10881         return false;
10882       Addr = DAG.getSelect(SDLoc(TheSelect),
10883                            LLD->getBasePtr().getValueType(),
10884                            TheSelect->getOperand(0), LLD->getBasePtr(),
10885                            RLD->getBasePtr());
10886     } else {  // Otherwise SELECT_CC
10887       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10888       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10889
10890       if ((LLD->hasAnyUseOfValue(1) &&
10891            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10892           (RLD->hasAnyUseOfValue(1) &&
10893            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10894         return false;
10895
10896       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10897                          LLD->getBasePtr().getValueType(),
10898                          TheSelect->getOperand(0),
10899                          TheSelect->getOperand(1),
10900                          LLD->getBasePtr(), RLD->getBasePtr(),
10901                          TheSelect->getOperand(4));
10902     }
10903
10904     SDValue Load;
10905     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10906       Load = DAG.getLoad(TheSelect->getValueType(0),
10907                          SDLoc(TheSelect),
10908                          // FIXME: Discards pointer and TBAA info.
10909                          LLD->getChain(), Addr, MachinePointerInfo(),
10910                          LLD->isVolatile(), LLD->isNonTemporal(),
10911                          LLD->isInvariant(), LLD->getAlignment());
10912     } else {
10913       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10914                             RLD->getExtensionType() : LLD->getExtensionType(),
10915                             SDLoc(TheSelect),
10916                             TheSelect->getValueType(0),
10917                             // FIXME: Discards pointer and TBAA info.
10918                             LLD->getChain(), Addr, MachinePointerInfo(),
10919                             LLD->getMemoryVT(), LLD->isVolatile(),
10920                             LLD->isNonTemporal(), LLD->getAlignment());
10921     }
10922
10923     // Users of the select now use the result of the load.
10924     CombineTo(TheSelect, Load);
10925
10926     // Users of the old loads now use the new load's chain.  We know the
10927     // old-load value is dead now.
10928     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10929     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10930     return true;
10931   }
10932
10933   return false;
10934 }
10935
10936 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10937 /// where 'cond' is the comparison specified by CC.
10938 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10939                                       SDValue N2, SDValue N3,
10940                                       ISD::CondCode CC, bool NotExtCompare) {
10941   // (x ? y : y) -> y.
10942   if (N2 == N3) return N2;
10943
10944   EVT VT = N2.getValueType();
10945   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10946   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10947   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10948
10949   // Determine if the condition we're dealing with is constant
10950   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10951                               N0, N1, CC, DL, false);
10952   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10953   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10954
10955   // fold select_cc true, x, y -> x
10956   if (SCCC && !SCCC->isNullValue())
10957     return N2;
10958   // fold select_cc false, x, y -> y
10959   if (SCCC && SCCC->isNullValue())
10960     return N3;
10961
10962   // Check to see if we can simplify the select into an fabs node
10963   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10964     // Allow either -0.0 or 0.0
10965     if (CFP->getValueAPF().isZero()) {
10966       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10967       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10968           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10969           N2 == N3.getOperand(0))
10970         return DAG.getNode(ISD::FABS, DL, VT, N0);
10971
10972       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10973       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10974           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10975           N2.getOperand(0) == N3)
10976         return DAG.getNode(ISD::FABS, DL, VT, N3);
10977     }
10978   }
10979
10980   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10981   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10982   // in it.  This is a win when the constant is not otherwise available because
10983   // it replaces two constant pool loads with one.  We only do this if the FP
10984   // type is known to be legal, because if it isn't, then we are before legalize
10985   // types an we want the other legalization to happen first (e.g. to avoid
10986   // messing with soft float) and if the ConstantFP is not legal, because if
10987   // it is legal, we may not need to store the FP constant in a constant pool.
10988   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10989     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10990       if (TLI.isTypeLegal(N2.getValueType()) &&
10991           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10992            TargetLowering::Legal) &&
10993           // If both constants have multiple uses, then we won't need to do an
10994           // extra load, they are likely around in registers for other users.
10995           (TV->hasOneUse() || FV->hasOneUse())) {
10996         Constant *Elts[] = {
10997           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10998           const_cast<ConstantFP*>(TV->getConstantFPValue())
10999         };
11000         Type *FPTy = Elts[0]->getType();
11001         const DataLayout &TD = *TLI.getDataLayout();
11002
11003         // Create a ConstantArray of the two constants.
11004         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11005         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11006                                             TD.getPrefTypeAlignment(FPTy));
11007         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11008
11009         // Get the offsets to the 0 and 1 element of the array so that we can
11010         // select between them.
11011         SDValue Zero = DAG.getIntPtrConstant(0);
11012         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11013         SDValue One = DAG.getIntPtrConstant(EltSize);
11014
11015         SDValue Cond = DAG.getSetCC(DL,
11016                                     getSetCCResultType(N0.getValueType()),
11017                                     N0, N1, CC);
11018         AddToWorkList(Cond.getNode());
11019         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11020                                           Cond, One, Zero);
11021         AddToWorkList(CstOffset.getNode());
11022         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11023                             CstOffset);
11024         AddToWorkList(CPIdx.getNode());
11025         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11026                            MachinePointerInfo::getConstantPool(), false,
11027                            false, false, Alignment);
11028
11029       }
11030     }
11031
11032   // Check to see if we can perform the "gzip trick", transforming
11033   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11034   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11035       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11036        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11037     EVT XType = N0.getValueType();
11038     EVT AType = N2.getValueType();
11039     if (XType.bitsGE(AType)) {
11040       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11041       // single-bit constant.
11042       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11043         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11044         ShCtV = XType.getSizeInBits()-ShCtV-1;
11045         SDValue ShCt = DAG.getConstant(ShCtV,
11046                                        getShiftAmountTy(N0.getValueType()));
11047         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11048                                     XType, N0, ShCt);
11049         AddToWorkList(Shift.getNode());
11050
11051         if (XType.bitsGT(AType)) {
11052           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11053           AddToWorkList(Shift.getNode());
11054         }
11055
11056         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11057       }
11058
11059       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11060                                   XType, N0,
11061                                   DAG.getConstant(XType.getSizeInBits()-1,
11062                                          getShiftAmountTy(N0.getValueType())));
11063       AddToWorkList(Shift.getNode());
11064
11065       if (XType.bitsGT(AType)) {
11066         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11067         AddToWorkList(Shift.getNode());
11068       }
11069
11070       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11071     }
11072   }
11073
11074   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11075   // where y is has a single bit set.
11076   // A plaintext description would be, we can turn the SELECT_CC into an AND
11077   // when the condition can be materialized as an all-ones register.  Any
11078   // single bit-test can be materialized as an all-ones register with
11079   // shift-left and shift-right-arith.
11080   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11081       N0->getValueType(0) == VT &&
11082       N1C && N1C->isNullValue() &&
11083       N2C && N2C->isNullValue()) {
11084     SDValue AndLHS = N0->getOperand(0);
11085     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11086     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11087       // Shift the tested bit over the sign bit.
11088       APInt AndMask = ConstAndRHS->getAPIntValue();
11089       SDValue ShlAmt =
11090         DAG.getConstant(AndMask.countLeadingZeros(),
11091                         getShiftAmountTy(AndLHS.getValueType()));
11092       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11093
11094       // Now arithmetic right shift it all the way over, so the result is either
11095       // all-ones, or zero.
11096       SDValue ShrAmt =
11097         DAG.getConstant(AndMask.getBitWidth()-1,
11098                         getShiftAmountTy(Shl.getValueType()));
11099       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11100
11101       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11102     }
11103   }
11104
11105   // fold select C, 16, 0 -> shl C, 4
11106   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11107     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11108       TargetLowering::ZeroOrOneBooleanContent) {
11109
11110     // If the caller doesn't want us to simplify this into a zext of a compare,
11111     // don't do it.
11112     if (NotExtCompare && N2C->getAPIntValue() == 1)
11113       return SDValue();
11114
11115     // Get a SetCC of the condition
11116     // NOTE: Don't create a SETCC if it's not legal on this target.
11117     if (!LegalOperations ||
11118         TLI.isOperationLegal(ISD::SETCC,
11119           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11120       SDValue Temp, SCC;
11121       // cast from setcc result type to select result type
11122       if (LegalTypes) {
11123         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11124                             N0, N1, CC);
11125         if (N2.getValueType().bitsLT(SCC.getValueType()))
11126           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11127                                         N2.getValueType());
11128         else
11129           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11130                              N2.getValueType(), SCC);
11131       } else {
11132         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11133         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11134                            N2.getValueType(), SCC);
11135       }
11136
11137       AddToWorkList(SCC.getNode());
11138       AddToWorkList(Temp.getNode());
11139
11140       if (N2C->getAPIntValue() == 1)
11141         return Temp;
11142
11143       // shl setcc result by log2 n2c
11144       return DAG.getNode(
11145           ISD::SHL, DL, N2.getValueType(), Temp,
11146           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11147                           getShiftAmountTy(Temp.getValueType())));
11148     }
11149   }
11150
11151   // Check to see if this is the equivalent of setcc
11152   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11153   // otherwise, go ahead with the folds.
11154   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11155     EVT XType = N0.getValueType();
11156     if (!LegalOperations ||
11157         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11158       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11159       if (Res.getValueType() != VT)
11160         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11161       return Res;
11162     }
11163
11164     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11165     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11166         (!LegalOperations ||
11167          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11168       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11169       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11170                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11171                                        getShiftAmountTy(Ctlz.getValueType())));
11172     }
11173     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11174     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11175       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11176                                   XType, DAG.getConstant(0, XType), N0);
11177       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11178       return DAG.getNode(ISD::SRL, DL, XType,
11179                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11180                          DAG.getConstant(XType.getSizeInBits()-1,
11181                                          getShiftAmountTy(XType)));
11182     }
11183     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11184     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11185       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11186                                  DAG.getConstant(XType.getSizeInBits()-1,
11187                                          getShiftAmountTy(N0.getValueType())));
11188       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11189     }
11190   }
11191
11192   // Check to see if this is an integer abs.
11193   // select_cc setg[te] X,  0,  X, -X ->
11194   // select_cc setgt    X, -1,  X, -X ->
11195   // select_cc setl[te] X,  0, -X,  X ->
11196   // select_cc setlt    X,  1, -X,  X ->
11197   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11198   if (N1C) {
11199     ConstantSDNode *SubC = NULL;
11200     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11201          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11202         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11203       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11204     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11205               (N1C->isOne() && CC == ISD::SETLT)) &&
11206              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11207       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11208
11209     EVT XType = N0.getValueType();
11210     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11211       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11212                                   N0,
11213                                   DAG.getConstant(XType.getSizeInBits()-1,
11214                                          getShiftAmountTy(N0.getValueType())));
11215       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11216                                 XType, N0, Shift);
11217       AddToWorkList(Shift.getNode());
11218       AddToWorkList(Add.getNode());
11219       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11220     }
11221   }
11222
11223   return SDValue();
11224 }
11225
11226 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11227 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11228                                    SDValue N1, ISD::CondCode Cond,
11229                                    SDLoc DL, bool foldBooleans) {
11230   TargetLowering::DAGCombinerInfo
11231     DagCombineInfo(DAG, Level, false, this);
11232   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11233 }
11234
11235 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11236 /// return a DAG expression to select that will generate the same value by
11237 /// multiplying by a magic number.  See:
11238 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11239 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11240   std::vector<SDNode*> Built;
11241   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11242
11243   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11244        ii != ee; ++ii)
11245     AddToWorkList(*ii);
11246   return S;
11247 }
11248
11249 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11250 /// return a DAG expression to select that will generate the same value by
11251 /// multiplying by a magic number.  See:
11252 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11253 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11254   std::vector<SDNode*> Built;
11255   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11256
11257   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11258        ii != ee; ++ii)
11259     AddToWorkList(*ii);
11260   return S;
11261 }
11262
11263 /// FindBaseOffset - Return true if base is a frame index, which is known not
11264 // to alias with anything but itself.  Provides base object and offset as
11265 // results.
11266 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11267                            const GlobalValue *&GV, const void *&CV) {
11268   // Assume it is a primitive operation.
11269   Base = Ptr; Offset = 0; GV = 0; CV = 0;
11270
11271   // If it's an adding a simple constant then integrate the offset.
11272   if (Base.getOpcode() == ISD::ADD) {
11273     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11274       Base = Base.getOperand(0);
11275       Offset += C->getZExtValue();
11276     }
11277   }
11278
11279   // Return the underlying GlobalValue, and update the Offset.  Return false
11280   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11281   // by multiple nodes with different offsets.
11282   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11283     GV = G->getGlobal();
11284     Offset += G->getOffset();
11285     return false;
11286   }
11287
11288   // Return the underlying Constant value, and update the Offset.  Return false
11289   // for ConstantSDNodes since the same constant pool entry may be represented
11290   // by multiple nodes with different offsets.
11291   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11292     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11293                                          : (const void *)C->getConstVal();
11294     Offset += C->getOffset();
11295     return false;
11296   }
11297   // If it's any of the following then it can't alias with anything but itself.
11298   return isa<FrameIndexSDNode>(Base);
11299 }
11300
11301 /// isAlias - Return true if there is any possibility that the two addresses
11302 /// overlap.
11303 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11304                           const Value *SrcValue1, int SrcValueOffset1,
11305                           unsigned SrcValueAlign1,
11306                           const MDNode *TBAAInfo1,
11307                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11308                           const Value *SrcValue2, int SrcValueOffset2,
11309                           unsigned SrcValueAlign2,
11310                           const MDNode *TBAAInfo2) const {
11311   // If they are the same then they must be aliases.
11312   if (Ptr1 == Ptr2) return true;
11313
11314   // If they are both volatile then they cannot be reordered.
11315   if (IsVolatile1 && IsVolatile2) return true;
11316
11317   // Gather base node and offset information.
11318   SDValue Base1, Base2;
11319   int64_t Offset1, Offset2;
11320   const GlobalValue *GV1, *GV2;
11321   const void *CV1, *CV2;
11322   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11323   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11324
11325   // If they have a same base address then check to see if they overlap.
11326   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11327     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11328
11329   // It is possible for different frame indices to alias each other, mostly
11330   // when tail call optimization reuses return address slots for arguments.
11331   // To catch this case, look up the actual index of frame indices to compute
11332   // the real alias relationship.
11333   if (isFrameIndex1 && isFrameIndex2) {
11334     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11335     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11336     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11337     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11338   }
11339
11340   // Otherwise, if we know what the bases are, and they aren't identical, then
11341   // we know they cannot alias.
11342   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11343     return false;
11344
11345   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11346   // compared to the size and offset of the access, we may be able to prove they
11347   // do not alias.  This check is conservative for now to catch cases created by
11348   // splitting vector types.
11349   if ((SrcValueAlign1 == SrcValueAlign2) &&
11350       (SrcValueOffset1 != SrcValueOffset2) &&
11351       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11352     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11353     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11354
11355     // There is no overlap between these relatively aligned accesses of similar
11356     // size, return no alias.
11357     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11358       return false;
11359   }
11360
11361   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11362     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11363 #ifndef NDEBUG
11364   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11365       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11366     UseAA = false;
11367 #endif
11368   if (UseAA && SrcValue1 && SrcValue2) {
11369     // Use alias analysis information.
11370     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11371     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11372     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11373     AliasAnalysis::AliasResult AAResult =
11374       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11375                                        UseTBAA ? TBAAInfo1 : 0),
11376                AliasAnalysis::Location(SrcValue2, Overlap2,
11377                                        UseTBAA ? TBAAInfo2 : 0));
11378     if (AAResult == AliasAnalysis::NoAlias)
11379       return false;
11380   }
11381
11382   // Otherwise we have to assume they alias.
11383   return true;
11384 }
11385
11386 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11387   SDValue Ptr0, Ptr1;
11388   int64_t Size0, Size1;
11389   bool IsVolatile0, IsVolatile1;
11390   const Value *SrcValue0, *SrcValue1;
11391   int SrcValueOffset0, SrcValueOffset1;
11392   unsigned SrcValueAlign0, SrcValueAlign1;
11393   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11394   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11395                 SrcValueAlign0, SrcTBAAInfo0);
11396   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11397                 SrcValueAlign1, SrcTBAAInfo1);
11398   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11399                  SrcValueAlign0, SrcTBAAInfo0,
11400                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11401                  SrcValueAlign1, SrcTBAAInfo1);
11402 }
11403
11404 /// FindAliasInfo - Extracts the relevant alias information from the memory
11405 /// node.  Returns true if the operand was a nonvolatile load.
11406 bool DAGCombiner::FindAliasInfo(SDNode *N,
11407                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11408                                 const Value *&SrcValue,
11409                                 int &SrcValueOffset,
11410                                 unsigned &SrcValueAlign,
11411                                 const MDNode *&TBAAInfo) const {
11412   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11413
11414   Ptr = LS->getBasePtr();
11415   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11416   IsVolatile = LS->isVolatile();
11417   SrcValue = LS->getSrcValue();
11418   SrcValueOffset = LS->getSrcValueOffset();
11419   SrcValueAlign = LS->getOriginalAlignment();
11420   TBAAInfo = LS->getTBAAInfo();
11421   return isa<LoadSDNode>(LS) && !IsVolatile;
11422 }
11423
11424 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11425 /// looking for aliasing nodes and adding them to the Aliases vector.
11426 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11427                                    SmallVectorImpl<SDValue> &Aliases) {
11428   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11429   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11430
11431   // Get alias information for node.
11432   SDValue Ptr;
11433   int64_t Size;
11434   bool IsVolatile;
11435   const Value *SrcValue;
11436   int SrcValueOffset;
11437   unsigned SrcValueAlign;
11438   const MDNode *SrcTBAAInfo;
11439   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11440                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11441
11442   // Starting off.
11443   Chains.push_back(OriginalChain);
11444   unsigned Depth = 0;
11445
11446   // Look at each chain and determine if it is an alias.  If so, add it to the
11447   // aliases list.  If not, then continue up the chain looking for the next
11448   // candidate.
11449   while (!Chains.empty()) {
11450     SDValue Chain = Chains.back();
11451     Chains.pop_back();
11452
11453     // For TokenFactor nodes, look at each operand and only continue up the
11454     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11455     // find more and revert to original chain since the xform is unlikely to be
11456     // profitable.
11457     //
11458     // FIXME: The depth check could be made to return the last non-aliasing
11459     // chain we found before we hit a tokenfactor rather than the original
11460     // chain.
11461     if (Depth > 6 || Aliases.size() == 2) {
11462       Aliases.clear();
11463       Aliases.push_back(OriginalChain);
11464       return;
11465     }
11466
11467     // Don't bother if we've been before.
11468     if (!Visited.insert(Chain.getNode()))
11469       continue;
11470
11471     switch (Chain.getOpcode()) {
11472     case ISD::EntryToken:
11473       // Entry token is ideal chain operand, but handled in FindBetterChain.
11474       break;
11475
11476     case ISD::LOAD:
11477     case ISD::STORE: {
11478       // Get alias information for Chain.
11479       SDValue OpPtr;
11480       int64_t OpSize;
11481       bool OpIsVolatile;
11482       const Value *OpSrcValue;
11483       int OpSrcValueOffset;
11484       unsigned OpSrcValueAlign;
11485       const MDNode *OpSrcTBAAInfo;
11486       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11487                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11488                                     OpSrcValueAlign,
11489                                     OpSrcTBAAInfo);
11490
11491       // If chain is alias then stop here.
11492       if (!(IsLoad && IsOpLoad) &&
11493           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11494                   SrcValueAlign, SrcTBAAInfo,
11495                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11496                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11497         Aliases.push_back(Chain);
11498       } else {
11499         // Look further up the chain.
11500         Chains.push_back(Chain.getOperand(0));
11501         ++Depth;
11502       }
11503       break;
11504     }
11505
11506     case ISD::TokenFactor:
11507       // We have to check each of the operands of the token factor for "small"
11508       // token factors, so we queue them up.  Adding the operands to the queue
11509       // (stack) in reverse order maintains the original order and increases the
11510       // likelihood that getNode will find a matching token factor (CSE.)
11511       if (Chain.getNumOperands() > 16) {
11512         Aliases.push_back(Chain);
11513         break;
11514       }
11515       for (unsigned n = Chain.getNumOperands(); n;)
11516         Chains.push_back(Chain.getOperand(--n));
11517       ++Depth;
11518       break;
11519
11520     default:
11521       // For all other instructions we will just have to take what we can get.
11522       Aliases.push_back(Chain);
11523       break;
11524     }
11525   }
11526
11527   // We need to be careful here to also search for aliases through the
11528   // value operand of a store, etc. Consider the following situation:
11529   //   Token1 = ...
11530   //   L1 = load Token1, %52
11531   //   S1 = store Token1, L1, %51
11532   //   L2 = load Token1, %52+8
11533   //   S2 = store Token1, L2, %51+8
11534   //   Token2 = Token(S1, S2)
11535   //   L3 = load Token2, %53
11536   //   S3 = store Token2, L3, %52
11537   //   L4 = load Token2, %53+8
11538   //   S4 = store Token2, L4, %52+8
11539   // If we search for aliases of S3 (which loads address %52), and we look
11540   // only through the chain, then we'll miss the trivial dependence on L1
11541   // (which also loads from %52). We then might change all loads and
11542   // stores to use Token1 as their chain operand, which could result in
11543   // copying %53 into %52 before copying %52 into %51 (which should
11544   // happen first).
11545   //
11546   // The problem is, however, that searching for such data dependencies
11547   // can become expensive, and the cost is not directly related to the
11548   // chain depth. Instead, we'll rule out such configurations here by
11549   // insisting that we've visited all chain users (except for users
11550   // of the original chain, which is not necessary). When doing this,
11551   // we need to look through nodes we don't care about (otherwise, things
11552   // like register copies will interfere with trivial cases).
11553
11554   SmallVector<const SDNode *, 16> Worklist;
11555   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11556        IE = Visited.end(); I != IE; ++I)
11557     if (*I != OriginalChain.getNode())
11558       Worklist.push_back(*I);
11559
11560   while (!Worklist.empty()) {
11561     const SDNode *M = Worklist.pop_back_val();
11562
11563     // We have already visited M, and want to make sure we've visited any uses
11564     // of M that we care about. For uses that we've not visisted, and don't
11565     // care about, queue them to the worklist.
11566
11567     for (SDNode::use_iterator UI = M->use_begin(),
11568          UIE = M->use_end(); UI != UIE; ++UI)
11569       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11570         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11571           // We've not visited this use, and we care about it (it could have an
11572           // ordering dependency with the original node).
11573           Aliases.clear();
11574           Aliases.push_back(OriginalChain);
11575           return;
11576         }
11577
11578         // We've not visited this use, but we don't care about it. Mark it as
11579         // visited and enqueue it to the worklist.
11580         Worklist.push_back(*UI);
11581       }
11582   }
11583 }
11584
11585 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11586 /// for a better chain (aliasing node.)
11587 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11588   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11589
11590   // Accumulate all the aliases to this node.
11591   GatherAllAliases(N, OldChain, Aliases);
11592
11593   // If no operands then chain to entry token.
11594   if (Aliases.size() == 0)
11595     return DAG.getEntryNode();
11596
11597   // If a single operand then chain to it.  We don't need to revisit it.
11598   if (Aliases.size() == 1)
11599     return Aliases[0];
11600
11601   // Construct a custom tailored token factor.
11602   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11603                      &Aliases[0], Aliases.size());
11604 }
11605
11606 // SelectionDAG::Combine - This is the entry point for the file.
11607 //
11608 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11609                            CodeGenOpt::Level OptLevel) {
11610   /// run - This is the main entry point to this class.
11611   ///
11612   DAGCombiner(*this, AA, OptLevel).Run(Level);
11613 }