Convert SelectionDAG::getNode methods to use ArrayRef<SDValue>.
[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 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 #define DEBUG_TYPE "dagcombine"
43
44 STATISTIC(NodesCombined   , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
50
51 namespace {
52   static cl::opt<bool>
53     CombinerAA("combiner-alias-analysis", cl::Hidden,
54                cl::desc("Enable DAG combiner alias-analysis heuristics"));
55
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79 //------------------------------ DAGCombiner ---------------------------------//
80
81   class DAGCombiner {
82     SelectionDAG &DAG;
83     const TargetLowering &TLI;
84     CombineLevel Level;
85     CodeGenOpt::Level OptLevel;
86     bool LegalOperations;
87     bool LegalTypes;
88     bool ForCodeSize;
89
90     // Worklist of all of the nodes that need to be simplified.
91     //
92     // This has the semantics that when adding to the worklist,
93     // the item added must be next to be processed. It should
94     // also only appear once. The naive approach to this takes
95     // linear time.
96     //
97     // To reduce the insert/remove time to logarithmic, we use
98     // a set and a vector to maintain our worklist.
99     //
100     // The set contains the items on the worklist, but does not
101     // maintain the order they should be visited.
102     //
103     // The vector maintains the order nodes should be visited, but may
104     // contain duplicate or removed nodes. When choosing a node to
105     // visit, we pop off the order stack until we find an item that is
106     // also in the contents set. All operations are O(log N).
107     SmallPtrSet<SDNode*, 64> WorkListContents;
108     SmallVector<SDNode*, 64> WorkListOrder;
109
110     // AA - Used for DAG load/store alias analysis.
111     AliasAnalysis &AA;
112
113     /// AddUsersToWorkList - When an instruction is simplified, add all users of
114     /// the instruction to the work lists because they might get more simplified
115     /// now.
116     ///
117     void AddUsersToWorkList(SDNode *N) {
118       for (SDNode *Node : N->uses())
119         AddToWorkList(Node);
120     }
121
122     /// visit - call the node-specific routine that knows how to fold each
123     /// particular type of node.
124     SDValue visit(SDNode *N);
125
126   public:
127     /// AddToWorkList - Add to the work list making sure its instance is at the
128     /// back (next to be processed.)
129     void AddToWorkList(SDNode *N) {
130       WorkListContents.insert(N);
131       WorkListOrder.push_back(N);
132     }
133
134     /// removeFromWorkList - remove all instances of N from the worklist.
135     ///
136     void removeFromWorkList(SDNode *N) {
137       WorkListContents.erase(N);
138     }
139
140     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
141                       bool AddTo = true);
142
143     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144       return CombineTo(N, &Res, 1, AddTo);
145     }
146
147     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
148                       bool AddTo = true) {
149       SDValue To[] = { Res0, Res1 };
150       return CombineTo(N, To, 2, AddTo);
151     }
152
153     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
154
155   private:
156
157     /// SimplifyDemandedBits - Check the specified integer node value to see if
158     /// it can be simplified or if things it uses can be simplified by bit
159     /// propagation.  If so, return true.
160     bool SimplifyDemandedBits(SDValue Op) {
161       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162       APInt Demanded = APInt::getAllOnesValue(BitWidth);
163       return SimplifyDemandedBits(Op, Demanded);
164     }
165
166     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
167
168     bool CombineToPreIndexedLoadStore(SDNode *N);
169     bool CombineToPostIndexedLoadStore(SDNode *N);
170     bool SliceUpLoad(SDNode *N);
171
172     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
173     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
174     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
175     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
176     SDValue PromoteIntBinOp(SDValue Op);
177     SDValue PromoteIntShiftOp(SDValue Op);
178     SDValue PromoteExtend(SDValue Op);
179     bool PromoteLoad(SDValue Op);
180
181     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
182                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
183                          ISD::NodeType ExtType);
184
185     /// combine - call the node-specific routine that knows how to fold each
186     /// particular type of node. If that doesn't do anything, try the
187     /// target-specific DAG combines.
188     SDValue combine(SDNode *N);
189
190     // Visitation implementation - Implement dag node combining for different
191     // node types.  The semantics are as follows:
192     // Return Value:
193     //   SDValue.getNode() == 0 - No change was made
194     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
195     //   otherwise              - N should be replaced by the returned Operand.
196     //
197     SDValue visitTokenFactor(SDNode *N);
198     SDValue visitMERGE_VALUES(SDNode *N);
199     SDValue visitADD(SDNode *N);
200     SDValue visitSUB(SDNode *N);
201     SDValue visitADDC(SDNode *N);
202     SDValue visitSUBC(SDNode *N);
203     SDValue visitADDE(SDNode *N);
204     SDValue visitSUBE(SDNode *N);
205     SDValue visitMUL(SDNode *N);
206     SDValue visitSDIV(SDNode *N);
207     SDValue visitUDIV(SDNode *N);
208     SDValue visitSREM(SDNode *N);
209     SDValue visitUREM(SDNode *N);
210     SDValue visitMULHU(SDNode *N);
211     SDValue visitMULHS(SDNode *N);
212     SDValue visitSMUL_LOHI(SDNode *N);
213     SDValue visitUMUL_LOHI(SDNode *N);
214     SDValue visitSMULO(SDNode *N);
215     SDValue visitUMULO(SDNode *N);
216     SDValue visitSDIVREM(SDNode *N);
217     SDValue visitUDIVREM(SDNode *N);
218     SDValue visitAND(SDNode *N);
219     SDValue visitOR(SDNode *N);
220     SDValue visitXOR(SDNode *N);
221     SDValue SimplifyVBinOp(SDNode *N);
222     SDValue SimplifyVUnaryOp(SDNode *N);
223     SDValue visitSHL(SDNode *N);
224     SDValue visitSRA(SDNode *N);
225     SDValue visitSRL(SDNode *N);
226     SDValue visitRotate(SDNode *N);
227     SDValue visitCTLZ(SDNode *N);
228     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
229     SDValue visitCTTZ(SDNode *N);
230     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
231     SDValue visitCTPOP(SDNode *N);
232     SDValue visitSELECT(SDNode *N);
233     SDValue visitVSELECT(SDNode *N);
234     SDValue visitSELECT_CC(SDNode *N);
235     SDValue visitSETCC(SDNode *N);
236     SDValue visitSIGN_EXTEND(SDNode *N);
237     SDValue visitZERO_EXTEND(SDNode *N);
238     SDValue visitANY_EXTEND(SDNode *N);
239     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
240     SDValue visitTRUNCATE(SDNode *N);
241     SDValue visitBITCAST(SDNode *N);
242     SDValue visitBUILD_PAIR(SDNode *N);
243     SDValue visitFADD(SDNode *N);
244     SDValue visitFSUB(SDNode *N);
245     SDValue visitFMUL(SDNode *N);
246     SDValue visitFMA(SDNode *N);
247     SDValue visitFDIV(SDNode *N);
248     SDValue visitFREM(SDNode *N);
249     SDValue visitFCOPYSIGN(SDNode *N);
250     SDValue visitSINT_TO_FP(SDNode *N);
251     SDValue visitUINT_TO_FP(SDNode *N);
252     SDValue visitFP_TO_SINT(SDNode *N);
253     SDValue visitFP_TO_UINT(SDNode *N);
254     SDValue visitFP_ROUND(SDNode *N);
255     SDValue visitFP_ROUND_INREG(SDNode *N);
256     SDValue visitFP_EXTEND(SDNode *N);
257     SDValue visitFNEG(SDNode *N);
258     SDValue visitFABS(SDNode *N);
259     SDValue visitFCEIL(SDNode *N);
260     SDValue visitFTRUNC(SDNode *N);
261     SDValue visitFFLOOR(SDNode *N);
262     SDValue visitBRCOND(SDNode *N);
263     SDValue visitBR_CC(SDNode *N);
264     SDValue visitLOAD(SDNode *N);
265     SDValue visitSTORE(SDNode *N);
266     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
267     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
268     SDValue visitBUILD_VECTOR(SDNode *N);
269     SDValue visitCONCAT_VECTORS(SDNode *N);
270     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
271     SDValue visitVECTOR_SHUFFLE(SDNode *N);
272     SDValue visitINSERT_SUBVECTOR(SDNode *N);
273
274     SDValue XformToShuffleWithZero(SDNode *N);
275     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
276
277     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
278
279     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
280     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
281     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
282     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
283                              SDValue N3, ISD::CondCode CC,
284                              bool NotExtCompare = false);
285     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
286                           SDLoc DL, bool foldBooleans = true);
287
288     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
289                            SDValue &CC) const;
290     bool isOneUseSetCC(SDValue N) const;
291
292     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
293                                          unsigned HiOp);
294     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296     SDValue BuildSDIV(SDNode *N);
297     SDValue BuildUDIV(SDNode *N);
298     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299                                bool DemandHighBits = true);
300     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302                               SDValue InnerPos, SDValue InnerNeg,
303                               unsigned PosOpcode, unsigned NegOpcode,
304                               SDLoc DL);
305     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306     SDValue ReduceLoadWidth(SDNode *N);
307     SDValue ReduceLoadOpStoreWidth(SDNode *N);
308     SDValue TransformFPLoadStorePair(SDNode *N);
309     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
311
312     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
313
314     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315     /// looking for aliasing nodes and adding them to the Aliases vector.
316     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317                           SmallVectorImpl<SDValue> &Aliases);
318
319     /// isAlias - Return true if there is any possibility that the two addresses
320     /// overlap.
321     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
322
323     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
324     /// looking for a better chain (aliasing node.)
325     SDValue FindBetterChain(SDNode *N, SDValue Chain);
326
327     /// Merge consecutive store operations into a wide store.
328     /// This optimization uses wide integers or vectors when possible.
329     /// \return True if some memory operations were changed.
330     bool MergeConsecutiveStores(StoreSDNode *N);
331
332     /// \brief Try to transform a truncation where C is a constant:
333     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
334     ///
335     /// \p N needs to be a truncation and its first operand an AND. Other
336     /// requirements are checked by the function (e.g. that trunc is
337     /// single-use) and if missed an empty SDValue is returned.
338     SDValue distributeTruncateThroughAnd(SDNode *N);
339
340   public:
341     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
342         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
343           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
344       AttributeSet FnAttrs =
345           DAG.getMachineFunction().getFunction()->getAttributes();
346       ForCodeSize =
347           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
348                                Attribute::OptimizeForSize) ||
349           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
350     }
351
352     /// Run - runs the dag combiner on all nodes in the work list
353     void Run(CombineLevel AtLevel);
354
355     SelectionDAG &getDAG() const { return DAG; }
356
357     /// getShiftAmountTy - Returns a type large enough to hold any valid
358     /// shift amount - before type legalization these can be huge.
359     EVT getShiftAmountTy(EVT LHSTy) {
360       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
361       if (LHSTy.isVector())
362         return LHSTy;
363       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
364                         : TLI.getPointerTy();
365     }
366
367     /// isTypeLegal - This method returns true if we are running before type
368     /// legalization or if the specified VT is legal.
369     bool isTypeLegal(const EVT &VT) {
370       if (!LegalTypes) return true;
371       return TLI.isTypeLegal(VT);
372     }
373
374     /// getSetCCResultType - Convenience wrapper around
375     /// TargetLowering::getSetCCResultType
376     EVT getSetCCResultType(EVT VT) const {
377       return TLI.getSetCCResultType(*DAG.getContext(), VT);
378     }
379   };
380 }
381
382
383 namespace {
384 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
385 /// nodes from the worklist.
386 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
387   DAGCombiner &DC;
388 public:
389   explicit WorkListRemover(DAGCombiner &dc)
390     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
391
392   void NodeDeleted(SDNode *N, SDNode *E) override {
393     DC.removeFromWorkList(N);
394   }
395 };
396 }
397
398 //===----------------------------------------------------------------------===//
399 //  TargetLowering::DAGCombinerInfo implementation
400 //===----------------------------------------------------------------------===//
401
402 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
403   ((DAGCombiner*)DC)->AddToWorkList(N);
404 }
405
406 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
407   ((DAGCombiner*)DC)->removeFromWorkList(N);
408 }
409
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
412   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
413 }
414
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
417   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
418 }
419
420
421 SDValue TargetLowering::DAGCombinerInfo::
422 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
423   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
424 }
425
426 void TargetLowering::DAGCombinerInfo::
427 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
428   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
429 }
430
431 //===----------------------------------------------------------------------===//
432 // Helper Functions
433 //===----------------------------------------------------------------------===//
434
435 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
436 /// specified expression for the same cost as the expression itself, or 2 if we
437 /// can compute the negated form more cheaply than the expression itself.
438 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
439                                const TargetLowering &TLI,
440                                const TargetOptions *Options,
441                                unsigned Depth = 0) {
442   // fneg is removable even if it has multiple uses.
443   if (Op.getOpcode() == ISD::FNEG) return 2;
444
445   // Don't allow anything with multiple uses.
446   if (!Op.hasOneUse()) return 0;
447
448   // Don't recurse exponentially.
449   if (Depth > 6) return 0;
450
451   switch (Op.getOpcode()) {
452   default: return false;
453   case ISD::ConstantFP:
454     // Don't invert constant FP values after legalize.  The negated constant
455     // isn't necessarily legal.
456     return LegalOperations ? 0 : 1;
457   case ISD::FADD:
458     // FIXME: determine better conditions for this xform.
459     if (!Options->UnsafeFPMath) return 0;
460
461     // After operation legalization, it might not be legal to create new FSUBs.
462     if (LegalOperations &&
463         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
464       return 0;
465
466     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
467     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
468                                     Options, Depth + 1))
469       return V;
470     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
471     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
472                               Depth + 1);
473   case ISD::FSUB:
474     // We can't turn -(A-B) into B-A when we honor signed zeros.
475     if (!Options->UnsafeFPMath) return 0;
476
477     // fold (fneg (fsub A, B)) -> (fsub B, A)
478     return 1;
479
480   case ISD::FMUL:
481   case ISD::FDIV:
482     if (Options->HonorSignDependentRoundingFPMath()) return 0;
483
484     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
485     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
486                                     Options, Depth + 1))
487       return V;
488
489     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
490                               Depth + 1);
491
492   case ISD::FP_EXTEND:
493   case ISD::FP_ROUND:
494   case ISD::FSIN:
495     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
496                               Depth + 1);
497   }
498 }
499
500 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
501 /// returns the newly negated expression.
502 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
503                                     bool LegalOperations, unsigned Depth = 0) {
504   // fneg is removable even if it has multiple uses.
505   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
506
507   // Don't allow anything with multiple uses.
508   assert(Op.hasOneUse() && "Unknown reuse!");
509
510   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
511   switch (Op.getOpcode()) {
512   default: llvm_unreachable("Unknown code");
513   case ISD::ConstantFP: {
514     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
515     V.changeSign();
516     return DAG.getConstantFP(V, Op.getValueType());
517   }
518   case ISD::FADD:
519     // FIXME: determine better conditions for this xform.
520     assert(DAG.getTarget().Options.UnsafeFPMath);
521
522     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
523     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
524                            DAG.getTargetLoweringInfo(),
525                            &DAG.getTarget().Options, Depth+1))
526       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
527                          GetNegatedExpression(Op.getOperand(0), DAG,
528                                               LegalOperations, Depth+1),
529                          Op.getOperand(1));
530     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
531     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532                        GetNegatedExpression(Op.getOperand(1), DAG,
533                                             LegalOperations, Depth+1),
534                        Op.getOperand(0));
535   case ISD::FSUB:
536     // We can't turn -(A-B) into B-A when we honor signed zeros.
537     assert(DAG.getTarget().Options.UnsafeFPMath);
538
539     // fold (fneg (fsub 0, B)) -> B
540     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
541       if (N0CFP->getValueAPF().isZero())
542         return Op.getOperand(1);
543
544     // fold (fneg (fsub A, B)) -> (fsub B, A)
545     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                        Op.getOperand(1), Op.getOperand(0));
547
548   case ISD::FMUL:
549   case ISD::FDIV:
550     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
551
552     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
553     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
554                            DAG.getTargetLoweringInfo(),
555                            &DAG.getTarget().Options, Depth+1))
556       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557                          GetNegatedExpression(Op.getOperand(0), DAG,
558                                               LegalOperations, Depth+1),
559                          Op.getOperand(1));
560
561     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
562     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563                        Op.getOperand(0),
564                        GetNegatedExpression(Op.getOperand(1), DAG,
565                                             LegalOperations, Depth+1));
566
567   case ISD::FP_EXTEND:
568   case ISD::FSIN:
569     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
570                        GetNegatedExpression(Op.getOperand(0), DAG,
571                                             LegalOperations, Depth+1));
572   case ISD::FP_ROUND:
573       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
574                          GetNegatedExpression(Op.getOperand(0), DAG,
575                                               LegalOperations, Depth+1),
576                          Op.getOperand(1));
577   }
578 }
579
580 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
581 // that selects between the target values used for true and false, making it
582 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
583 // the appropriate nodes based on the type of node we are checking. This
584 // simplifies life a bit for the callers.
585 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
586                                     SDValue &CC) const {
587   if (N.getOpcode() == ISD::SETCC) {
588     LHS = N.getOperand(0);
589     RHS = N.getOperand(1);
590     CC  = N.getOperand(2);
591     return true;
592   }
593
594   if (N.getOpcode() != ISD::SELECT_CC ||
595       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
596       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
597     return false;
598
599   LHS = N.getOperand(0);
600   RHS = N.getOperand(1);
601   CC  = N.getOperand(4);
602   return true;
603 }
604
605 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
606 // one use.  If this is true, it allows the users to invert the operation for
607 // free when it is profitable to do so.
608 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
609   SDValue N0, N1, N2;
610   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
611     return true;
612   return false;
613 }
614
615 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
616 /// elements are all the same constant or undefined.
617 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
618   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
619   if (!C)
620     return false;
621
622   APInt SplatUndef;
623   unsigned SplatBitSize;
624   bool HasAnyUndefs;
625   EVT EltVT = N->getValueType(0).getVectorElementType();
626   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
627                              HasAnyUndefs) &&
628           EltVT.getSizeInBits() >= SplatBitSize);
629 }
630
631 // \brief Returns the SDNode if it is a constant BuildVector or constant.
632 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
633   if (isa<ConstantSDNode>(N))
634     return N.getNode();
635   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
636   if(BV && BV->isConstant())
637     return BV;
638   return nullptr;
639 }
640
641 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
642 // int.
643 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
644   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
645     return CN;
646
647   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
648     return BV->getConstantSplatValue();
649
650   return nullptr;
651 }
652
653 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
654                                     SDValue N0, SDValue N1) {
655   EVT VT = N0.getValueType();
656   if (N0.getOpcode() == Opc) {
657     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
658       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
659         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
660         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
661         if (!OpNode.getNode())
662           return SDValue();
663         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
664       }
665       if (N0.hasOneUse()) {
666         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
667         // use
668         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
669         if (!OpNode.getNode())
670           return SDValue();
671         AddToWorkList(OpNode.getNode());
672         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
673       }
674     }
675   }
676
677   if (N1.getOpcode() == Opc) {
678     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
679       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
680         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
681         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
682         if (!OpNode.getNode())
683           return SDValue();
684         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
685       }
686       if (N1.hasOneUse()) {
687         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
688         // use
689         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
690         if (!OpNode.getNode())
691           return SDValue();
692         AddToWorkList(OpNode.getNode());
693         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
694       }
695     }
696   }
697
698   return SDValue();
699 }
700
701 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
702                                bool AddTo) {
703   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
704   ++NodesCombined;
705   DEBUG(dbgs() << "\nReplacing.1 ";
706         N->dump(&DAG);
707         dbgs() << "\nWith: ";
708         To[0].getNode()->dump(&DAG);
709         dbgs() << " and " << NumTo-1 << " other values\n";
710         for (unsigned i = 0, e = NumTo; i != e; ++i)
711           assert((!To[i].getNode() ||
712                   N->getValueType(i) == To[i].getValueType()) &&
713                  "Cannot combine value to value of different type!"));
714   WorkListRemover DeadNodes(*this);
715   DAG.ReplaceAllUsesWith(N, To);
716   if (AddTo) {
717     // Push the new nodes and any users onto the worklist
718     for (unsigned i = 0, e = NumTo; i != e; ++i) {
719       if (To[i].getNode()) {
720         AddToWorkList(To[i].getNode());
721         AddUsersToWorkList(To[i].getNode());
722       }
723     }
724   }
725
726   // Finally, if the node is now dead, remove it from the graph.  The node
727   // may not be dead if the replacement process recursively simplified to
728   // something else needing this node.
729   if (N->use_empty()) {
730     // Nodes can be reintroduced into the worklist.  Make sure we do not
731     // process a node that has been replaced.
732     removeFromWorkList(N);
733
734     // Finally, since the node is now dead, remove it from the graph.
735     DAG.DeleteNode(N);
736   }
737   return SDValue(N, 0);
738 }
739
740 void DAGCombiner::
741 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
742   // Replace all uses.  If any nodes become isomorphic to other nodes and
743   // are deleted, make sure to remove them from our worklist.
744   WorkListRemover DeadNodes(*this);
745   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
746
747   // Push the new node and any (possibly new) users onto the worklist.
748   AddToWorkList(TLO.New.getNode());
749   AddUsersToWorkList(TLO.New.getNode());
750
751   // Finally, if the node is now dead, remove it from the graph.  The node
752   // may not be dead if the replacement process recursively simplified to
753   // something else needing this node.
754   if (TLO.Old.getNode()->use_empty()) {
755     removeFromWorkList(TLO.Old.getNode());
756
757     // If the operands of this node are only used by the node, they will now
758     // be dead.  Make sure to visit them first to delete dead nodes early.
759     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
760       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
761         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
762
763     DAG.DeleteNode(TLO.Old.getNode());
764   }
765 }
766
767 /// SimplifyDemandedBits - Check the specified integer node value to see if
768 /// it can be simplified or if things it uses can be simplified by bit
769 /// propagation.  If so, return true.
770 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
771   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
772   APInt KnownZero, KnownOne;
773   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
774     return false;
775
776   // Revisit the node.
777   AddToWorkList(Op.getNode());
778
779   // Replace the old value with the new one.
780   ++NodesCombined;
781   DEBUG(dbgs() << "\nReplacing.2 ";
782         TLO.Old.getNode()->dump(&DAG);
783         dbgs() << "\nWith: ";
784         TLO.New.getNode()->dump(&DAG);
785         dbgs() << '\n');
786
787   CommitTargetLoweringOpt(TLO);
788   return true;
789 }
790
791 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
792   SDLoc dl(Load);
793   EVT VT = Load->getValueType(0);
794   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
795
796   DEBUG(dbgs() << "\nReplacing.9 ";
797         Load->dump(&DAG);
798         dbgs() << "\nWith: ";
799         Trunc.getNode()->dump(&DAG);
800         dbgs() << '\n');
801   WorkListRemover DeadNodes(*this);
802   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
803   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
804   removeFromWorkList(Load);
805   DAG.DeleteNode(Load);
806   AddToWorkList(Trunc.getNode());
807 }
808
809 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
810   Replace = false;
811   SDLoc dl(Op);
812   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
813     EVT MemVT = LD->getMemoryVT();
814     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
815       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
816                                                   : ISD::EXTLOAD)
817       : LD->getExtensionType();
818     Replace = true;
819     return DAG.getExtLoad(ExtType, dl, PVT,
820                           LD->getChain(), LD->getBasePtr(),
821                           MemVT, LD->getMemOperand());
822   }
823
824   unsigned Opc = Op.getOpcode();
825   switch (Opc) {
826   default: break;
827   case ISD::AssertSext:
828     return DAG.getNode(ISD::AssertSext, dl, PVT,
829                        SExtPromoteOperand(Op.getOperand(0), PVT),
830                        Op.getOperand(1));
831   case ISD::AssertZext:
832     return DAG.getNode(ISD::AssertZext, dl, PVT,
833                        ZExtPromoteOperand(Op.getOperand(0), PVT),
834                        Op.getOperand(1));
835   case ISD::Constant: {
836     unsigned ExtOpc =
837       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
838     return DAG.getNode(ExtOpc, dl, PVT, Op);
839   }
840   }
841
842   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
843     return SDValue();
844   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
845 }
846
847 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
848   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
849     return SDValue();
850   EVT OldVT = Op.getValueType();
851   SDLoc dl(Op);
852   bool Replace = false;
853   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
854   if (!NewOp.getNode())
855     return SDValue();
856   AddToWorkList(NewOp.getNode());
857
858   if (Replace)
859     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
861                      DAG.getValueType(OldVT));
862 }
863
864 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
865   EVT OldVT = Op.getValueType();
866   SDLoc dl(Op);
867   bool Replace = false;
868   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
869   if (!NewOp.getNode())
870     return SDValue();
871   AddToWorkList(NewOp.getNode());
872
873   if (Replace)
874     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
876 }
877
878 /// PromoteIntBinOp - Promote the specified integer binary operation if the
879 /// target indicates it is beneficial. e.g. On x86, it's usually better to
880 /// promote i16 operations to i32 since i16 instructions are longer.
881 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
882   if (!LegalOperations)
883     return SDValue();
884
885   EVT VT = Op.getValueType();
886   if (VT.isVector() || !VT.isInteger())
887     return SDValue();
888
889   // If operation type is 'undesirable', e.g. i16 on x86, consider
890   // promoting it.
891   unsigned Opc = Op.getOpcode();
892   if (TLI.isTypeDesirableForOp(Opc, VT))
893     return SDValue();
894
895   EVT PVT = VT;
896   // Consult target whether it is a good idea to promote this operation and
897   // what's the right type to promote it to.
898   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
899     assert(PVT != VT && "Don't know what type to promote to!");
900
901     bool Replace0 = false;
902     SDValue N0 = Op.getOperand(0);
903     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
904     if (!NN0.getNode())
905       return SDValue();
906
907     bool Replace1 = false;
908     SDValue N1 = Op.getOperand(1);
909     SDValue NN1;
910     if (N0 == N1)
911       NN1 = NN0;
912     else {
913       NN1 = PromoteOperand(N1, PVT, Replace1);
914       if (!NN1.getNode())
915         return SDValue();
916     }
917
918     AddToWorkList(NN0.getNode());
919     if (NN1.getNode())
920       AddToWorkList(NN1.getNode());
921
922     if (Replace0)
923       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
924     if (Replace1)
925       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
926
927     DEBUG(dbgs() << "\nPromoting ";
928           Op.getNode()->dump(&DAG));
929     SDLoc dl(Op);
930     return DAG.getNode(ISD::TRUNCATE, dl, VT,
931                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
932   }
933   return SDValue();
934 }
935
936 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
937 /// target indicates it is beneficial. e.g. On x86, it's usually better to
938 /// promote i16 operations to i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
940   if (!LegalOperations)
941     return SDValue();
942
943   EVT VT = Op.getValueType();
944   if (VT.isVector() || !VT.isInteger())
945     return SDValue();
946
947   // If operation type is 'undesirable', e.g. i16 on x86, consider
948   // promoting it.
949   unsigned Opc = Op.getOpcode();
950   if (TLI.isTypeDesirableForOp(Opc, VT))
951     return SDValue();
952
953   EVT PVT = VT;
954   // Consult target whether it is a good idea to promote this operation and
955   // what's the right type to promote it to.
956   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957     assert(PVT != VT && "Don't know what type to promote to!");
958
959     bool Replace = false;
960     SDValue N0 = Op.getOperand(0);
961     if (Opc == ISD::SRA)
962       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
963     else if (Opc == ISD::SRL)
964       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
965     else
966       N0 = PromoteOperand(N0, PVT, Replace);
967     if (!N0.getNode())
968       return SDValue();
969
970     AddToWorkList(N0.getNode());
971     if (Replace)
972       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
973
974     DEBUG(dbgs() << "\nPromoting ";
975           Op.getNode()->dump(&DAG));
976     SDLoc dl(Op);
977     return DAG.getNode(ISD::TRUNCATE, dl, VT,
978                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
979   }
980   return SDValue();
981 }
982
983 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
984   if (!LegalOperations)
985     return SDValue();
986
987   EVT VT = Op.getValueType();
988   if (VT.isVector() || !VT.isInteger())
989     return SDValue();
990
991   // If operation type is 'undesirable', e.g. i16 on x86, consider
992   // promoting it.
993   unsigned Opc = Op.getOpcode();
994   if (TLI.isTypeDesirableForOp(Opc, VT))
995     return SDValue();
996
997   EVT PVT = VT;
998   // Consult target whether it is a good idea to promote this operation and
999   // what's the right type to promote it to.
1000   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001     assert(PVT != VT && "Don't know what type to promote to!");
1002     // fold (aext (aext x)) -> (aext x)
1003     // fold (aext (zext x)) -> (zext x)
1004     // fold (aext (sext x)) -> (sext x)
1005     DEBUG(dbgs() << "\nPromoting ";
1006           Op.getNode()->dump(&DAG));
1007     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1008   }
1009   return SDValue();
1010 }
1011
1012 bool DAGCombiner::PromoteLoad(SDValue Op) {
1013   if (!LegalOperations)
1014     return false;
1015
1016   EVT VT = Op.getValueType();
1017   if (VT.isVector() || !VT.isInteger())
1018     return false;
1019
1020   // If operation type is 'undesirable', e.g. i16 on x86, consider
1021   // promoting it.
1022   unsigned Opc = Op.getOpcode();
1023   if (TLI.isTypeDesirableForOp(Opc, VT))
1024     return false;
1025
1026   EVT PVT = VT;
1027   // Consult target whether it is a good idea to promote this operation and
1028   // what's the right type to promote it to.
1029   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1030     assert(PVT != VT && "Don't know what type to promote to!");
1031
1032     SDLoc dl(Op);
1033     SDNode *N = Op.getNode();
1034     LoadSDNode *LD = cast<LoadSDNode>(N);
1035     EVT MemVT = LD->getMemoryVT();
1036     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1037       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1038                                                   : ISD::EXTLOAD)
1039       : LD->getExtensionType();
1040     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1041                                    LD->getChain(), LD->getBasePtr(),
1042                                    MemVT, LD->getMemOperand());
1043     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1044
1045     DEBUG(dbgs() << "\nPromoting ";
1046           N->dump(&DAG);
1047           dbgs() << "\nTo: ";
1048           Result.getNode()->dump(&DAG);
1049           dbgs() << '\n');
1050     WorkListRemover DeadNodes(*this);
1051     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1052     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1053     removeFromWorkList(N);
1054     DAG.DeleteNode(N);
1055     AddToWorkList(Result.getNode());
1056     return true;
1057   }
1058   return false;
1059 }
1060
1061
1062 //===----------------------------------------------------------------------===//
1063 //  Main DAG Combiner implementation
1064 //===----------------------------------------------------------------------===//
1065
1066 void DAGCombiner::Run(CombineLevel AtLevel) {
1067   // set the instance variables, so that the various visit routines may use it.
1068   Level = AtLevel;
1069   LegalOperations = Level >= AfterLegalizeVectorOps;
1070   LegalTypes = Level >= AfterLegalizeTypes;
1071
1072   // Add all the dag nodes to the worklist.
1073   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1074        E = DAG.allnodes_end(); I != E; ++I)
1075     AddToWorkList(I);
1076
1077   // Create a dummy node (which is not added to allnodes), that adds a reference
1078   // to the root node, preventing it from being deleted, and tracking any
1079   // changes of the root.
1080   HandleSDNode Dummy(DAG.getRoot());
1081
1082   // The root of the dag may dangle to deleted nodes until the dag combiner is
1083   // done.  Set it to null to avoid confusion.
1084   DAG.setRoot(SDValue());
1085
1086   // while the worklist isn't empty, find a node and
1087   // try and combine it.
1088   while (!WorkListContents.empty()) {
1089     SDNode *N;
1090     // The WorkListOrder holds the SDNodes in order, but it may contain
1091     // duplicates.
1092     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1093     // worklist *should* contain, and check the node we want to visit is should
1094     // actually be visited.
1095     do {
1096       N = WorkListOrder.pop_back_val();
1097     } while (!WorkListContents.erase(N));
1098
1099     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1100     // N is deleted from the DAG, since they too may now be dead or may have a
1101     // reduced number of uses, allowing other xforms.
1102     if (N->use_empty() && N != &Dummy) {
1103       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104         AddToWorkList(N->getOperand(i).getNode());
1105
1106       DAG.DeleteNode(N);
1107       continue;
1108     }
1109
1110     SDValue RV = combine(N);
1111
1112     if (!RV.getNode())
1113       continue;
1114
1115     ++NodesCombined;
1116
1117     // If we get back the same node we passed in, rather than a new node or
1118     // zero, we know that the node must have defined multiple values and
1119     // CombineTo was used.  Since CombineTo takes care of the worklist
1120     // mechanics for us, we have no work to do in this case.
1121     if (RV.getNode() == N)
1122       continue;
1123
1124     assert(N->getOpcode() != ISD::DELETED_NODE &&
1125            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1126            "Node was deleted but visit returned new node!");
1127
1128     DEBUG(dbgs() << "\nReplacing.3 ";
1129           N->dump(&DAG);
1130           dbgs() << "\nWith: ";
1131           RV.getNode()->dump(&DAG);
1132           dbgs() << '\n');
1133
1134     // Transfer debug value.
1135     DAG.TransferDbgValues(SDValue(N, 0), RV);
1136     WorkListRemover DeadNodes(*this);
1137     if (N->getNumValues() == RV.getNode()->getNumValues())
1138       DAG.ReplaceAllUsesWith(N, RV.getNode());
1139     else {
1140       assert(N->getValueType(0) == RV.getValueType() &&
1141              N->getNumValues() == 1 && "Type mismatch");
1142       SDValue OpV = RV;
1143       DAG.ReplaceAllUsesWith(N, &OpV);
1144     }
1145
1146     // Push the new node and any users onto the worklist
1147     AddToWorkList(RV.getNode());
1148     AddUsersToWorkList(RV.getNode());
1149
1150     // Add any uses of the old node to the worklist in case this node is the
1151     // last one that uses them.  They may become dead after this node is
1152     // deleted.
1153     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1154       AddToWorkList(N->getOperand(i).getNode());
1155
1156     // Finally, if the node is now dead, remove it from the graph.  The node
1157     // may not be dead if the replacement process recursively simplified to
1158     // something else needing this node.
1159     if (N->use_empty()) {
1160       // Nodes can be reintroduced into the worklist.  Make sure we do not
1161       // process a node that has been replaced.
1162       removeFromWorkList(N);
1163
1164       // Finally, since the node is now dead, remove it from the graph.
1165       DAG.DeleteNode(N);
1166     }
1167   }
1168
1169   // If the root changed (e.g. it was a dead load, update the root).
1170   DAG.setRoot(Dummy.getValue());
1171   DAG.RemoveDeadNodes();
1172 }
1173
1174 SDValue DAGCombiner::visit(SDNode *N) {
1175   switch (N->getOpcode()) {
1176   default: break;
1177   case ISD::TokenFactor:        return visitTokenFactor(N);
1178   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1179   case ISD::ADD:                return visitADD(N);
1180   case ISD::SUB:                return visitSUB(N);
1181   case ISD::ADDC:               return visitADDC(N);
1182   case ISD::SUBC:               return visitSUBC(N);
1183   case ISD::ADDE:               return visitADDE(N);
1184   case ISD::SUBE:               return visitSUBE(N);
1185   case ISD::MUL:                return visitMUL(N);
1186   case ISD::SDIV:               return visitSDIV(N);
1187   case ISD::UDIV:               return visitUDIV(N);
1188   case ISD::SREM:               return visitSREM(N);
1189   case ISD::UREM:               return visitUREM(N);
1190   case ISD::MULHU:              return visitMULHU(N);
1191   case ISD::MULHS:              return visitMULHS(N);
1192   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1193   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1194   case ISD::SMULO:              return visitSMULO(N);
1195   case ISD::UMULO:              return visitUMULO(N);
1196   case ISD::SDIVREM:            return visitSDIVREM(N);
1197   case ISD::UDIVREM:            return visitUDIVREM(N);
1198   case ISD::AND:                return visitAND(N);
1199   case ISD::OR:                 return visitOR(N);
1200   case ISD::XOR:                return visitXOR(N);
1201   case ISD::SHL:                return visitSHL(N);
1202   case ISD::SRA:                return visitSRA(N);
1203   case ISD::SRL:                return visitSRL(N);
1204   case ISD::ROTR:
1205   case ISD::ROTL:               return visitRotate(N);
1206   case ISD::CTLZ:               return visitCTLZ(N);
1207   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1208   case ISD::CTTZ:               return visitCTTZ(N);
1209   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1210   case ISD::CTPOP:              return visitCTPOP(N);
1211   case ISD::SELECT:             return visitSELECT(N);
1212   case ISD::VSELECT:            return visitVSELECT(N);
1213   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1214   case ISD::SETCC:              return visitSETCC(N);
1215   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1216   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1217   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1218   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1219   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1220   case ISD::BITCAST:            return visitBITCAST(N);
1221   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1222   case ISD::FADD:               return visitFADD(N);
1223   case ISD::FSUB:               return visitFSUB(N);
1224   case ISD::FMUL:               return visitFMUL(N);
1225   case ISD::FMA:                return visitFMA(N);
1226   case ISD::FDIV:               return visitFDIV(N);
1227   case ISD::FREM:               return visitFREM(N);
1228   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1229   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1230   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1231   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1232   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1233   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1234   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1235   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1236   case ISD::FNEG:               return visitFNEG(N);
1237   case ISD::FABS:               return visitFABS(N);
1238   case ISD::FFLOOR:             return visitFFLOOR(N);
1239   case ISD::FCEIL:              return visitFCEIL(N);
1240   case ISD::FTRUNC:             return visitFTRUNC(N);
1241   case ISD::BRCOND:             return visitBRCOND(N);
1242   case ISD::BR_CC:              return visitBR_CC(N);
1243   case ISD::LOAD:               return visitLOAD(N);
1244   case ISD::STORE:              return visitSTORE(N);
1245   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1246   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1247   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1248   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1249   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1250   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1251   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1252   }
1253   return SDValue();
1254 }
1255
1256 SDValue DAGCombiner::combine(SDNode *N) {
1257   SDValue RV = visit(N);
1258
1259   // If nothing happened, try a target-specific DAG combine.
1260   if (!RV.getNode()) {
1261     assert(N->getOpcode() != ISD::DELETED_NODE &&
1262            "Node was deleted but visit returned NULL!");
1263
1264     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1265         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1266
1267       // Expose the DAG combiner to the target combiner impls.
1268       TargetLowering::DAGCombinerInfo
1269         DagCombineInfo(DAG, Level, false, this);
1270
1271       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1272     }
1273   }
1274
1275   // If nothing happened still, try promoting the operation.
1276   if (!RV.getNode()) {
1277     switch (N->getOpcode()) {
1278     default: break;
1279     case ISD::ADD:
1280     case ISD::SUB:
1281     case ISD::MUL:
1282     case ISD::AND:
1283     case ISD::OR:
1284     case ISD::XOR:
1285       RV = PromoteIntBinOp(SDValue(N, 0));
1286       break;
1287     case ISD::SHL:
1288     case ISD::SRA:
1289     case ISD::SRL:
1290       RV = PromoteIntShiftOp(SDValue(N, 0));
1291       break;
1292     case ISD::SIGN_EXTEND:
1293     case ISD::ZERO_EXTEND:
1294     case ISD::ANY_EXTEND:
1295       RV = PromoteExtend(SDValue(N, 0));
1296       break;
1297     case ISD::LOAD:
1298       if (PromoteLoad(SDValue(N, 0)))
1299         RV = SDValue(N, 0);
1300       break;
1301     }
1302   }
1303
1304   // If N is a commutative binary node, try commuting it to enable more
1305   // sdisel CSE.
1306   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1307       N->getNumValues() == 1) {
1308     SDValue N0 = N->getOperand(0);
1309     SDValue N1 = N->getOperand(1);
1310
1311     // Constant operands are canonicalized to RHS.
1312     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1313       SDValue Ops[] = { N1, N0 };
1314       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1315                                             Ops, 2);
1316       if (CSENode)
1317         return SDValue(CSENode, 0);
1318     }
1319   }
1320
1321   return RV;
1322 }
1323
1324 /// getInputChainForNode - Given a node, return its input chain if it has one,
1325 /// otherwise return a null sd operand.
1326 static SDValue getInputChainForNode(SDNode *N) {
1327   if (unsigned NumOps = N->getNumOperands()) {
1328     if (N->getOperand(0).getValueType() == MVT::Other)
1329       return N->getOperand(0);
1330     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1331       return N->getOperand(NumOps-1);
1332     for (unsigned i = 1; i < NumOps-1; ++i)
1333       if (N->getOperand(i).getValueType() == MVT::Other)
1334         return N->getOperand(i);
1335   }
1336   return SDValue();
1337 }
1338
1339 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1340   // If N has two operands, where one has an input chain equal to the other,
1341   // the 'other' chain is redundant.
1342   if (N->getNumOperands() == 2) {
1343     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1344       return N->getOperand(0);
1345     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1346       return N->getOperand(1);
1347   }
1348
1349   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1350   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1351   SmallPtrSet<SDNode*, 16> SeenOps;
1352   bool Changed = false;             // If we should replace this token factor.
1353
1354   // Start out with this token factor.
1355   TFs.push_back(N);
1356
1357   // Iterate through token factors.  The TFs grows when new token factors are
1358   // encountered.
1359   for (unsigned i = 0; i < TFs.size(); ++i) {
1360     SDNode *TF = TFs[i];
1361
1362     // Check each of the operands.
1363     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1364       SDValue Op = TF->getOperand(i);
1365
1366       switch (Op.getOpcode()) {
1367       case ISD::EntryToken:
1368         // Entry tokens don't need to be added to the list. They are
1369         // rededundant.
1370         Changed = true;
1371         break;
1372
1373       case ISD::TokenFactor:
1374         if (Op.hasOneUse() &&
1375             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1376           // Queue up for processing.
1377           TFs.push_back(Op.getNode());
1378           // Clean up in case the token factor is removed.
1379           AddToWorkList(Op.getNode());
1380           Changed = true;
1381           break;
1382         }
1383         // Fall thru
1384
1385       default:
1386         // Only add if it isn't already in the list.
1387         if (SeenOps.insert(Op.getNode()))
1388           Ops.push_back(Op);
1389         else
1390           Changed = true;
1391         break;
1392       }
1393     }
1394   }
1395
1396   SDValue Result;
1397
1398   // If we've change things around then replace token factor.
1399   if (Changed) {
1400     if (Ops.empty()) {
1401       // The entry token is the only possible outcome.
1402       Result = DAG.getEntryNode();
1403     } else {
1404       // New and improved token factor.
1405       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1406     }
1407
1408     // Don't add users to work list.
1409     return CombineTo(N, Result, false);
1410   }
1411
1412   return Result;
1413 }
1414
1415 /// MERGE_VALUES can always be eliminated.
1416 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1417   WorkListRemover DeadNodes(*this);
1418   // Replacing results may cause a different MERGE_VALUES to suddenly
1419   // be CSE'd with N, and carry its uses with it. Iterate until no
1420   // uses remain, to ensure that the node can be safely deleted.
1421   // First add the users of this node to the work list so that they
1422   // can be tried again once they have new operands.
1423   AddUsersToWorkList(N);
1424   do {
1425     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1426       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1427   } while (!N->use_empty());
1428   removeFromWorkList(N);
1429   DAG.DeleteNode(N);
1430   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1431 }
1432
1433 static
1434 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1435                               SelectionDAG &DAG) {
1436   EVT VT = N0.getValueType();
1437   SDValue N00 = N0.getOperand(0);
1438   SDValue N01 = N0.getOperand(1);
1439   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1440
1441   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1442       isa<ConstantSDNode>(N00.getOperand(1))) {
1443     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1444     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1445                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1446                                  N00.getOperand(0), N01),
1447                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1448                                  N00.getOperand(1), N01));
1449     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1450   }
1451
1452   return SDValue();
1453 }
1454
1455 SDValue DAGCombiner::visitADD(SDNode *N) {
1456   SDValue N0 = N->getOperand(0);
1457   SDValue N1 = N->getOperand(1);
1458   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1460   EVT VT = N0.getValueType();
1461
1462   // fold vector ops
1463   if (VT.isVector()) {
1464     SDValue FoldedVOp = SimplifyVBinOp(N);
1465     if (FoldedVOp.getNode()) return FoldedVOp;
1466
1467     // fold (add x, 0) -> x, vector edition
1468     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1469       return N0;
1470     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1471       return N1;
1472   }
1473
1474   // fold (add x, undef) -> undef
1475   if (N0.getOpcode() == ISD::UNDEF)
1476     return N0;
1477   if (N1.getOpcode() == ISD::UNDEF)
1478     return N1;
1479   // fold (add c1, c2) -> c1+c2
1480   if (N0C && N1C)
1481     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1482   // canonicalize constant to RHS
1483   if (N0C && !N1C)
1484     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1485   // fold (add x, 0) -> x
1486   if (N1C && N1C->isNullValue())
1487     return N0;
1488   // fold (add Sym, c) -> Sym+c
1489   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1490     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1491         GA->getOpcode() == ISD::GlobalAddress)
1492       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1493                                   GA->getOffset() +
1494                                     (uint64_t)N1C->getSExtValue());
1495   // fold ((c1-A)+c2) -> (c1+c2)-A
1496   if (N1C && N0.getOpcode() == ISD::SUB)
1497     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1498       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1499                          DAG.getConstant(N1C->getAPIntValue()+
1500                                          N0C->getAPIntValue(), VT),
1501                          N0.getOperand(1));
1502   // reassociate add
1503   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1504   if (RADD.getNode())
1505     return RADD;
1506   // fold ((0-A) + B) -> B-A
1507   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1508       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1509     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1510   // fold (A + (0-B)) -> A-B
1511   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1512       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1513     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1514   // fold (A+(B-A)) -> B
1515   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1516     return N1.getOperand(0);
1517   // fold ((B-A)+A) -> B
1518   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1519     return N0.getOperand(0);
1520   // fold (A+(B-(A+C))) to (B-C)
1521   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1522       N0 == N1.getOperand(1).getOperand(0))
1523     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1524                        N1.getOperand(1).getOperand(1));
1525   // fold (A+(B-(C+A))) to (B-C)
1526   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1527       N0 == N1.getOperand(1).getOperand(1))
1528     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1529                        N1.getOperand(1).getOperand(0));
1530   // fold (A+((B-A)+or-C)) to (B+or-C)
1531   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1532       N1.getOperand(0).getOpcode() == ISD::SUB &&
1533       N0 == N1.getOperand(0).getOperand(1))
1534     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1535                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1536
1537   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1538   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1539     SDValue N00 = N0.getOperand(0);
1540     SDValue N01 = N0.getOperand(1);
1541     SDValue N10 = N1.getOperand(0);
1542     SDValue N11 = N1.getOperand(1);
1543
1544     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1545       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1546                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1547                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1548   }
1549
1550   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1551     return SDValue(N, 0);
1552
1553   // fold (a+b) -> (a|b) iff a and b share no bits.
1554   if (VT.isInteger() && !VT.isVector()) {
1555     APInt LHSZero, LHSOne;
1556     APInt RHSZero, RHSOne;
1557     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1558
1559     if (LHSZero.getBoolValue()) {
1560       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1561
1562       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1563       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1564       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1565         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1566           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1567       }
1568     }
1569   }
1570
1571   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1572   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1573     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1574     if (Result.getNode()) return Result;
1575   }
1576   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1577     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1578     if (Result.getNode()) return Result;
1579   }
1580
1581   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1582   if (N1.getOpcode() == ISD::SHL &&
1583       N1.getOperand(0).getOpcode() == ISD::SUB)
1584     if (ConstantSDNode *C =
1585           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1586       if (C->getAPIntValue() == 0)
1587         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1588                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1589                                        N1.getOperand(0).getOperand(1),
1590                                        N1.getOperand(1)));
1591   if (N0.getOpcode() == ISD::SHL &&
1592       N0.getOperand(0).getOpcode() == ISD::SUB)
1593     if (ConstantSDNode *C =
1594           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1595       if (C->getAPIntValue() == 0)
1596         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1597                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1598                                        N0.getOperand(0).getOperand(1),
1599                                        N0.getOperand(1)));
1600
1601   if (N1.getOpcode() == ISD::AND) {
1602     SDValue AndOp0 = N1.getOperand(0);
1603     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1604     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1605     unsigned DestBits = VT.getScalarType().getSizeInBits();
1606
1607     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1608     // and similar xforms where the inner op is either ~0 or 0.
1609     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1610       SDLoc DL(N);
1611       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1612     }
1613   }
1614
1615   // add (sext i1), X -> sub X, (zext i1)
1616   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1617       N0.getOperand(0).getValueType() == MVT::i1 &&
1618       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1619     SDLoc DL(N);
1620     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1621     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1622   }
1623
1624   return SDValue();
1625 }
1626
1627 SDValue DAGCombiner::visitADDC(SDNode *N) {
1628   SDValue N0 = N->getOperand(0);
1629   SDValue N1 = N->getOperand(1);
1630   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1631   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1632   EVT VT = N0.getValueType();
1633
1634   // If the flag result is dead, turn this into an ADD.
1635   if (!N->hasAnyUseOfValue(1))
1636     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1637                      DAG.getNode(ISD::CARRY_FALSE,
1638                                  SDLoc(N), MVT::Glue));
1639
1640   // canonicalize constant to RHS.
1641   if (N0C && !N1C)
1642     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1643
1644   // fold (addc x, 0) -> x + no carry out
1645   if (N1C && N1C->isNullValue())
1646     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1647                                         SDLoc(N), MVT::Glue));
1648
1649   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1650   APInt LHSZero, LHSOne;
1651   APInt RHSZero, RHSOne;
1652   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1653
1654   if (LHSZero.getBoolValue()) {
1655     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1656
1657     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1658     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1659     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1660       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1661                        DAG.getNode(ISD::CARRY_FALSE,
1662                                    SDLoc(N), MVT::Glue));
1663   }
1664
1665   return SDValue();
1666 }
1667
1668 SDValue DAGCombiner::visitADDE(SDNode *N) {
1669   SDValue N0 = N->getOperand(0);
1670   SDValue N1 = N->getOperand(1);
1671   SDValue CarryIn = N->getOperand(2);
1672   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1673   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1674
1675   // canonicalize constant to RHS
1676   if (N0C && !N1C)
1677     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1678                        N1, N0, CarryIn);
1679
1680   // fold (adde x, y, false) -> (addc x, y)
1681   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1682     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1683
1684   return SDValue();
1685 }
1686
1687 // Since it may not be valid to emit a fold to zero for vector initializers
1688 // check if we can before folding.
1689 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1690                              SelectionDAG &DAG,
1691                              bool LegalOperations, bool LegalTypes) {
1692   if (!VT.isVector())
1693     return DAG.getConstant(0, VT);
1694   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1695     return DAG.getConstant(0, VT);
1696   return SDValue();
1697 }
1698
1699 SDValue DAGCombiner::visitSUB(SDNode *N) {
1700   SDValue N0 = N->getOperand(0);
1701   SDValue N1 = N->getOperand(1);
1702   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1703   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1704   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1705     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1706   EVT VT = N0.getValueType();
1707
1708   // fold vector ops
1709   if (VT.isVector()) {
1710     SDValue FoldedVOp = SimplifyVBinOp(N);
1711     if (FoldedVOp.getNode()) return FoldedVOp;
1712
1713     // fold (sub x, 0) -> x, vector edition
1714     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1715       return N0;
1716   }
1717
1718   // fold (sub x, x) -> 0
1719   // FIXME: Refactor this and xor and other similar operations together.
1720   if (N0 == N1)
1721     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1722   // fold (sub c1, c2) -> c1-c2
1723   if (N0C && N1C)
1724     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1725   // fold (sub x, c) -> (add x, -c)
1726   if (N1C)
1727     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1728                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1729   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1730   if (N0C && N0C->isAllOnesValue())
1731     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1732   // fold A-(A-B) -> B
1733   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1734     return N1.getOperand(1);
1735   // fold (A+B)-A -> B
1736   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1737     return N0.getOperand(1);
1738   // fold (A+B)-B -> A
1739   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1740     return N0.getOperand(0);
1741   // fold C2-(A+C1) -> (C2-C1)-A
1742   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1743     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1744                                    VT);
1745     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1746                        N1.getOperand(0));
1747   }
1748   // fold ((A+(B+or-C))-B) -> A+or-C
1749   if (N0.getOpcode() == ISD::ADD &&
1750       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1751        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1752       N0.getOperand(1).getOperand(0) == N1)
1753     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1754                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1755   // fold ((A+(C+B))-B) -> A+C
1756   if (N0.getOpcode() == ISD::ADD &&
1757       N0.getOperand(1).getOpcode() == ISD::ADD &&
1758       N0.getOperand(1).getOperand(1) == N1)
1759     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1760                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1761   // fold ((A-(B-C))-C) -> A-B
1762   if (N0.getOpcode() == ISD::SUB &&
1763       N0.getOperand(1).getOpcode() == ISD::SUB &&
1764       N0.getOperand(1).getOperand(1) == N1)
1765     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1766                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1767
1768   // If either operand of a sub is undef, the result is undef
1769   if (N0.getOpcode() == ISD::UNDEF)
1770     return N0;
1771   if (N1.getOpcode() == ISD::UNDEF)
1772     return N1;
1773
1774   // If the relocation model supports it, consider symbol offsets.
1775   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1776     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1777       // fold (sub Sym, c) -> Sym-c
1778       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1779         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1780                                     GA->getOffset() -
1781                                       (uint64_t)N1C->getSExtValue());
1782       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1783       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1784         if (GA->getGlobal() == GB->getGlobal())
1785           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1786                                  VT);
1787     }
1788
1789   return SDValue();
1790 }
1791
1792 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1793   SDValue N0 = N->getOperand(0);
1794   SDValue N1 = N->getOperand(1);
1795   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1796   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1797   EVT VT = N0.getValueType();
1798
1799   // If the flag result is dead, turn this into an SUB.
1800   if (!N->hasAnyUseOfValue(1))
1801     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1802                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1803                                  MVT::Glue));
1804
1805   // fold (subc x, x) -> 0 + no borrow
1806   if (N0 == N1)
1807     return CombineTo(N, DAG.getConstant(0, VT),
1808                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1809                                  MVT::Glue));
1810
1811   // fold (subc x, 0) -> x + no borrow
1812   if (N1C && N1C->isNullValue())
1813     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1814                                         MVT::Glue));
1815
1816   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1817   if (N0C && N0C->isAllOnesValue())
1818     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1819                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1820                                  MVT::Glue));
1821
1822   return SDValue();
1823 }
1824
1825 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1826   SDValue N0 = N->getOperand(0);
1827   SDValue N1 = N->getOperand(1);
1828   SDValue CarryIn = N->getOperand(2);
1829
1830   // fold (sube x, y, false) -> (subc x, y)
1831   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1832     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1833
1834   return SDValue();
1835 }
1836
1837 SDValue DAGCombiner::visitMUL(SDNode *N) {
1838   SDValue N0 = N->getOperand(0);
1839   SDValue N1 = N->getOperand(1);
1840   EVT VT = N0.getValueType();
1841
1842   // fold (mul x, undef) -> 0
1843   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1844     return DAG.getConstant(0, VT);
1845
1846   bool N0IsConst = false;
1847   bool N1IsConst = false;
1848   APInt ConstValue0, ConstValue1;
1849   // fold vector ops
1850   if (VT.isVector()) {
1851     SDValue FoldedVOp = SimplifyVBinOp(N);
1852     if (FoldedVOp.getNode()) return FoldedVOp;
1853
1854     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1855     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1856   } else {
1857     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1858     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1859                             : APInt();
1860     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1861     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1862                             : APInt();
1863   }
1864
1865   // fold (mul c1, c2) -> c1*c2
1866   if (N0IsConst && N1IsConst)
1867     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1868
1869   // canonicalize constant to RHS
1870   if (N0IsConst && !N1IsConst)
1871     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1872   // fold (mul x, 0) -> 0
1873   if (N1IsConst && ConstValue1 == 0)
1874     return N1;
1875   // We require a splat of the entire scalar bit width for non-contiguous
1876   // bit patterns.
1877   bool IsFullSplat =
1878     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1879   // fold (mul x, 1) -> x
1880   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1881     return N0;
1882   // fold (mul x, -1) -> 0-x
1883   if (N1IsConst && ConstValue1.isAllOnesValue())
1884     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1885                        DAG.getConstant(0, VT), N0);
1886   // fold (mul x, (1 << c)) -> x << c
1887   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1888     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1889                        DAG.getConstant(ConstValue1.logBase2(),
1890                                        getShiftAmountTy(N0.getValueType())));
1891   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1892   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1893     unsigned Log2Val = (-ConstValue1).logBase2();
1894     // FIXME: If the input is something that is easily negated (e.g. a
1895     // single-use add), we should put the negate there.
1896     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897                        DAG.getConstant(0, VT),
1898                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1899                             DAG.getConstant(Log2Val,
1900                                       getShiftAmountTy(N0.getValueType()))));
1901   }
1902
1903   APInt Val;
1904   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1905   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1906       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1907                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1908     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1909                              N1, N0.getOperand(1));
1910     AddToWorkList(C3.getNode());
1911     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1912                        N0.getOperand(0), C3);
1913   }
1914
1915   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1916   // use.
1917   {
1918     SDValue Sh(nullptr,0), Y(nullptr,0);
1919     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1920     if (N0.getOpcode() == ISD::SHL &&
1921         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1923         N0.getNode()->hasOneUse()) {
1924       Sh = N0; Y = N1;
1925     } else if (N1.getOpcode() == ISD::SHL &&
1926                isa<ConstantSDNode>(N1.getOperand(1)) &&
1927                N1.getNode()->hasOneUse()) {
1928       Sh = N1; Y = N0;
1929     }
1930
1931     if (Sh.getNode()) {
1932       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933                                 Sh.getOperand(0), Y);
1934       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935                          Mul, Sh.getOperand(1));
1936     }
1937   }
1938
1939   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1940   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1941       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1942                      isa<ConstantSDNode>(N0.getOperand(1))))
1943     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1944                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1945                                    N0.getOperand(0), N1),
1946                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1947                                    N0.getOperand(1), N1));
1948
1949   // reassociate mul
1950   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1951   if (RMUL.getNode())
1952     return RMUL;
1953
1954   return SDValue();
1955 }
1956
1957 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1958   SDValue N0 = N->getOperand(0);
1959   SDValue N1 = N->getOperand(1);
1960   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1961   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1962   EVT VT = N->getValueType(0);
1963
1964   // fold vector ops
1965   if (VT.isVector()) {
1966     SDValue FoldedVOp = SimplifyVBinOp(N);
1967     if (FoldedVOp.getNode()) return FoldedVOp;
1968   }
1969
1970   // fold (sdiv c1, c2) -> c1/c2
1971   if (N0C && N1C && !N1C->isNullValue())
1972     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1973   // fold (sdiv X, 1) -> X
1974   if (N1C && N1C->getAPIntValue() == 1LL)
1975     return N0;
1976   // fold (sdiv X, -1) -> 0-X
1977   if (N1C && N1C->isAllOnesValue())
1978     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979                        DAG.getConstant(0, VT), N0);
1980   // If we know the sign bits of both operands are zero, strength reduce to a
1981   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1982   if (!VT.isVector()) {
1983     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1984       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1985                          N0, N1);
1986   }
1987
1988   const APInt *Divisor = nullptr;
1989   if (N1C) {
1990     Divisor = &N1C->getAPIntValue();
1991   } else if (N1.getValueType().isVector() &&
1992              N1->getOpcode() == ISD::BUILD_VECTOR) {
1993     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
1994     if (ConstantSDNode *C = BV->getConstantSplatValue())
1995       Divisor = &C->getAPIntValue();
1996   }
1997
1998   // fold (sdiv X, pow2) -> simple ops after legalize
1999   if (Divisor && !!*Divisor &&
2000       (Divisor->isPowerOf2() || (-*Divisor).isPowerOf2())) {
2001     // If dividing by powers of two is cheap, then don't perform the following
2002     // fold.
2003     if (TLI.isPow2DivCheap())
2004       return SDValue();
2005
2006     unsigned lg2 = Divisor->countTrailingZeros();
2007
2008     // Splat the sign bit into the register
2009     SDValue SGN =
2010         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2011                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2012                                     getShiftAmountTy(N0.getValueType())));
2013     AddToWorkList(SGN.getNode());
2014
2015     // Add (N0 < 0) ? abs2 - 1 : 0;
2016     SDValue SRL =
2017         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2018                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2019                                     getShiftAmountTy(SGN.getValueType())));
2020     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2021     AddToWorkList(SRL.getNode());
2022     AddToWorkList(ADD.getNode());    // Divide by pow2
2023     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2024                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2025
2026     // If we're dividing by a positive value, we're done.  Otherwise, we must
2027     // negate the result.
2028     if (Divisor->isNonNegative())
2029       return SRA;
2030
2031     AddToWorkList(SRA.getNode());
2032     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2033   }
2034
2035   // if integer divide is expensive and we satisfy the requirements, emit an
2036   // alternate sequence.
2037   if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2038     SDValue Op = BuildSDIV(N);
2039     if (Op.getNode()) return Op;
2040   }
2041
2042   // undef / X -> 0
2043   if (N0.getOpcode() == ISD::UNDEF)
2044     return DAG.getConstant(0, VT);
2045   // X / undef -> undef
2046   if (N1.getOpcode() == ISD::UNDEF)
2047     return N1;
2048
2049   return SDValue();
2050 }
2051
2052 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2053   SDValue N0 = N->getOperand(0);
2054   SDValue N1 = N->getOperand(1);
2055   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2056   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2057   EVT VT = N->getValueType(0);
2058
2059   // fold vector ops
2060   if (VT.isVector()) {
2061     SDValue FoldedVOp = SimplifyVBinOp(N);
2062     if (FoldedVOp.getNode()) return FoldedVOp;
2063   }
2064
2065   // fold (udiv c1, c2) -> c1/c2
2066   if (N0C && N1C && !N1C->isNullValue())
2067     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2068   // fold (udiv x, (1 << c)) -> x >>u c
2069   if (N1C && N1C->getAPIntValue().isPowerOf2())
2070     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2071                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2072                                        getShiftAmountTy(N0.getValueType())));
2073   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2074   if (N1.getOpcode() == ISD::SHL) {
2075     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2076       if (SHC->getAPIntValue().isPowerOf2()) {
2077         EVT ADDVT = N1.getOperand(1).getValueType();
2078         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2079                                   N1.getOperand(1),
2080                                   DAG.getConstant(SHC->getAPIntValue()
2081                                                                   .logBase2(),
2082                                                   ADDVT));
2083         AddToWorkList(Add.getNode());
2084         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2085       }
2086     }
2087   }
2088   // fold (udiv x, c) -> alternate
2089   if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2090     SDValue Op = BuildUDIV(N);
2091     if (Op.getNode()) return Op;
2092   }
2093
2094   // undef / X -> 0
2095   if (N0.getOpcode() == ISD::UNDEF)
2096     return DAG.getConstant(0, VT);
2097   // X / undef -> undef
2098   if (N1.getOpcode() == ISD::UNDEF)
2099     return N1;
2100
2101   return SDValue();
2102 }
2103
2104 SDValue DAGCombiner::visitSREM(SDNode *N) {
2105   SDValue N0 = N->getOperand(0);
2106   SDValue N1 = N->getOperand(1);
2107   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2108   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2109   EVT VT = N->getValueType(0);
2110
2111   // fold (srem c1, c2) -> c1%c2
2112   if (N0C && N1C && !N1C->isNullValue())
2113     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2114   // If we know the sign bits of both operands are zero, strength reduce to a
2115   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2116   if (!VT.isVector()) {
2117     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2118       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2119   }
2120
2121   // If X/C can be simplified by the division-by-constant logic, lower
2122   // X%C to the equivalent of X-X/C*C.
2123   if (N1C && !N1C->isNullValue()) {
2124     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2125     AddToWorkList(Div.getNode());
2126     SDValue OptimizedDiv = combine(Div.getNode());
2127     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2128       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2129                                 OptimizedDiv, N1);
2130       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2131       AddToWorkList(Mul.getNode());
2132       return Sub;
2133     }
2134   }
2135
2136   // undef % X -> 0
2137   if (N0.getOpcode() == ISD::UNDEF)
2138     return DAG.getConstant(0, VT);
2139   // X % undef -> undef
2140   if (N1.getOpcode() == ISD::UNDEF)
2141     return N1;
2142
2143   return SDValue();
2144 }
2145
2146 SDValue DAGCombiner::visitUREM(SDNode *N) {
2147   SDValue N0 = N->getOperand(0);
2148   SDValue N1 = N->getOperand(1);
2149   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2150   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2151   EVT VT = N->getValueType(0);
2152
2153   // fold (urem c1, c2) -> c1%c2
2154   if (N0C && N1C && !N1C->isNullValue())
2155     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2156   // fold (urem x, pow2) -> (and x, pow2-1)
2157   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2158     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2159                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2160   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2161   if (N1.getOpcode() == ISD::SHL) {
2162     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2163       if (SHC->getAPIntValue().isPowerOf2()) {
2164         SDValue Add =
2165           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2166                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2167                                  VT));
2168         AddToWorkList(Add.getNode());
2169         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2170       }
2171     }
2172   }
2173
2174   // If X/C can be simplified by the division-by-constant logic, lower
2175   // X%C to the equivalent of X-X/C*C.
2176   if (N1C && !N1C->isNullValue()) {
2177     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2178     AddToWorkList(Div.getNode());
2179     SDValue OptimizedDiv = combine(Div.getNode());
2180     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2181       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2182                                 OptimizedDiv, N1);
2183       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2184       AddToWorkList(Mul.getNode());
2185       return Sub;
2186     }
2187   }
2188
2189   // undef % X -> 0
2190   if (N0.getOpcode() == ISD::UNDEF)
2191     return DAG.getConstant(0, VT);
2192   // X % undef -> undef
2193   if (N1.getOpcode() == ISD::UNDEF)
2194     return N1;
2195
2196   return SDValue();
2197 }
2198
2199 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2200   SDValue N0 = N->getOperand(0);
2201   SDValue N1 = N->getOperand(1);
2202   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2203   EVT VT = N->getValueType(0);
2204   SDLoc DL(N);
2205
2206   // fold (mulhs x, 0) -> 0
2207   if (N1C && N1C->isNullValue())
2208     return N1;
2209   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2210   if (N1C && N1C->getAPIntValue() == 1)
2211     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2212                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2213                                        getShiftAmountTy(N0.getValueType())));
2214   // fold (mulhs x, undef) -> 0
2215   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2216     return DAG.getConstant(0, VT);
2217
2218   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2219   // plus a shift.
2220   if (VT.isSimple() && !VT.isVector()) {
2221     MVT Simple = VT.getSimpleVT();
2222     unsigned SimpleSize = Simple.getSizeInBits();
2223     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2224     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2225       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2226       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2227       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2228       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2229             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2230       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2231     }
2232   }
2233
2234   return SDValue();
2235 }
2236
2237 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2238   SDValue N0 = N->getOperand(0);
2239   SDValue N1 = N->getOperand(1);
2240   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2241   EVT VT = N->getValueType(0);
2242   SDLoc DL(N);
2243
2244   // fold (mulhu x, 0) -> 0
2245   if (N1C && N1C->isNullValue())
2246     return N1;
2247   // fold (mulhu x, 1) -> 0
2248   if (N1C && N1C->getAPIntValue() == 1)
2249     return DAG.getConstant(0, N0.getValueType());
2250   // fold (mulhu x, undef) -> 0
2251   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2252     return DAG.getConstant(0, VT);
2253
2254   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2255   // plus a shift.
2256   if (VT.isSimple() && !VT.isVector()) {
2257     MVT Simple = VT.getSimpleVT();
2258     unsigned SimpleSize = Simple.getSizeInBits();
2259     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2260     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2261       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2262       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2263       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2264       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2265             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2266       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2267     }
2268   }
2269
2270   return SDValue();
2271 }
2272
2273 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2274 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2275 /// that are being performed. Return true if a simplification was made.
2276 ///
2277 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2278                                                 unsigned HiOp) {
2279   // If the high half is not needed, just compute the low half.
2280   bool HiExists = N->hasAnyUseOfValue(1);
2281   if (!HiExists &&
2282       (!LegalOperations ||
2283        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2284     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2285                               N->op_begin(), N->getNumOperands());
2286     return CombineTo(N, Res, Res);
2287   }
2288
2289   // If the low half is not needed, just compute the high half.
2290   bool LoExists = N->hasAnyUseOfValue(0);
2291   if (!LoExists &&
2292       (!LegalOperations ||
2293        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2294     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2295                               N->op_begin(), N->getNumOperands());
2296     return CombineTo(N, Res, Res);
2297   }
2298
2299   // If both halves are used, return as it is.
2300   if (LoExists && HiExists)
2301     return SDValue();
2302
2303   // If the two computed results can be simplified separately, separate them.
2304   if (LoExists) {
2305     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2306                              N->op_begin(), N->getNumOperands());
2307     AddToWorkList(Lo.getNode());
2308     SDValue LoOpt = combine(Lo.getNode());
2309     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2310         (!LegalOperations ||
2311          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2312       return CombineTo(N, LoOpt, LoOpt);
2313   }
2314
2315   if (HiExists) {
2316     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2317                              N->op_begin(), N->getNumOperands());
2318     AddToWorkList(Hi.getNode());
2319     SDValue HiOpt = combine(Hi.getNode());
2320     if (HiOpt.getNode() && HiOpt != Hi &&
2321         (!LegalOperations ||
2322          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2323       return CombineTo(N, HiOpt, HiOpt);
2324   }
2325
2326   return SDValue();
2327 }
2328
2329 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2330   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2331   if (Res.getNode()) return Res;
2332
2333   EVT VT = N->getValueType(0);
2334   SDLoc DL(N);
2335
2336   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2337   // plus a shift.
2338   if (VT.isSimple() && !VT.isVector()) {
2339     MVT Simple = VT.getSimpleVT();
2340     unsigned SimpleSize = Simple.getSizeInBits();
2341     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2342     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2343       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2344       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2345       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2346       // Compute the high part as N1.
2347       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2348             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2349       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2350       // Compute the low part as N0.
2351       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2352       return CombineTo(N, Lo, Hi);
2353     }
2354   }
2355
2356   return SDValue();
2357 }
2358
2359 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2360   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2361   if (Res.getNode()) return Res;
2362
2363   EVT VT = N->getValueType(0);
2364   SDLoc DL(N);
2365
2366   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2367   // plus a shift.
2368   if (VT.isSimple() && !VT.isVector()) {
2369     MVT Simple = VT.getSimpleVT();
2370     unsigned SimpleSize = Simple.getSizeInBits();
2371     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2372     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2373       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2374       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2375       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2376       // Compute the high part as N1.
2377       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2378             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2379       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2380       // Compute the low part as N0.
2381       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2382       return CombineTo(N, Lo, Hi);
2383     }
2384   }
2385
2386   return SDValue();
2387 }
2388
2389 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2390   // (smulo x, 2) -> (saddo x, x)
2391   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392     if (C2->getAPIntValue() == 2)
2393       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2394                          N->getOperand(0), N->getOperand(0));
2395
2396   return SDValue();
2397 }
2398
2399 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2400   // (umulo x, 2) -> (uaddo x, x)
2401   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2402     if (C2->getAPIntValue() == 2)
2403       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2404                          N->getOperand(0), N->getOperand(0));
2405
2406   return SDValue();
2407 }
2408
2409 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2410   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2411   if (Res.getNode()) return Res;
2412
2413   return SDValue();
2414 }
2415
2416 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2417   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2418   if (Res.getNode()) return Res;
2419
2420   return SDValue();
2421 }
2422
2423 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2424 /// two operands of the same opcode, try to simplify it.
2425 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2426   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2427   EVT VT = N0.getValueType();
2428   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2429
2430   // Bail early if none of these transforms apply.
2431   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2432
2433   // For each of OP in AND/OR/XOR:
2434   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2435   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2436   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2437   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2438   //
2439   // do not sink logical op inside of a vector extend, since it may combine
2440   // into a vsetcc.
2441   EVT Op0VT = N0.getOperand(0).getValueType();
2442   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2443        N0.getOpcode() == ISD::SIGN_EXTEND ||
2444        // Avoid infinite looping with PromoteIntBinOp.
2445        (N0.getOpcode() == ISD::ANY_EXTEND &&
2446         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2447        (N0.getOpcode() == ISD::TRUNCATE &&
2448         (!TLI.isZExtFree(VT, Op0VT) ||
2449          !TLI.isTruncateFree(Op0VT, VT)) &&
2450         TLI.isTypeLegal(Op0VT))) &&
2451       !VT.isVector() &&
2452       Op0VT == N1.getOperand(0).getValueType() &&
2453       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2454     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2455                                  N0.getOperand(0).getValueType(),
2456                                  N0.getOperand(0), N1.getOperand(0));
2457     AddToWorkList(ORNode.getNode());
2458     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2459   }
2460
2461   // For each of OP in SHL/SRL/SRA/AND...
2462   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2463   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2464   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2465   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2466        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2467       N0.getOperand(1) == N1.getOperand(1)) {
2468     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2469                                  N0.getOperand(0).getValueType(),
2470                                  N0.getOperand(0), N1.getOperand(0));
2471     AddToWorkList(ORNode.getNode());
2472     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2473                        ORNode, N0.getOperand(1));
2474   }
2475
2476   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2477   // Only perform this optimization after type legalization and before
2478   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2479   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2480   // we don't want to undo this promotion.
2481   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2482   // on scalars.
2483   if ((N0.getOpcode() == ISD::BITCAST ||
2484        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2485       Level == AfterLegalizeTypes) {
2486     SDValue In0 = N0.getOperand(0);
2487     SDValue In1 = N1.getOperand(0);
2488     EVT In0Ty = In0.getValueType();
2489     EVT In1Ty = In1.getValueType();
2490     SDLoc DL(N);
2491     // If both incoming values are integers, and the original types are the
2492     // same.
2493     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2494       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2495       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2496       AddToWorkList(Op.getNode());
2497       return BC;
2498     }
2499   }
2500
2501   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2502   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2503   // If both shuffles use the same mask, and both shuffle within a single
2504   // vector, then it is worthwhile to move the swizzle after the operation.
2505   // The type-legalizer generates this pattern when loading illegal
2506   // vector types from memory. In many cases this allows additional shuffle
2507   // optimizations.
2508   // There are other cases where moving the shuffle after the xor/and/or
2509   // is profitable even if shuffles don't perform a swizzle.
2510   // If both shuffles use the same mask, and both shuffles have the same first
2511   // or second operand, then it might still be profitable to move the shuffle
2512   // after the xor/and/or operation.
2513   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2514     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2515     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2516
2517     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2518            "Inputs to shuffles are not the same type");
2519  
2520     // Check that both shuffles use the same mask. The masks are known to be of
2521     // the same length because the result vector type is the same.
2522     // Check also that shuffles have only one use to avoid introducing extra
2523     // instructions.
2524     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2525         SVN0->getMask().equals(SVN1->getMask())) {
2526       SDValue ShOp = N0->getOperand(1);
2527
2528       // Don't try to fold this node if it requires introducing a
2529       // build vector of all zeros that might be illegal at this stage.
2530       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2531         if (!LegalTypes)
2532           ShOp = DAG.getConstant(0, VT);
2533         else
2534           ShOp = SDValue();
2535       }
2536
2537       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2538       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2539       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2540       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2541         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2542                                       N0->getOperand(0), N1->getOperand(0));
2543         AddToWorkList(NewNode.getNode());
2544         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2545                                     &SVN0->getMask()[0]);
2546       }
2547
2548       // Don't try to fold this node if it requires introducing a
2549       // build vector of all zeros that might be illegal at this stage.
2550       ShOp = N0->getOperand(0);
2551       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2552         if (!LegalTypes)
2553           ShOp = DAG.getConstant(0, VT);
2554         else
2555           ShOp = SDValue();
2556       }
2557
2558       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2559       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2560       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2561       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2562         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2563                                       N0->getOperand(1), N1->getOperand(1));
2564         AddToWorkList(NewNode.getNode());
2565         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2566                                     &SVN0->getMask()[0]);
2567       }
2568     }
2569   }
2570
2571   return SDValue();
2572 }
2573
2574 SDValue DAGCombiner::visitAND(SDNode *N) {
2575   SDValue N0 = N->getOperand(0);
2576   SDValue N1 = N->getOperand(1);
2577   SDValue LL, LR, RL, RR, CC0, CC1;
2578   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2580   EVT VT = N1.getValueType();
2581   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2582
2583   // fold vector ops
2584   if (VT.isVector()) {
2585     SDValue FoldedVOp = SimplifyVBinOp(N);
2586     if (FoldedVOp.getNode()) return FoldedVOp;
2587
2588     // fold (and x, 0) -> 0, vector edition
2589     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2590       return N0;
2591     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2592       return N1;
2593
2594     // fold (and x, -1) -> x, vector edition
2595     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2596       return N1;
2597     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2598       return N0;
2599   }
2600
2601   // fold (and x, undef) -> 0
2602   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2603     return DAG.getConstant(0, VT);
2604   // fold (and c1, c2) -> c1&c2
2605   if (N0C && N1C)
2606     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2607   // canonicalize constant to RHS
2608   if (N0C && !N1C)
2609     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2610   // fold (and x, -1) -> x
2611   if (N1C && N1C->isAllOnesValue())
2612     return N0;
2613   // if (and x, c) is known to be zero, return 0
2614   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2615                                    APInt::getAllOnesValue(BitWidth)))
2616     return DAG.getConstant(0, VT);
2617   // reassociate and
2618   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2619   if (RAND.getNode())
2620     return RAND;
2621   // fold (and (or x, C), D) -> D if (C & D) == D
2622   if (N1C && N0.getOpcode() == ISD::OR)
2623     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2624       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2625         return N1;
2626   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2627   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2628     SDValue N0Op0 = N0.getOperand(0);
2629     APInt Mask = ~N1C->getAPIntValue();
2630     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2631     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2632       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2633                                  N0.getValueType(), N0Op0);
2634
2635       // Replace uses of the AND with uses of the Zero extend node.
2636       CombineTo(N, Zext);
2637
2638       // We actually want to replace all uses of the any_extend with the
2639       // zero_extend, to avoid duplicating things.  This will later cause this
2640       // AND to be folded.
2641       CombineTo(N0.getNode(), Zext);
2642       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2643     }
2644   }
2645   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2646   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2647   // already be zero by virtue of the width of the base type of the load.
2648   //
2649   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2650   // more cases.
2651   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2652        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2653       N0.getOpcode() == ISD::LOAD) {
2654     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2655                                          N0 : N0.getOperand(0) );
2656
2657     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2658     // This can be a pure constant or a vector splat, in which case we treat the
2659     // vector as a scalar and use the splat value.
2660     APInt Constant = APInt::getNullValue(1);
2661     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2662       Constant = C->getAPIntValue();
2663     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2664       APInt SplatValue, SplatUndef;
2665       unsigned SplatBitSize;
2666       bool HasAnyUndefs;
2667       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2668                                              SplatBitSize, HasAnyUndefs);
2669       if (IsSplat) {
2670         // Undef bits can contribute to a possible optimisation if set, so
2671         // set them.
2672         SplatValue |= SplatUndef;
2673
2674         // The splat value may be something like "0x00FFFFFF", which means 0 for
2675         // the first vector value and FF for the rest, repeating. We need a mask
2676         // that will apply equally to all members of the vector, so AND all the
2677         // lanes of the constant together.
2678         EVT VT = Vector->getValueType(0);
2679         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2680
2681         // If the splat value has been compressed to a bitlength lower
2682         // than the size of the vector lane, we need to re-expand it to
2683         // the lane size.
2684         if (BitWidth > SplatBitSize)
2685           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2686                SplatBitSize < BitWidth;
2687                SplatBitSize = SplatBitSize * 2)
2688             SplatValue |= SplatValue.shl(SplatBitSize);
2689
2690         Constant = APInt::getAllOnesValue(BitWidth);
2691         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2692           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2693       }
2694     }
2695
2696     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2697     // actually legal and isn't going to get expanded, else this is a false
2698     // optimisation.
2699     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2700                                                     Load->getMemoryVT());
2701
2702     // Resize the constant to the same size as the original memory access before
2703     // extension. If it is still the AllOnesValue then this AND is completely
2704     // unneeded.
2705     Constant =
2706       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2707
2708     bool B;
2709     switch (Load->getExtensionType()) {
2710     default: B = false; break;
2711     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2712     case ISD::ZEXTLOAD:
2713     case ISD::NON_EXTLOAD: B = true; break;
2714     }
2715
2716     if (B && Constant.isAllOnesValue()) {
2717       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2718       // preserve semantics once we get rid of the AND.
2719       SDValue NewLoad(Load, 0);
2720       if (Load->getExtensionType() == ISD::EXTLOAD) {
2721         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2722                               Load->getValueType(0), SDLoc(Load),
2723                               Load->getChain(), Load->getBasePtr(),
2724                               Load->getOffset(), Load->getMemoryVT(),
2725                               Load->getMemOperand());
2726         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2727         if (Load->getNumValues() == 3) {
2728           // PRE/POST_INC loads have 3 values.
2729           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2730                            NewLoad.getValue(2) };
2731           CombineTo(Load, To, 3, true);
2732         } else {
2733           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2734         }
2735       }
2736
2737       // Fold the AND away, taking care not to fold to the old load node if we
2738       // replaced it.
2739       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2740
2741       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2742     }
2743   }
2744   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2745   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2746     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2747     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2748
2749     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2750         LL.getValueType().isInteger()) {
2751       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2752       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2753         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2754                                      LR.getValueType(), LL, RL);
2755         AddToWorkList(ORNode.getNode());
2756         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2757       }
2758       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2759       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2760         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2761                                       LR.getValueType(), LL, RL);
2762         AddToWorkList(ANDNode.getNode());
2763         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2764       }
2765       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2766       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2767         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2768                                      LR.getValueType(), LL, RL);
2769         AddToWorkList(ORNode.getNode());
2770         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2771       }
2772     }
2773     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2774     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2775         Op0 == Op1 && LL.getValueType().isInteger() &&
2776       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2777                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2778                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2779                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2780       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2781                                     LL, DAG.getConstant(1, LL.getValueType()));
2782       AddToWorkList(ADDNode.getNode());
2783       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2784                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2785     }
2786     // canonicalize equivalent to ll == rl
2787     if (LL == RR && LR == RL) {
2788       Op1 = ISD::getSetCCSwappedOperands(Op1);
2789       std::swap(RL, RR);
2790     }
2791     if (LL == RL && LR == RR) {
2792       bool isInteger = LL.getValueType().isInteger();
2793       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2794       if (Result != ISD::SETCC_INVALID &&
2795           (!LegalOperations ||
2796            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2797             TLI.isOperationLegal(ISD::SETCC,
2798                             getSetCCResultType(N0.getSimpleValueType())))))
2799         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2800                             LL, LR, Result);
2801     }
2802   }
2803
2804   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2805   if (N0.getOpcode() == N1.getOpcode()) {
2806     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2807     if (Tmp.getNode()) return Tmp;
2808   }
2809
2810   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2811   // fold (and (sra)) -> (and (srl)) when possible.
2812   if (!VT.isVector() &&
2813       SimplifyDemandedBits(SDValue(N, 0)))
2814     return SDValue(N, 0);
2815
2816   // fold (zext_inreg (extload x)) -> (zextload x)
2817   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2818     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2819     EVT MemVT = LN0->getMemoryVT();
2820     // If we zero all the possible extended bits, then we can turn this into
2821     // a zextload if we are running before legalize or the operation is legal.
2822     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2823     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2824                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2825         ((!LegalOperations && !LN0->isVolatile()) ||
2826          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2827       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2828                                        LN0->getChain(), LN0->getBasePtr(),
2829                                        MemVT, LN0->getMemOperand());
2830       AddToWorkList(N);
2831       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2832       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2833     }
2834   }
2835   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2836   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2837       N0.hasOneUse()) {
2838     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2839     EVT MemVT = LN0->getMemoryVT();
2840     // If we zero all the possible extended bits, then we can turn this into
2841     // a zextload if we are running before legalize or the operation is legal.
2842     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2843     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2844                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2845         ((!LegalOperations && !LN0->isVolatile()) ||
2846          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2847       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2848                                        LN0->getChain(), LN0->getBasePtr(),
2849                                        MemVT, LN0->getMemOperand());
2850       AddToWorkList(N);
2851       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2852       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2853     }
2854   }
2855
2856   // fold (and (load x), 255) -> (zextload x, i8)
2857   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2858   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2859   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2860               (N0.getOpcode() == ISD::ANY_EXTEND &&
2861                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2862     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2863     LoadSDNode *LN0 = HasAnyExt
2864       ? cast<LoadSDNode>(N0.getOperand(0))
2865       : cast<LoadSDNode>(N0);
2866     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2867         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2868       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2869       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2870         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2871         EVT LoadedVT = LN0->getMemoryVT();
2872
2873         if (ExtVT == LoadedVT &&
2874             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2875           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2876
2877           SDValue NewLoad =
2878             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2879                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2880                            LN0->getMemOperand());
2881           AddToWorkList(N);
2882           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2883           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2884         }
2885
2886         // Do not change the width of a volatile load.
2887         // Do not generate loads of non-round integer types since these can
2888         // be expensive (and would be wrong if the type is not byte sized).
2889         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2890             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2891           EVT PtrType = LN0->getOperand(1).getValueType();
2892
2893           unsigned Alignment = LN0->getAlignment();
2894           SDValue NewPtr = LN0->getBasePtr();
2895
2896           // For big endian targets, we need to add an offset to the pointer
2897           // to load the correct bytes.  For little endian systems, we merely
2898           // need to read fewer bytes from the same pointer.
2899           if (TLI.isBigEndian()) {
2900             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2901             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2902             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2903             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2904                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2905             Alignment = MinAlign(Alignment, PtrOff);
2906           }
2907
2908           AddToWorkList(NewPtr.getNode());
2909
2910           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2911           SDValue Load =
2912             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2913                            LN0->getChain(), NewPtr,
2914                            LN0->getPointerInfo(),
2915                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2916                            Alignment, LN0->getTBAAInfo());
2917           AddToWorkList(N);
2918           CombineTo(LN0, Load, Load.getValue(1));
2919           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2920         }
2921       }
2922     }
2923   }
2924
2925   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2926       VT.getSizeInBits() <= 64) {
2927     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2928       APInt ADDC = ADDI->getAPIntValue();
2929       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2931         // immediate for an add, but it is legal if its top c2 bits are set,
2932         // transform the ADD so the immediate doesn't need to be materialized
2933         // in a register.
2934         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2935           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2936                                              SRLI->getZExtValue());
2937           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2938             ADDC |= Mask;
2939             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2940               SDValue NewAdd =
2941                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2942                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2943               CombineTo(N0.getNode(), NewAdd);
2944               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2945             }
2946           }
2947         }
2948       }
2949     }
2950   }
2951
2952   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2953   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2954     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2955                                        N0.getOperand(1), false);
2956     if (BSwap.getNode())
2957       return BSwap;
2958   }
2959
2960   return SDValue();
2961 }
2962
2963 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2964 ///
2965 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2966                                         bool DemandHighBits) {
2967   if (!LegalOperations)
2968     return SDValue();
2969
2970   EVT VT = N->getValueType(0);
2971   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2972     return SDValue();
2973   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2974     return SDValue();
2975
2976   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2977   bool LookPassAnd0 = false;
2978   bool LookPassAnd1 = false;
2979   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2980       std::swap(N0, N1);
2981   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2982       std::swap(N0, N1);
2983   if (N0.getOpcode() == ISD::AND) {
2984     if (!N0.getNode()->hasOneUse())
2985       return SDValue();
2986     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2987     if (!N01C || N01C->getZExtValue() != 0xFF00)
2988       return SDValue();
2989     N0 = N0.getOperand(0);
2990     LookPassAnd0 = true;
2991   }
2992
2993   if (N1.getOpcode() == ISD::AND) {
2994     if (!N1.getNode()->hasOneUse())
2995       return SDValue();
2996     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2997     if (!N11C || N11C->getZExtValue() != 0xFF)
2998       return SDValue();
2999     N1 = N1.getOperand(0);
3000     LookPassAnd1 = true;
3001   }
3002
3003   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3004     std::swap(N0, N1);
3005   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3006     return SDValue();
3007   if (!N0.getNode()->hasOneUse() ||
3008       !N1.getNode()->hasOneUse())
3009     return SDValue();
3010
3011   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3012   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013   if (!N01C || !N11C)
3014     return SDValue();
3015   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3016     return SDValue();
3017
3018   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3019   SDValue N00 = N0->getOperand(0);
3020   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3021     if (!N00.getNode()->hasOneUse())
3022       return SDValue();
3023     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3024     if (!N001C || N001C->getZExtValue() != 0xFF)
3025       return SDValue();
3026     N00 = N00.getOperand(0);
3027     LookPassAnd0 = true;
3028   }
3029
3030   SDValue N10 = N1->getOperand(0);
3031   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3032     if (!N10.getNode()->hasOneUse())
3033       return SDValue();
3034     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3035     if (!N101C || N101C->getZExtValue() != 0xFF00)
3036       return SDValue();
3037     N10 = N10.getOperand(0);
3038     LookPassAnd1 = true;
3039   }
3040
3041   if (N00 != N10)
3042     return SDValue();
3043
3044   // Make sure everything beyond the low halfword gets set to zero since the SRL
3045   // 16 will clear the top bits.
3046   unsigned OpSizeInBits = VT.getSizeInBits();
3047   if (DemandHighBits && OpSizeInBits > 16) {
3048     // If the left-shift isn't masked out then the only way this is a bswap is
3049     // if all bits beyond the low 8 are 0. In that case the entire pattern
3050     // reduces to a left shift anyway: leave it for other parts of the combiner.
3051     if (!LookPassAnd0)
3052       return SDValue();
3053
3054     // However, if the right shift isn't masked out then it might be because
3055     // it's not needed. See if we can spot that too.
3056     if (!LookPassAnd1 &&
3057         !DAG.MaskedValueIsZero(
3058             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3059       return SDValue();
3060   }
3061
3062   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3063   if (OpSizeInBits > 16)
3064     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3065                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3066   return Res;
3067 }
3068
3069 /// isBSwapHWordElement - Return true if the specified node is an element
3070 /// that makes up a 32-bit packed halfword byteswap. i.e.
3071 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3072 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3073   if (!N.getNode()->hasOneUse())
3074     return false;
3075
3076   unsigned Opc = N.getOpcode();
3077   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3078     return false;
3079
3080   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3081   if (!N1C)
3082     return false;
3083
3084   unsigned Num;
3085   switch (N1C->getZExtValue()) {
3086   default:
3087     return false;
3088   case 0xFF:       Num = 0; break;
3089   case 0xFF00:     Num = 1; break;
3090   case 0xFF0000:   Num = 2; break;
3091   case 0xFF000000: Num = 3; break;
3092   }
3093
3094   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3095   SDValue N0 = N.getOperand(0);
3096   if (Opc == ISD::AND) {
3097     if (Num == 0 || Num == 2) {
3098       // (x >> 8) & 0xff
3099       // (x >> 8) & 0xff0000
3100       if (N0.getOpcode() != ISD::SRL)
3101         return false;
3102       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103       if (!C || C->getZExtValue() != 8)
3104         return false;
3105     } else {
3106       // (x << 8) & 0xff00
3107       // (x << 8) & 0xff000000
3108       if (N0.getOpcode() != ISD::SHL)
3109         return false;
3110       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111       if (!C || C->getZExtValue() != 8)
3112         return false;
3113     }
3114   } else if (Opc == ISD::SHL) {
3115     // (x & 0xff) << 8
3116     // (x & 0xff0000) << 8
3117     if (Num != 0 && Num != 2)
3118       return false;
3119     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3120     if (!C || C->getZExtValue() != 8)
3121       return false;
3122   } else { // Opc == ISD::SRL
3123     // (x & 0xff00) >> 8
3124     // (x & 0xff000000) >> 8
3125     if (Num != 1 && Num != 3)
3126       return false;
3127     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3128     if (!C || C->getZExtValue() != 8)
3129       return false;
3130   }
3131
3132   if (Parts[Num])
3133     return false;
3134
3135   Parts[Num] = N0.getOperand(0).getNode();
3136   return true;
3137 }
3138
3139 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3140 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3141 /// => (rotl (bswap x), 16)
3142 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3143   if (!LegalOperations)
3144     return SDValue();
3145
3146   EVT VT = N->getValueType(0);
3147   if (VT != MVT::i32)
3148     return SDValue();
3149   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3150     return SDValue();
3151
3152   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3153   // Look for either
3154   // (or (or (and), (and)), (or (and), (and)))
3155   // (or (or (or (and), (and)), (and)), (and))
3156   if (N0.getOpcode() != ISD::OR)
3157     return SDValue();
3158   SDValue N00 = N0.getOperand(0);
3159   SDValue N01 = N0.getOperand(1);
3160
3161   if (N1.getOpcode() == ISD::OR &&
3162       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3163     // (or (or (and), (and)), (or (and), (and)))
3164     SDValue N000 = N00.getOperand(0);
3165     if (!isBSwapHWordElement(N000, Parts))
3166       return SDValue();
3167
3168     SDValue N001 = N00.getOperand(1);
3169     if (!isBSwapHWordElement(N001, Parts))
3170       return SDValue();
3171     SDValue N010 = N01.getOperand(0);
3172     if (!isBSwapHWordElement(N010, Parts))
3173       return SDValue();
3174     SDValue N011 = N01.getOperand(1);
3175     if (!isBSwapHWordElement(N011, Parts))
3176       return SDValue();
3177   } else {
3178     // (or (or (or (and), (and)), (and)), (and))
3179     if (!isBSwapHWordElement(N1, Parts))
3180       return SDValue();
3181     if (!isBSwapHWordElement(N01, Parts))
3182       return SDValue();
3183     if (N00.getOpcode() != ISD::OR)
3184       return SDValue();
3185     SDValue N000 = N00.getOperand(0);
3186     if (!isBSwapHWordElement(N000, Parts))
3187       return SDValue();
3188     SDValue N001 = N00.getOperand(1);
3189     if (!isBSwapHWordElement(N001, Parts))
3190       return SDValue();
3191   }
3192
3193   // Make sure the parts are all coming from the same node.
3194   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3195     return SDValue();
3196
3197   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3198                               SDValue(Parts[0],0));
3199
3200   // Result of the bswap should be rotated by 16. If it's not legal, then
3201   // do  (x << 16) | (x >> 16).
3202   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3203   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3204     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3205   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3206     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3207   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3208                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3209                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3210 }
3211
3212 SDValue DAGCombiner::visitOR(SDNode *N) {
3213   SDValue N0 = N->getOperand(0);
3214   SDValue N1 = N->getOperand(1);
3215   SDValue LL, LR, RL, RR, CC0, CC1;
3216   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3217   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3218   EVT VT = N1.getValueType();
3219
3220   // fold vector ops
3221   if (VT.isVector()) {
3222     SDValue FoldedVOp = SimplifyVBinOp(N);
3223     if (FoldedVOp.getNode()) return FoldedVOp;
3224
3225     // fold (or x, 0) -> x, vector edition
3226     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3227       return N1;
3228     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3229       return N0;
3230
3231     // fold (or x, -1) -> -1, vector edition
3232     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3233       return N0;
3234     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3235       return N1;
3236
3237     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3238     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3239     // Do this only if the resulting shuffle is legal.
3240     if (isa<ShuffleVectorSDNode>(N0) &&
3241         isa<ShuffleVectorSDNode>(N1) &&
3242         N0->getOperand(1) == N1->getOperand(1) &&
3243         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3244       bool CanFold = true;
3245       unsigned NumElts = VT.getVectorNumElements();
3246       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3247       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3248       // We construct two shuffle masks:
3249       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3250       // and N1 as the second operand.
3251       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3252       // and N0 as the second operand.
3253       // We do this because OR is commutable and therefore there might be
3254       // two ways to fold this node into a shuffle.
3255       SmallVector<int,4> Mask1;
3256       SmallVector<int,4> Mask2;
3257       
3258       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3259         int M0 = SV0->getMaskElt(i);
3260         int M1 = SV1->getMaskElt(i);
3261    
3262         // Both shuffle indexes are undef. Propagate Undef.
3263         if (M0 < 0 && M1 < 0) {
3264           Mask1.push_back(M0);
3265           Mask2.push_back(M0);
3266           continue;
3267         }
3268
3269         if (M0 < 0 || M1 < 0 ||
3270             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3271             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3272           CanFold = false;
3273           break;
3274         }
3275         
3276         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3277         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3278       }
3279
3280       if (CanFold) {
3281         // Fold this sequence only if the resulting shuffle is 'legal'.
3282         if (TLI.isShuffleMaskLegal(Mask1, VT))
3283           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3284                                       N1->getOperand(0), &Mask1[0]);
3285         if (TLI.isShuffleMaskLegal(Mask2, VT))
3286           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3287                                       N0->getOperand(0), &Mask2[0]);
3288       }
3289     }
3290   }
3291
3292   // fold (or x, undef) -> -1
3293   if (!LegalOperations &&
3294       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3295     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3296     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3297   }
3298   // fold (or c1, c2) -> c1|c2
3299   if (N0C && N1C)
3300     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3301   // canonicalize constant to RHS
3302   if (N0C && !N1C)
3303     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3304   // fold (or x, 0) -> x
3305   if (N1C && N1C->isNullValue())
3306     return N0;
3307   // fold (or x, -1) -> -1
3308   if (N1C && N1C->isAllOnesValue())
3309     return N1;
3310   // fold (or x, c) -> c iff (x & ~c) == 0
3311   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3312     return N1;
3313
3314   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3315   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3316   if (BSwap.getNode())
3317     return BSwap;
3318   BSwap = MatchBSwapHWordLow(N, N0, N1);
3319   if (BSwap.getNode())
3320     return BSwap;
3321
3322   // reassociate or
3323   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3324   if (ROR.getNode())
3325     return ROR;
3326   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3327   // iff (c1 & c2) == 0.
3328   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3329              isa<ConstantSDNode>(N0.getOperand(1))) {
3330     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3331     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3332       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3333       if (!COR.getNode())
3334         return SDValue();
3335       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3336                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3337                                      N0.getOperand(0), N1), COR);
3338     }
3339   }
3340   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3341   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3342     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3343     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3344
3345     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3346         LL.getValueType().isInteger()) {
3347       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3348       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3349       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3350           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3351         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3352                                      LR.getValueType(), LL, RL);
3353         AddToWorkList(ORNode.getNode());
3354         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3355       }
3356       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3357       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3358       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3359           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3360         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3361                                       LR.getValueType(), LL, RL);
3362         AddToWorkList(ANDNode.getNode());
3363         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3364       }
3365     }
3366     // canonicalize equivalent to ll == rl
3367     if (LL == RR && LR == RL) {
3368       Op1 = ISD::getSetCCSwappedOperands(Op1);
3369       std::swap(RL, RR);
3370     }
3371     if (LL == RL && LR == RR) {
3372       bool isInteger = LL.getValueType().isInteger();
3373       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3374       if (Result != ISD::SETCC_INVALID &&
3375           (!LegalOperations ||
3376            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3377             TLI.isOperationLegal(ISD::SETCC,
3378               getSetCCResultType(N0.getValueType())))))
3379         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3380                             LL, LR, Result);
3381     }
3382   }
3383
3384   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3385   if (N0.getOpcode() == N1.getOpcode()) {
3386     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3387     if (Tmp.getNode()) return Tmp;
3388   }
3389
3390   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3391   if (N0.getOpcode() == ISD::AND &&
3392       N1.getOpcode() == ISD::AND &&
3393       N0.getOperand(1).getOpcode() == ISD::Constant &&
3394       N1.getOperand(1).getOpcode() == ISD::Constant &&
3395       // Don't increase # computations.
3396       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3397     // We can only do this xform if we know that bits from X that are set in C2
3398     // but not in C1 are already zero.  Likewise for Y.
3399     const APInt &LHSMask =
3400       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3401     const APInt &RHSMask =
3402       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3403
3404     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3405         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3406       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3407                               N0.getOperand(0), N1.getOperand(0));
3408       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3409                          DAG.getConstant(LHSMask | RHSMask, VT));
3410     }
3411   }
3412
3413   // See if this is some rotate idiom.
3414   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3415     return SDValue(Rot, 0);
3416
3417   // Simplify the operands using demanded-bits information.
3418   if (!VT.isVector() &&
3419       SimplifyDemandedBits(SDValue(N, 0)))
3420     return SDValue(N, 0);
3421
3422   return SDValue();
3423 }
3424
3425 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3426 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3427   if (Op.getOpcode() == ISD::AND) {
3428     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3429       Mask = Op.getOperand(1);
3430       Op = Op.getOperand(0);
3431     } else {
3432       return false;
3433     }
3434   }
3435
3436   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3437     Shift = Op;
3438     return true;
3439   }
3440
3441   return false;
3442 }
3443
3444 // Return true if we can prove that, whenever Neg and Pos are both in the
3445 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3446 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3447 //
3448 //     (or (shift1 X, Neg), (shift2 X, Pos))
3449 //
3450 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3451 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3452 // to consider shift amounts with defined behavior.
3453 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3454   // If OpSize is a power of 2 then:
3455   //
3456   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3457   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3458   //
3459   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3460   // for the stronger condition:
3461   //
3462   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3463   //
3464   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3465   // we can just replace Neg with Neg' for the rest of the function.
3466   //
3467   // In other cases we check for the even stronger condition:
3468   //
3469   //     Neg == OpSize - Pos                                    [B]
3470   //
3471   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3472   // behavior if Pos == 0 (and consequently Neg == OpSize).
3473   //
3474   // We could actually use [A] whenever OpSize is a power of 2, but the
3475   // only extra cases that it would match are those uninteresting ones
3476   // where Neg and Pos are never in range at the same time.  E.g. for
3477   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3478   // as well as (sub 32, Pos), but:
3479   //
3480   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3481   //
3482   // always invokes undefined behavior for 32-bit X.
3483   //
3484   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3485   unsigned MaskLoBits = 0;
3486   if (Neg.getOpcode() == ISD::AND &&
3487       isPowerOf2_64(OpSize) &&
3488       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3489       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3490     Neg = Neg.getOperand(0);
3491     MaskLoBits = Log2_64(OpSize);
3492   }
3493
3494   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3495   if (Neg.getOpcode() != ISD::SUB)
3496     return 0;
3497   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3498   if (!NegC)
3499     return 0;
3500   SDValue NegOp1 = Neg.getOperand(1);
3501
3502   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3503   // Pos'.  The truncation is redundant for the purpose of the equality.
3504   if (MaskLoBits &&
3505       Pos.getOpcode() == ISD::AND &&
3506       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3507       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3508     Pos = Pos.getOperand(0);
3509
3510   // The condition we need is now:
3511   //
3512   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3513   //
3514   // If NegOp1 == Pos then we need:
3515   //
3516   //              OpSize & Mask == NegC & Mask
3517   //
3518   // (because "x & Mask" is a truncation and distributes through subtraction).
3519   APInt Width;
3520   if (Pos == NegOp1)
3521     Width = NegC->getAPIntValue();
3522   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3523   // Then the condition we want to prove becomes:
3524   //
3525   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3526   //
3527   // which, again because "x & Mask" is a truncation, becomes:
3528   //
3529   //                NegC & Mask == (OpSize - PosC) & Mask
3530   //              OpSize & Mask == (NegC + PosC) & Mask
3531   else if (Pos.getOpcode() == ISD::ADD &&
3532            Pos.getOperand(0) == NegOp1 &&
3533            Pos.getOperand(1).getOpcode() == ISD::Constant)
3534     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3535              NegC->getAPIntValue());
3536   else
3537     return false;
3538
3539   // Now we just need to check that OpSize & Mask == Width & Mask.
3540   if (MaskLoBits)
3541     // Opsize & Mask is 0 since Mask is Opsize - 1.
3542     return Width.getLoBits(MaskLoBits) == 0;
3543   return Width == OpSize;
3544 }
3545
3546 // A subroutine of MatchRotate used once we have found an OR of two opposite
3547 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3548 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3549 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3550 // Neg with outer conversions stripped away.
3551 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3552                                        SDValue Neg, SDValue InnerPos,
3553                                        SDValue InnerNeg, unsigned PosOpcode,
3554                                        unsigned NegOpcode, SDLoc DL) {
3555   // fold (or (shl x, (*ext y)),
3556   //          (srl x, (*ext (sub 32, y)))) ->
3557   //   (rotl x, y) or (rotr x, (sub 32, y))
3558   //
3559   // fold (or (shl x, (*ext (sub 32, y))),
3560   //          (srl x, (*ext y))) ->
3561   //   (rotr x, y) or (rotl x, (sub 32, y))
3562   EVT VT = Shifted.getValueType();
3563   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3564     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3565     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3566                        HasPos ? Pos : Neg).getNode();
3567   }
3568
3569   return nullptr;
3570 }
3571
3572 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3573 // idioms for rotate, and if the target supports rotation instructions, generate
3574 // a rot[lr].
3575 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3576   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3577   EVT VT = LHS.getValueType();
3578   if (!TLI.isTypeLegal(VT)) return nullptr;
3579
3580   // The target must have at least one rotate flavor.
3581   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3582   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3583   if (!HasROTL && !HasROTR) return nullptr;
3584
3585   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3586   SDValue LHSShift;   // The shift.
3587   SDValue LHSMask;    // AND value if any.
3588   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3589     return nullptr; // Not part of a rotate.
3590
3591   SDValue RHSShift;   // The shift.
3592   SDValue RHSMask;    // AND value if any.
3593   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3594     return nullptr; // Not part of a rotate.
3595
3596   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3597     return nullptr;   // Not shifting the same value.
3598
3599   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3600     return nullptr;   // Shifts must disagree.
3601
3602   // Canonicalize shl to left side in a shl/srl pair.
3603   if (RHSShift.getOpcode() == ISD::SHL) {
3604     std::swap(LHS, RHS);
3605     std::swap(LHSShift, RHSShift);
3606     std::swap(LHSMask , RHSMask );
3607   }
3608
3609   unsigned OpSizeInBits = VT.getSizeInBits();
3610   SDValue LHSShiftArg = LHSShift.getOperand(0);
3611   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3612   SDValue RHSShiftArg = RHSShift.getOperand(0);
3613   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3614
3615   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3616   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3617   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3618       RHSShiftAmt.getOpcode() == ISD::Constant) {
3619     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3620     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3621     if ((LShVal + RShVal) != OpSizeInBits)
3622       return nullptr;
3623
3624     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3625                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3626
3627     // If there is an AND of either shifted operand, apply it to the result.
3628     if (LHSMask.getNode() || RHSMask.getNode()) {
3629       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3630
3631       if (LHSMask.getNode()) {
3632         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3633         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3634       }
3635       if (RHSMask.getNode()) {
3636         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3637         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3638       }
3639
3640       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3641     }
3642
3643     return Rot.getNode();
3644   }
3645
3646   // If there is a mask here, and we have a variable shift, we can't be sure
3647   // that we're masking out the right stuff.
3648   if (LHSMask.getNode() || RHSMask.getNode())
3649     return nullptr;
3650
3651   // If the shift amount is sign/zext/any-extended just peel it off.
3652   SDValue LExtOp0 = LHSShiftAmt;
3653   SDValue RExtOp0 = RHSShiftAmt;
3654   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3655        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3656        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3657        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3658       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3659        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3660        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3661        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3662     LExtOp0 = LHSShiftAmt.getOperand(0);
3663     RExtOp0 = RHSShiftAmt.getOperand(0);
3664   }
3665
3666   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3667                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3668   if (TryL)
3669     return TryL;
3670
3671   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3672                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3673   if (TryR)
3674     return TryR;
3675
3676   return nullptr;
3677 }
3678
3679 SDValue DAGCombiner::visitXOR(SDNode *N) {
3680   SDValue N0 = N->getOperand(0);
3681   SDValue N1 = N->getOperand(1);
3682   SDValue LHS, RHS, CC;
3683   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3684   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3685   EVT VT = N0.getValueType();
3686
3687   // fold vector ops
3688   if (VT.isVector()) {
3689     SDValue FoldedVOp = SimplifyVBinOp(N);
3690     if (FoldedVOp.getNode()) return FoldedVOp;
3691
3692     // fold (xor x, 0) -> x, vector edition
3693     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3694       return N1;
3695     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3696       return N0;
3697   }
3698
3699   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3700   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3701     return DAG.getConstant(0, VT);
3702   // fold (xor x, undef) -> undef
3703   if (N0.getOpcode() == ISD::UNDEF)
3704     return N0;
3705   if (N1.getOpcode() == ISD::UNDEF)
3706     return N1;
3707   // fold (xor c1, c2) -> c1^c2
3708   if (N0C && N1C)
3709     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3710   // canonicalize constant to RHS
3711   if (N0C && !N1C)
3712     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3713   // fold (xor x, 0) -> x
3714   if (N1C && N1C->isNullValue())
3715     return N0;
3716   // reassociate xor
3717   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3718   if (RXOR.getNode())
3719     return RXOR;
3720
3721   // fold !(x cc y) -> (x !cc y)
3722   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3723     bool isInt = LHS.getValueType().isInteger();
3724     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3725                                                isInt);
3726
3727     if (!LegalOperations ||
3728         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3729       switch (N0.getOpcode()) {
3730       default:
3731         llvm_unreachable("Unhandled SetCC Equivalent!");
3732       case ISD::SETCC:
3733         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3734       case ISD::SELECT_CC:
3735         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3736                                N0.getOperand(3), NotCC);
3737       }
3738     }
3739   }
3740
3741   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3742   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3743       N0.getNode()->hasOneUse() &&
3744       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3745     SDValue V = N0.getOperand(0);
3746     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3747                     DAG.getConstant(1, V.getValueType()));
3748     AddToWorkList(V.getNode());
3749     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3750   }
3751
3752   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3753   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3754       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3755     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3756     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3757       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3758       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3759       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3760       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3761       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3762     }
3763   }
3764   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3765   if (N1C && N1C->isAllOnesValue() &&
3766       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3767     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3768     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3769       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3770       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3771       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3772       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3773       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3774     }
3775   }
3776   // fold (xor (and x, y), y) -> (and (not x), y)
3777   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3778       N0->getOperand(1) == N1) {
3779     SDValue X = N0->getOperand(0);
3780     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3781     AddToWorkList(NotX.getNode());
3782     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3783   }
3784   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3785   if (N1C && N0.getOpcode() == ISD::XOR) {
3786     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3787     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3788     if (N00C)
3789       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3790                          DAG.getConstant(N1C->getAPIntValue() ^
3791                                          N00C->getAPIntValue(), VT));
3792     if (N01C)
3793       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3794                          DAG.getConstant(N1C->getAPIntValue() ^
3795                                          N01C->getAPIntValue(), VT));
3796   }
3797   // fold (xor x, x) -> 0
3798   if (N0 == N1)
3799     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3800
3801   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3802   if (N0.getOpcode() == N1.getOpcode()) {
3803     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3804     if (Tmp.getNode()) return Tmp;
3805   }
3806
3807   // Simplify the expression using non-local knowledge.
3808   if (!VT.isVector() &&
3809       SimplifyDemandedBits(SDValue(N, 0)))
3810     return SDValue(N, 0);
3811
3812   return SDValue();
3813 }
3814
3815 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3816 /// the shift amount is a constant.
3817 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3818   // We can't and shouldn't fold opaque constants.
3819   if (Amt->isOpaque())
3820     return SDValue();
3821
3822   SDNode *LHS = N->getOperand(0).getNode();
3823   if (!LHS->hasOneUse()) return SDValue();
3824
3825   // We want to pull some binops through shifts, so that we have (and (shift))
3826   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3827   // thing happens with address calculations, so it's important to canonicalize
3828   // it.
3829   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3830
3831   switch (LHS->getOpcode()) {
3832   default: return SDValue();
3833   case ISD::OR:
3834   case ISD::XOR:
3835     HighBitSet = false; // We can only transform sra if the high bit is clear.
3836     break;
3837   case ISD::AND:
3838     HighBitSet = true;  // We can only transform sra if the high bit is set.
3839     break;
3840   case ISD::ADD:
3841     if (N->getOpcode() != ISD::SHL)
3842       return SDValue(); // only shl(add) not sr[al](add).
3843     HighBitSet = false; // We can only transform sra if the high bit is clear.
3844     break;
3845   }
3846
3847   // We require the RHS of the binop to be a constant and not opaque as well.
3848   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3849   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3850
3851   // FIXME: disable this unless the input to the binop is a shift by a constant.
3852   // If it is not a shift, it pessimizes some common cases like:
3853   //
3854   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3855   //    int bar(int *X, int i) { return X[i & 255]; }
3856   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3857   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3858        BinOpLHSVal->getOpcode() != ISD::SRA &&
3859        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3860       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3861     return SDValue();
3862
3863   EVT VT = N->getValueType(0);
3864
3865   // If this is a signed shift right, and the high bit is modified by the
3866   // logical operation, do not perform the transformation. The highBitSet
3867   // boolean indicates the value of the high bit of the constant which would
3868   // cause it to be modified for this operation.
3869   if (N->getOpcode() == ISD::SRA) {
3870     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3871     if (BinOpRHSSignSet != HighBitSet)
3872       return SDValue();
3873   }
3874
3875   // Fold the constants, shifting the binop RHS by the shift amount.
3876   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3877                                N->getValueType(0),
3878                                LHS->getOperand(1), N->getOperand(1));
3879   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3880
3881   // Create the new shift.
3882   SDValue NewShift = DAG.getNode(N->getOpcode(),
3883                                  SDLoc(LHS->getOperand(0)),
3884                                  VT, LHS->getOperand(0), N->getOperand(1));
3885
3886   // Create the new binop.
3887   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3888 }
3889
3890 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3891   assert(N->getOpcode() == ISD::TRUNCATE);
3892   assert(N->getOperand(0).getOpcode() == ISD::AND);
3893
3894   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3895   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3896     SDValue N01 = N->getOperand(0).getOperand(1);
3897
3898     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3899       EVT TruncVT = N->getValueType(0);
3900       SDValue N00 = N->getOperand(0).getOperand(0);
3901       APInt TruncC = N01C->getAPIntValue();
3902       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3903
3904       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3905                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3906                          DAG.getConstant(TruncC, TruncVT));
3907     }
3908   }
3909
3910   return SDValue();
3911 }
3912
3913 SDValue DAGCombiner::visitRotate(SDNode *N) {
3914   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3915   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3916       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3917     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3918     if (NewOp1.getNode())
3919       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3920                          N->getOperand(0), NewOp1);
3921   }
3922   return SDValue();
3923 }
3924
3925 SDValue DAGCombiner::visitSHL(SDNode *N) {
3926   SDValue N0 = N->getOperand(0);
3927   SDValue N1 = N->getOperand(1);
3928   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3929   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3930   EVT VT = N0.getValueType();
3931   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3932
3933   // fold vector ops
3934   if (VT.isVector()) {
3935     SDValue FoldedVOp = SimplifyVBinOp(N);
3936     if (FoldedVOp.getNode()) return FoldedVOp;
3937
3938     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3939     // If setcc produces all-one true value then:
3940     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3941     if (N1CV && N1CV->isConstant()) {
3942       if (N0.getOpcode() == ISD::AND &&
3943           TLI.getBooleanContents(true) ==
3944           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3945         SDValue N00 = N0->getOperand(0);
3946         SDValue N01 = N0->getOperand(1);
3947         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3948
3949         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3950           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3951           if (C.getNode())
3952             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3953         }
3954       } else {
3955         N1C = isConstOrConstSplat(N1);
3956       }
3957     }
3958   }
3959
3960   // fold (shl c1, c2) -> c1<<c2
3961   if (N0C && N1C)
3962     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3963   // fold (shl 0, x) -> 0
3964   if (N0C && N0C->isNullValue())
3965     return N0;
3966   // fold (shl x, c >= size(x)) -> undef
3967   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3968     return DAG.getUNDEF(VT);
3969   // fold (shl x, 0) -> x
3970   if (N1C && N1C->isNullValue())
3971     return N0;
3972   // fold (shl undef, x) -> 0
3973   if (N0.getOpcode() == ISD::UNDEF)
3974     return DAG.getConstant(0, VT);
3975   // if (shl x, c) is known to be zero, return 0
3976   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3977                             APInt::getAllOnesValue(OpSizeInBits)))
3978     return DAG.getConstant(0, VT);
3979   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3980   if (N1.getOpcode() == ISD::TRUNCATE &&
3981       N1.getOperand(0).getOpcode() == ISD::AND) {
3982     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3983     if (NewOp1.getNode())
3984       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3985   }
3986
3987   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3988     return SDValue(N, 0);
3989
3990   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3991   if (N1C && N0.getOpcode() == ISD::SHL) {
3992     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3993       uint64_t c1 = N0C1->getZExtValue();
3994       uint64_t c2 = N1C->getZExtValue();
3995       if (c1 + c2 >= OpSizeInBits)
3996         return DAG.getConstant(0, VT);
3997       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3998                          DAG.getConstant(c1 + c2, N1.getValueType()));
3999     }
4000   }
4001
4002   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4003   // For this to be valid, the second form must not preserve any of the bits
4004   // that are shifted out by the inner shift in the first form.  This means
4005   // the outer shift size must be >= the number of bits added by the ext.
4006   // As a corollary, we don't care what kind of ext it is.
4007   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4008               N0.getOpcode() == ISD::ANY_EXTEND ||
4009               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4010       N0.getOperand(0).getOpcode() == ISD::SHL) {
4011     SDValue N0Op0 = N0.getOperand(0);
4012     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4013       uint64_t c1 = N0Op0C1->getZExtValue();
4014       uint64_t c2 = N1C->getZExtValue();
4015       EVT InnerShiftVT = N0Op0.getValueType();
4016       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4017       if (c2 >= OpSizeInBits - InnerShiftSize) {
4018         if (c1 + c2 >= OpSizeInBits)
4019           return DAG.getConstant(0, VT);
4020         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4021                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4022                                        N0Op0->getOperand(0)),
4023                            DAG.getConstant(c1 + c2, N1.getValueType()));
4024       }
4025     }
4026   }
4027
4028   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4029   // Only fold this if the inner zext has no other uses to avoid increasing
4030   // the total number of instructions.
4031   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4032       N0.getOperand(0).getOpcode() == ISD::SRL) {
4033     SDValue N0Op0 = N0.getOperand(0);
4034     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4035       uint64_t c1 = N0Op0C1->getZExtValue();
4036       if (c1 < VT.getScalarSizeInBits()) {
4037         uint64_t c2 = N1C->getZExtValue();
4038         if (c1 == c2) {
4039           SDValue NewOp0 = N0.getOperand(0);
4040           EVT CountVT = NewOp0.getOperand(1).getValueType();
4041           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4042                                        NewOp0, DAG.getConstant(c2, CountVT));
4043           AddToWorkList(NewSHL.getNode());
4044           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4045         }
4046       }
4047     }
4048   }
4049
4050   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4051   //                               (and (srl x, (sub c1, c2), MASK)
4052   // Only fold this if the inner shift has no other uses -- if it does, folding
4053   // this will increase the total number of instructions.
4054   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4055     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4056       uint64_t c1 = N0C1->getZExtValue();
4057       if (c1 < OpSizeInBits) {
4058         uint64_t c2 = N1C->getZExtValue();
4059         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4060         SDValue Shift;
4061         if (c2 > c1) {
4062           Mask = Mask.shl(c2 - c1);
4063           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4064                               DAG.getConstant(c2 - c1, N1.getValueType()));
4065         } else {
4066           Mask = Mask.lshr(c1 - c2);
4067           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4068                               DAG.getConstant(c1 - c2, N1.getValueType()));
4069         }
4070         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4071                            DAG.getConstant(Mask, VT));
4072       }
4073     }
4074   }
4075   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4076   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4077     unsigned BitSize = VT.getScalarSizeInBits();
4078     SDValue HiBitsMask =
4079       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4080                                             BitSize - N1C->getZExtValue()), VT);
4081     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4082                        HiBitsMask);
4083   }
4084
4085   if (N1C) {
4086     SDValue NewSHL = visitShiftByConstant(N, N1C);
4087     if (NewSHL.getNode())
4088       return NewSHL;
4089   }
4090
4091   return SDValue();
4092 }
4093
4094 SDValue DAGCombiner::visitSRA(SDNode *N) {
4095   SDValue N0 = N->getOperand(0);
4096   SDValue N1 = N->getOperand(1);
4097   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4098   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4099   EVT VT = N0.getValueType();
4100   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4101
4102   // fold vector ops
4103   if (VT.isVector()) {
4104     SDValue FoldedVOp = SimplifyVBinOp(N);
4105     if (FoldedVOp.getNode()) return FoldedVOp;
4106
4107     N1C = isConstOrConstSplat(N1);
4108   }
4109
4110   // fold (sra c1, c2) -> (sra c1, c2)
4111   if (N0C && N1C)
4112     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4113   // fold (sra 0, x) -> 0
4114   if (N0C && N0C->isNullValue())
4115     return N0;
4116   // fold (sra -1, x) -> -1
4117   if (N0C && N0C->isAllOnesValue())
4118     return N0;
4119   // fold (sra x, (setge c, size(x))) -> undef
4120   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4121     return DAG.getUNDEF(VT);
4122   // fold (sra x, 0) -> x
4123   if (N1C && N1C->isNullValue())
4124     return N0;
4125   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4126   // sext_inreg.
4127   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4128     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4129     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4130     if (VT.isVector())
4131       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4132                                ExtVT, VT.getVectorNumElements());
4133     if ((!LegalOperations ||
4134          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4135       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4136                          N0.getOperand(0), DAG.getValueType(ExtVT));
4137   }
4138
4139   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4140   if (N1C && N0.getOpcode() == ISD::SRA) {
4141     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4142       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4143       if (Sum >= OpSizeInBits)
4144         Sum = OpSizeInBits - 1;
4145       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4146                          DAG.getConstant(Sum, N1.getValueType()));
4147     }
4148   }
4149
4150   // fold (sra (shl X, m), (sub result_size, n))
4151   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4152   // result_size - n != m.
4153   // If truncate is free for the target sext(shl) is likely to result in better
4154   // code.
4155   if (N0.getOpcode() == ISD::SHL && N1C) {
4156     // Get the two constanst of the shifts, CN0 = m, CN = n.
4157     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4158     if (N01C) {
4159       LLVMContext &Ctx = *DAG.getContext();
4160       // Determine what the truncate's result bitsize and type would be.
4161       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4162
4163       if (VT.isVector())
4164         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4165
4166       // Determine the residual right-shift amount.
4167       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4168
4169       // If the shift is not a no-op (in which case this should be just a sign
4170       // extend already), the truncated to type is legal, sign_extend is legal
4171       // on that type, and the truncate to that type is both legal and free,
4172       // perform the transform.
4173       if ((ShiftAmt > 0) &&
4174           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4175           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4176           TLI.isTruncateFree(VT, TruncVT)) {
4177
4178           SDValue Amt = DAG.getConstant(ShiftAmt,
4179               getShiftAmountTy(N0.getOperand(0).getValueType()));
4180           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4181                                       N0.getOperand(0), Amt);
4182           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4183                                       Shift);
4184           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4185                              N->getValueType(0), Trunc);
4186       }
4187     }
4188   }
4189
4190   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4191   if (N1.getOpcode() == ISD::TRUNCATE &&
4192       N1.getOperand(0).getOpcode() == ISD::AND) {
4193     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4194     if (NewOp1.getNode())
4195       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4196   }
4197
4198   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4199   //      if c1 is equal to the number of bits the trunc removes
4200   if (N0.getOpcode() == ISD::TRUNCATE &&
4201       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4202        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4203       N0.getOperand(0).hasOneUse() &&
4204       N0.getOperand(0).getOperand(1).hasOneUse() &&
4205       N1C) {
4206     SDValue N0Op0 = N0.getOperand(0);
4207     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4208       unsigned LargeShiftVal = LargeShift->getZExtValue();
4209       EVT LargeVT = N0Op0.getValueType();
4210
4211       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4212         SDValue Amt =
4213           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4214                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4215         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4216                                   N0Op0.getOperand(0), Amt);
4217         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4218       }
4219     }
4220   }
4221
4222   // Simplify, based on bits shifted out of the LHS.
4223   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4224     return SDValue(N, 0);
4225
4226
4227   // If the sign bit is known to be zero, switch this to a SRL.
4228   if (DAG.SignBitIsZero(N0))
4229     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4230
4231   if (N1C) {
4232     SDValue NewSRA = visitShiftByConstant(N, N1C);
4233     if (NewSRA.getNode())
4234       return NewSRA;
4235   }
4236
4237   return SDValue();
4238 }
4239
4240 SDValue DAGCombiner::visitSRL(SDNode *N) {
4241   SDValue N0 = N->getOperand(0);
4242   SDValue N1 = N->getOperand(1);
4243   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4244   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4245   EVT VT = N0.getValueType();
4246   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4247
4248   // fold vector ops
4249   if (VT.isVector()) {
4250     SDValue FoldedVOp = SimplifyVBinOp(N);
4251     if (FoldedVOp.getNode()) return FoldedVOp;
4252
4253     N1C = isConstOrConstSplat(N1);
4254   }
4255
4256   // fold (srl c1, c2) -> c1 >>u c2
4257   if (N0C && N1C)
4258     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4259   // fold (srl 0, x) -> 0
4260   if (N0C && N0C->isNullValue())
4261     return N0;
4262   // fold (srl x, c >= size(x)) -> undef
4263   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4264     return DAG.getUNDEF(VT);
4265   // fold (srl x, 0) -> x
4266   if (N1C && N1C->isNullValue())
4267     return N0;
4268   // if (srl x, c) is known to be zero, return 0
4269   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4270                                    APInt::getAllOnesValue(OpSizeInBits)))
4271     return DAG.getConstant(0, VT);
4272
4273   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4274   if (N1C && N0.getOpcode() == ISD::SRL) {
4275     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4276       uint64_t c1 = N01C->getZExtValue();
4277       uint64_t c2 = N1C->getZExtValue();
4278       if (c1 + c2 >= OpSizeInBits)
4279         return DAG.getConstant(0, VT);
4280       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4281                          DAG.getConstant(c1 + c2, N1.getValueType()));
4282     }
4283   }
4284
4285   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4286   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4287       N0.getOperand(0).getOpcode() == ISD::SRL &&
4288       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4289     uint64_t c1 =
4290       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4291     uint64_t c2 = N1C->getZExtValue();
4292     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4293     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4294     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4295     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4296     if (c1 + OpSizeInBits == InnerShiftSize) {
4297       if (c1 + c2 >= InnerShiftSize)
4298         return DAG.getConstant(0, VT);
4299       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4300                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4301                                      N0.getOperand(0)->getOperand(0),
4302                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4303     }
4304   }
4305
4306   // fold (srl (shl x, c), c) -> (and x, cst2)
4307   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4308     unsigned BitSize = N0.getScalarValueSizeInBits();
4309     if (BitSize <= 64) {
4310       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4311       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4312                          DAG.getConstant(~0ULL >> ShAmt, VT));
4313     }
4314   }
4315
4316   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4317   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4318     // Shifting in all undef bits?
4319     EVT SmallVT = N0.getOperand(0).getValueType();
4320     unsigned BitSize = SmallVT.getScalarSizeInBits();
4321     if (N1C->getZExtValue() >= BitSize)
4322       return DAG.getUNDEF(VT);
4323
4324     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4325       uint64_t ShiftAmt = N1C->getZExtValue();
4326       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4327                                        N0.getOperand(0),
4328                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4329       AddToWorkList(SmallShift.getNode());
4330       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4331       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4332                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4333                          DAG.getConstant(Mask, VT));
4334     }
4335   }
4336
4337   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4338   // bit, which is unmodified by sra.
4339   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4340     if (N0.getOpcode() == ISD::SRA)
4341       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4342   }
4343
4344   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4345   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4346       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4347     APInt KnownZero, KnownOne;
4348     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4349
4350     // If any of the input bits are KnownOne, then the input couldn't be all
4351     // zeros, thus the result of the srl will always be zero.
4352     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4353
4354     // If all of the bits input the to ctlz node are known to be zero, then
4355     // the result of the ctlz is "32" and the result of the shift is one.
4356     APInt UnknownBits = ~KnownZero;
4357     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4358
4359     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4360     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4361       // Okay, we know that only that the single bit specified by UnknownBits
4362       // could be set on input to the CTLZ node. If this bit is set, the SRL
4363       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4364       // to an SRL/XOR pair, which is likely to simplify more.
4365       unsigned ShAmt = UnknownBits.countTrailingZeros();
4366       SDValue Op = N0.getOperand(0);
4367
4368       if (ShAmt) {
4369         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4370                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4371         AddToWorkList(Op.getNode());
4372       }
4373
4374       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4375                          Op, DAG.getConstant(1, VT));
4376     }
4377   }
4378
4379   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4380   if (N1.getOpcode() == ISD::TRUNCATE &&
4381       N1.getOperand(0).getOpcode() == ISD::AND) {
4382     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4383     if (NewOp1.getNode())
4384       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4385   }
4386
4387   // fold operands of srl based on knowledge that the low bits are not
4388   // demanded.
4389   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4390     return SDValue(N, 0);
4391
4392   if (N1C) {
4393     SDValue NewSRL = visitShiftByConstant(N, N1C);
4394     if (NewSRL.getNode())
4395       return NewSRL;
4396   }
4397
4398   // Attempt to convert a srl of a load into a narrower zero-extending load.
4399   SDValue NarrowLoad = ReduceLoadWidth(N);
4400   if (NarrowLoad.getNode())
4401     return NarrowLoad;
4402
4403   // Here is a common situation. We want to optimize:
4404   //
4405   //   %a = ...
4406   //   %b = and i32 %a, 2
4407   //   %c = srl i32 %b, 1
4408   //   brcond i32 %c ...
4409   //
4410   // into
4411   //
4412   //   %a = ...
4413   //   %b = and %a, 2
4414   //   %c = setcc eq %b, 0
4415   //   brcond %c ...
4416   //
4417   // However when after the source operand of SRL is optimized into AND, the SRL
4418   // itself may not be optimized further. Look for it and add the BRCOND into
4419   // the worklist.
4420   if (N->hasOneUse()) {
4421     SDNode *Use = *N->use_begin();
4422     if (Use->getOpcode() == ISD::BRCOND)
4423       AddToWorkList(Use);
4424     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4425       // Also look pass the truncate.
4426       Use = *Use->use_begin();
4427       if (Use->getOpcode() == ISD::BRCOND)
4428         AddToWorkList(Use);
4429     }
4430   }
4431
4432   return SDValue();
4433 }
4434
4435 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4436   SDValue N0 = N->getOperand(0);
4437   EVT VT = N->getValueType(0);
4438
4439   // fold (ctlz c1) -> c2
4440   if (isa<ConstantSDNode>(N0))
4441     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4442   return SDValue();
4443 }
4444
4445 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4446   SDValue N0 = N->getOperand(0);
4447   EVT VT = N->getValueType(0);
4448
4449   // fold (ctlz_zero_undef c1) -> c2
4450   if (isa<ConstantSDNode>(N0))
4451     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4452   return SDValue();
4453 }
4454
4455 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4456   SDValue N0 = N->getOperand(0);
4457   EVT VT = N->getValueType(0);
4458
4459   // fold (cttz c1) -> c2
4460   if (isa<ConstantSDNode>(N0))
4461     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4462   return SDValue();
4463 }
4464
4465 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4466   SDValue N0 = N->getOperand(0);
4467   EVT VT = N->getValueType(0);
4468
4469   // fold (cttz_zero_undef c1) -> c2
4470   if (isa<ConstantSDNode>(N0))
4471     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4472   return SDValue();
4473 }
4474
4475 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4476   SDValue N0 = N->getOperand(0);
4477   EVT VT = N->getValueType(0);
4478
4479   // fold (ctpop c1) -> c2
4480   if (isa<ConstantSDNode>(N0))
4481     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4482   return SDValue();
4483 }
4484
4485 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4486   SDValue N0 = N->getOperand(0);
4487   SDValue N1 = N->getOperand(1);
4488   SDValue N2 = N->getOperand(2);
4489   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4490   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4491   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4492   EVT VT = N->getValueType(0);
4493   EVT VT0 = N0.getValueType();
4494
4495   // fold (select C, X, X) -> X
4496   if (N1 == N2)
4497     return N1;
4498   // fold (select true, X, Y) -> X
4499   if (N0C && !N0C->isNullValue())
4500     return N1;
4501   // fold (select false, X, Y) -> Y
4502   if (N0C && N0C->isNullValue())
4503     return N2;
4504   // fold (select C, 1, X) -> (or C, X)
4505   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4506     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4507   // fold (select C, 0, 1) -> (xor C, 1)
4508   if (VT.isInteger() &&
4509       (VT0 == MVT::i1 ||
4510        (VT0.isInteger() &&
4511         TLI.getBooleanContents(false) ==
4512         TargetLowering::ZeroOrOneBooleanContent)) &&
4513       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4514     SDValue XORNode;
4515     if (VT == VT0)
4516       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4517                          N0, DAG.getConstant(1, VT0));
4518     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4519                           N0, DAG.getConstant(1, VT0));
4520     AddToWorkList(XORNode.getNode());
4521     if (VT.bitsGT(VT0))
4522       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4523     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4524   }
4525   // fold (select C, 0, X) -> (and (not C), X)
4526   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4527     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4528     AddToWorkList(NOTNode.getNode());
4529     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4530   }
4531   // fold (select C, X, 1) -> (or (not C), X)
4532   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4533     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4534     AddToWorkList(NOTNode.getNode());
4535     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4536   }
4537   // fold (select C, X, 0) -> (and C, X)
4538   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4539     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4540   // fold (select X, X, Y) -> (or X, Y)
4541   // fold (select X, 1, Y) -> (or X, Y)
4542   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4543     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4544   // fold (select X, Y, X) -> (and X, Y)
4545   // fold (select X, Y, 0) -> (and X, Y)
4546   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4547     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4548
4549   // If we can fold this based on the true/false value, do so.
4550   if (SimplifySelectOps(N, N1, N2))
4551     return SDValue(N, 0);  // Don't revisit N.
4552
4553   // fold selects based on a setcc into other things, such as min/max/abs
4554   if (N0.getOpcode() == ISD::SETCC) {
4555     // FIXME:
4556     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4557     // having to say they don't support SELECT_CC on every type the DAG knows
4558     // about, since there is no way to mark an opcode illegal at all value types
4559     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4560         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4561       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4562                          N0.getOperand(0), N0.getOperand(1),
4563                          N1, N2, N0.getOperand(2));
4564     return SimplifySelect(SDLoc(N), N0, N1, N2);
4565   }
4566
4567   return SDValue();
4568 }
4569
4570 static
4571 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4572   SDLoc DL(N);
4573   EVT LoVT, HiVT;
4574   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4575
4576   // Split the inputs.
4577   SDValue Lo, Hi, LL, LH, RL, RH;
4578   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4579   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4580
4581   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4582   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4583
4584   return std::make_pair(Lo, Hi);
4585 }
4586
4587 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4588   SDValue N0 = N->getOperand(0);
4589   SDValue N1 = N->getOperand(1);
4590   SDValue N2 = N->getOperand(2);
4591   SDLoc DL(N);
4592
4593   // Canonicalize integer abs.
4594   // vselect (setg[te] X,  0),  X, -X ->
4595   // vselect (setgt    X, -1),  X, -X ->
4596   // vselect (setl[te] X,  0), -X,  X ->
4597   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4598   if (N0.getOpcode() == ISD::SETCC) {
4599     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4600     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4601     bool isAbs = false;
4602     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4603
4604     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4605          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4606         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4607       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4608     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4609              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4610       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4611
4612     if (isAbs) {
4613       EVT VT = LHS.getValueType();
4614       SDValue Shift = DAG.getNode(
4615           ISD::SRA, DL, VT, LHS,
4616           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4617       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4618       AddToWorkList(Shift.getNode());
4619       AddToWorkList(Add.getNode());
4620       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4621     }
4622   }
4623
4624   // If the VSELECT result requires splitting and the mask is provided by a
4625   // SETCC, then split both nodes and its operands before legalization. This
4626   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4627   // and enables future optimizations (e.g. min/max pattern matching on X86).
4628   if (N0.getOpcode() == ISD::SETCC) {
4629     EVT VT = N->getValueType(0);
4630
4631     // Check if any splitting is required.
4632     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4633         TargetLowering::TypeSplitVector)
4634       return SDValue();
4635
4636     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4637     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4638     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4639     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4640
4641     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4642     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4643
4644     // Add the new VSELECT nodes to the work list in case they need to be split
4645     // again.
4646     AddToWorkList(Lo.getNode());
4647     AddToWorkList(Hi.getNode());
4648
4649     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4650   }
4651
4652   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4653   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4654     return N1;
4655   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4656   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4657     return N2;
4658
4659   return SDValue();
4660 }
4661
4662 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4663   SDValue N0 = N->getOperand(0);
4664   SDValue N1 = N->getOperand(1);
4665   SDValue N2 = N->getOperand(2);
4666   SDValue N3 = N->getOperand(3);
4667   SDValue N4 = N->getOperand(4);
4668   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4669
4670   // fold select_cc lhs, rhs, x, x, cc -> x
4671   if (N2 == N3)
4672     return N2;
4673
4674   // Determine if the condition we're dealing with is constant
4675   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4676                               N0, N1, CC, SDLoc(N), false);
4677   if (SCC.getNode()) {
4678     AddToWorkList(SCC.getNode());
4679
4680     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4681       if (!SCCC->isNullValue())
4682         return N2;    // cond always true -> true val
4683       else
4684         return N3;    // cond always false -> false val
4685     }
4686
4687     // Fold to a simpler select_cc
4688     if (SCC.getOpcode() == ISD::SETCC)
4689       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4690                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4691                          SCC.getOperand(2));
4692   }
4693
4694   // If we can fold this based on the true/false value, do so.
4695   if (SimplifySelectOps(N, N2, N3))
4696     return SDValue(N, 0);  // Don't revisit N.
4697
4698   // fold select_cc into other things, such as min/max/abs
4699   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4700 }
4701
4702 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4703   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4704                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4705                        SDLoc(N));
4706 }
4707
4708 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4709 // dag node into a ConstantSDNode or a build_vector of constants.
4710 // This function is called by the DAGCombiner when visiting sext/zext/aext
4711 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4712 // Vector extends are not folded if operations are legal; this is to
4713 // avoid introducing illegal build_vector dag nodes.
4714 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4715                                          SelectionDAG &DAG, bool LegalTypes,
4716                                          bool LegalOperations) {
4717   unsigned Opcode = N->getOpcode();
4718   SDValue N0 = N->getOperand(0);
4719   EVT VT = N->getValueType(0);
4720
4721   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4722          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4723
4724   // fold (sext c1) -> c1
4725   // fold (zext c1) -> c1
4726   // fold (aext c1) -> c1
4727   if (isa<ConstantSDNode>(N0))
4728     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4729
4730   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4731   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4732   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4733   EVT SVT = VT.getScalarType();
4734   if (!(VT.isVector() &&
4735       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4736       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4737     return nullptr;
4738   
4739   // We can fold this node into a build_vector.
4740   unsigned VTBits = SVT.getSizeInBits();
4741   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4742   unsigned ShAmt = VTBits - EVTBits;
4743   SmallVector<SDValue, 8> Elts;
4744   unsigned NumElts = N0->getNumOperands();
4745   SDLoc DL(N);
4746
4747   for (unsigned i=0; i != NumElts; ++i) {
4748     SDValue Op = N0->getOperand(i);
4749     if (Op->getOpcode() == ISD::UNDEF) {
4750       Elts.push_back(DAG.getUNDEF(SVT));
4751       continue;
4752     }
4753
4754     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4755     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4756     if (Opcode == ISD::SIGN_EXTEND)
4757       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4758                                      SVT));
4759     else
4760       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4761                                      SVT));
4762   }
4763
4764   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4765 }
4766
4767 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4768 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4769 // transformation. Returns true if extension are possible and the above
4770 // mentioned transformation is profitable.
4771 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4772                                     unsigned ExtOpc,
4773                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4774                                     const TargetLowering &TLI) {
4775   bool HasCopyToRegUses = false;
4776   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4777   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4778                             UE = N0.getNode()->use_end();
4779        UI != UE; ++UI) {
4780     SDNode *User = *UI;
4781     if (User == N)
4782       continue;
4783     if (UI.getUse().getResNo() != N0.getResNo())
4784       continue;
4785     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4786     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4787       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4788       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4789         // Sign bits will be lost after a zext.
4790         return false;
4791       bool Add = false;
4792       for (unsigned i = 0; i != 2; ++i) {
4793         SDValue UseOp = User->getOperand(i);
4794         if (UseOp == N0)
4795           continue;
4796         if (!isa<ConstantSDNode>(UseOp))
4797           return false;
4798         Add = true;
4799       }
4800       if (Add)
4801         ExtendNodes.push_back(User);
4802       continue;
4803     }
4804     // If truncates aren't free and there are users we can't
4805     // extend, it isn't worthwhile.
4806     if (!isTruncFree)
4807       return false;
4808     // Remember if this value is live-out.
4809     if (User->getOpcode() == ISD::CopyToReg)
4810       HasCopyToRegUses = true;
4811   }
4812
4813   if (HasCopyToRegUses) {
4814     bool BothLiveOut = false;
4815     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4816          UI != UE; ++UI) {
4817       SDUse &Use = UI.getUse();
4818       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4819         BothLiveOut = true;
4820         break;
4821       }
4822     }
4823     if (BothLiveOut)
4824       // Both unextended and extended values are live out. There had better be
4825       // a good reason for the transformation.
4826       return ExtendNodes.size();
4827   }
4828   return true;
4829 }
4830
4831 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4832                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4833                                   ISD::NodeType ExtType) {
4834   // Extend SetCC uses if necessary.
4835   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4836     SDNode *SetCC = SetCCs[i];
4837     SmallVector<SDValue, 4> Ops;
4838
4839     for (unsigned j = 0; j != 2; ++j) {
4840       SDValue SOp = SetCC->getOperand(j);
4841       if (SOp == Trunc)
4842         Ops.push_back(ExtLoad);
4843       else
4844         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4845     }
4846
4847     Ops.push_back(SetCC->getOperand(2));
4848     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4849   }
4850 }
4851
4852 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4853   SDValue N0 = N->getOperand(0);
4854   EVT VT = N->getValueType(0);
4855
4856   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4857                                               LegalOperations))
4858     return SDValue(Res, 0);
4859
4860   // fold (sext (sext x)) -> (sext x)
4861   // fold (sext (aext x)) -> (sext x)
4862   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4863     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4864                        N0.getOperand(0));
4865
4866   if (N0.getOpcode() == ISD::TRUNCATE) {
4867     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4868     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4869     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4870     if (NarrowLoad.getNode()) {
4871       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4872       if (NarrowLoad.getNode() != N0.getNode()) {
4873         CombineTo(N0.getNode(), NarrowLoad);
4874         // CombineTo deleted the truncate, if needed, but not what's under it.
4875         AddToWorkList(oye);
4876       }
4877       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4878     }
4879
4880     // See if the value being truncated is already sign extended.  If so, just
4881     // eliminate the trunc/sext pair.
4882     SDValue Op = N0.getOperand(0);
4883     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4884     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4885     unsigned DestBits = VT.getScalarType().getSizeInBits();
4886     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4887
4888     if (OpBits == DestBits) {
4889       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4890       // bits, it is already ready.
4891       if (NumSignBits > DestBits-MidBits)
4892         return Op;
4893     } else if (OpBits < DestBits) {
4894       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4895       // bits, just sext from i32.
4896       if (NumSignBits > OpBits-MidBits)
4897         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4898     } else {
4899       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4900       // bits, just truncate to i32.
4901       if (NumSignBits > OpBits-MidBits)
4902         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4903     }
4904
4905     // fold (sext (truncate x)) -> (sextinreg x).
4906     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4907                                                  N0.getValueType())) {
4908       if (OpBits < DestBits)
4909         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4910       else if (OpBits > DestBits)
4911         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4912       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4913                          DAG.getValueType(N0.getValueType()));
4914     }
4915   }
4916
4917   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4918   // None of the supported targets knows how to perform load and sign extend
4919   // on vectors in one instruction.  We only perform this transformation on
4920   // scalars.
4921   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4922       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4923       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4924        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4925     bool DoXform = true;
4926     SmallVector<SDNode*, 4> SetCCs;
4927     if (!N0.hasOneUse())
4928       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4929     if (DoXform) {
4930       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4931       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4932                                        LN0->getChain(),
4933                                        LN0->getBasePtr(), N0.getValueType(),
4934                                        LN0->getMemOperand());
4935       CombineTo(N, ExtLoad);
4936       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4937                                   N0.getValueType(), ExtLoad);
4938       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4939       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4940                       ISD::SIGN_EXTEND);
4941       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4942     }
4943   }
4944
4945   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4946   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4947   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4948       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4949     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4950     EVT MemVT = LN0->getMemoryVT();
4951     if ((!LegalOperations && !LN0->isVolatile()) ||
4952         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4953       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4954                                        LN0->getChain(),
4955                                        LN0->getBasePtr(), MemVT,
4956                                        LN0->getMemOperand());
4957       CombineTo(N, ExtLoad);
4958       CombineTo(N0.getNode(),
4959                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4960                             N0.getValueType(), ExtLoad),
4961                 ExtLoad.getValue(1));
4962       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4963     }
4964   }
4965
4966   // fold (sext (and/or/xor (load x), cst)) ->
4967   //      (and/or/xor (sextload x), (sext cst))
4968   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4969        N0.getOpcode() == ISD::XOR) &&
4970       isa<LoadSDNode>(N0.getOperand(0)) &&
4971       N0.getOperand(1).getOpcode() == ISD::Constant &&
4972       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4973       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4974     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4975     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4976       bool DoXform = true;
4977       SmallVector<SDNode*, 4> SetCCs;
4978       if (!N0.hasOneUse())
4979         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4980                                           SetCCs, TLI);
4981       if (DoXform) {
4982         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4983                                          LN0->getChain(), LN0->getBasePtr(),
4984                                          LN0->getMemoryVT(),
4985                                          LN0->getMemOperand());
4986         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4987         Mask = Mask.sext(VT.getSizeInBits());
4988         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4989                                   ExtLoad, DAG.getConstant(Mask, VT));
4990         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4991                                     SDLoc(N0.getOperand(0)),
4992                                     N0.getOperand(0).getValueType(), ExtLoad);
4993         CombineTo(N, And);
4994         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4995         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4996                         ISD::SIGN_EXTEND);
4997         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4998       }
4999     }
5000   }
5001
5002   if (N0.getOpcode() == ISD::SETCC) {
5003     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5004     // Only do this before legalize for now.
5005     if (VT.isVector() && !LegalOperations &&
5006         TLI.getBooleanContents(true) ==
5007           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5008       EVT N0VT = N0.getOperand(0).getValueType();
5009       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5010       // of the same size as the compared operands. Only optimize sext(setcc())
5011       // if this is the case.
5012       EVT SVT = getSetCCResultType(N0VT);
5013
5014       // We know that the # elements of the results is the same as the
5015       // # elements of the compare (and the # elements of the compare result
5016       // for that matter).  Check to see that they are the same size.  If so,
5017       // we know that the element size of the sext'd result matches the
5018       // element size of the compare operands.
5019       if (VT.getSizeInBits() == SVT.getSizeInBits())
5020         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5021                              N0.getOperand(1),
5022                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5023
5024       // If the desired elements are smaller or larger than the source
5025       // elements we can use a matching integer vector type and then
5026       // truncate/sign extend
5027       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5028       if (SVT == MatchingVectorType) {
5029         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5030                                N0.getOperand(0), N0.getOperand(1),
5031                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5032         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5033       }
5034     }
5035
5036     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5037     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5038     SDValue NegOne =
5039       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5040     SDValue SCC =
5041       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5042                        NegOne, DAG.getConstant(0, VT),
5043                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5044     if (SCC.getNode()) return SCC;
5045
5046     if (!VT.isVector()) {
5047       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5048       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5049         SDLoc DL(N);
5050         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5051         SDValue SetCC = DAG.getSetCC(DL,
5052                                      SetCCVT,
5053                                      N0.getOperand(0), N0.getOperand(1), CC);
5054         EVT SelectVT = getSetCCResultType(VT);
5055         return DAG.getSelect(DL, VT,
5056                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5057                              NegOne, DAG.getConstant(0, VT));
5058
5059       }
5060     }
5061   }
5062
5063   // fold (sext x) -> (zext x) if the sign bit is known zero.
5064   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5065       DAG.SignBitIsZero(N0))
5066     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5067
5068   return SDValue();
5069 }
5070
5071 // isTruncateOf - If N is a truncate of some other value, return true, record
5072 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5073 // This function computes KnownZero to avoid a duplicated call to
5074 // ComputeMaskedBits in the caller.
5075 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5076                          APInt &KnownZero) {
5077   APInt KnownOne;
5078   if (N->getOpcode() == ISD::TRUNCATE) {
5079     Op = N->getOperand(0);
5080     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5081     return true;
5082   }
5083
5084   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5085       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5086     return false;
5087
5088   SDValue Op0 = N->getOperand(0);
5089   SDValue Op1 = N->getOperand(1);
5090   assert(Op0.getValueType() == Op1.getValueType());
5091
5092   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5093   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5094   if (COp0 && COp0->isNullValue())
5095     Op = Op1;
5096   else if (COp1 && COp1->isNullValue())
5097     Op = Op0;
5098   else
5099     return false;
5100
5101   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5102
5103   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5104     return false;
5105
5106   return true;
5107 }
5108
5109 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5110   SDValue N0 = N->getOperand(0);
5111   EVT VT = N->getValueType(0);
5112
5113   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5114                                               LegalOperations))
5115     return SDValue(Res, 0);
5116
5117   // fold (zext (zext x)) -> (zext x)
5118   // fold (zext (aext x)) -> (zext x)
5119   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5120     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5121                        N0.getOperand(0));
5122
5123   // fold (zext (truncate x)) -> (zext x) or
5124   //      (zext (truncate x)) -> (truncate x)
5125   // This is valid when the truncated bits of x are already zero.
5126   // FIXME: We should extend this to work for vectors too.
5127   SDValue Op;
5128   APInt KnownZero;
5129   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5130     APInt TruncatedBits =
5131       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5132       APInt(Op.getValueSizeInBits(), 0) :
5133       APInt::getBitsSet(Op.getValueSizeInBits(),
5134                         N0.getValueSizeInBits(),
5135                         std::min(Op.getValueSizeInBits(),
5136                                  VT.getSizeInBits()));
5137     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5138       if (VT.bitsGT(Op.getValueType()))
5139         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5140       if (VT.bitsLT(Op.getValueType()))
5141         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5142
5143       return Op;
5144     }
5145   }
5146
5147   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5148   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5149   if (N0.getOpcode() == ISD::TRUNCATE) {
5150     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5151     if (NarrowLoad.getNode()) {
5152       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5153       if (NarrowLoad.getNode() != N0.getNode()) {
5154         CombineTo(N0.getNode(), NarrowLoad);
5155         // CombineTo deleted the truncate, if needed, but not what's under it.
5156         AddToWorkList(oye);
5157       }
5158       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5159     }
5160   }
5161
5162   // fold (zext (truncate x)) -> (and x, mask)
5163   if (N0.getOpcode() == ISD::TRUNCATE &&
5164       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5165
5166     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5167     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5168     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5169     if (NarrowLoad.getNode()) {
5170       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5171       if (NarrowLoad.getNode() != N0.getNode()) {
5172         CombineTo(N0.getNode(), NarrowLoad);
5173         // CombineTo deleted the truncate, if needed, but not what's under it.
5174         AddToWorkList(oye);
5175       }
5176       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5177     }
5178
5179     SDValue Op = N0.getOperand(0);
5180     if (Op.getValueType().bitsLT(VT)) {
5181       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5182       AddToWorkList(Op.getNode());
5183     } else if (Op.getValueType().bitsGT(VT)) {
5184       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5185       AddToWorkList(Op.getNode());
5186     }
5187     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5188                                   N0.getValueType().getScalarType());
5189   }
5190
5191   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5192   // if either of the casts is not free.
5193   if (N0.getOpcode() == ISD::AND &&
5194       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5195       N0.getOperand(1).getOpcode() == ISD::Constant &&
5196       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5197                            N0.getValueType()) ||
5198        !TLI.isZExtFree(N0.getValueType(), VT))) {
5199     SDValue X = N0.getOperand(0).getOperand(0);
5200     if (X.getValueType().bitsLT(VT)) {
5201       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5202     } else if (X.getValueType().bitsGT(VT)) {
5203       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5204     }
5205     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5206     Mask = Mask.zext(VT.getSizeInBits());
5207     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5208                        X, DAG.getConstant(Mask, VT));
5209   }
5210
5211   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5212   // None of the supported targets knows how to perform load and vector_zext
5213   // on vectors in one instruction.  We only perform this transformation on
5214   // scalars.
5215   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5216       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5217       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5218        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5219     bool DoXform = true;
5220     SmallVector<SDNode*, 4> SetCCs;
5221     if (!N0.hasOneUse())
5222       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5223     if (DoXform) {
5224       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5225       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5226                                        LN0->getChain(),
5227                                        LN0->getBasePtr(), N0.getValueType(),
5228                                        LN0->getMemOperand());
5229       CombineTo(N, ExtLoad);
5230       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5231                                   N0.getValueType(), ExtLoad);
5232       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5233
5234       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5235                       ISD::ZERO_EXTEND);
5236       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5237     }
5238   }
5239
5240   // fold (zext (and/or/xor (load x), cst)) ->
5241   //      (and/or/xor (zextload x), (zext cst))
5242   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5243        N0.getOpcode() == ISD::XOR) &&
5244       isa<LoadSDNode>(N0.getOperand(0)) &&
5245       N0.getOperand(1).getOpcode() == ISD::Constant &&
5246       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5247       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5248     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5249     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5250       bool DoXform = true;
5251       SmallVector<SDNode*, 4> SetCCs;
5252       if (!N0.hasOneUse())
5253         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5254                                           SetCCs, TLI);
5255       if (DoXform) {
5256         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5257                                          LN0->getChain(), LN0->getBasePtr(),
5258                                          LN0->getMemoryVT(),
5259                                          LN0->getMemOperand());
5260         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5261         Mask = Mask.zext(VT.getSizeInBits());
5262         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5263                                   ExtLoad, DAG.getConstant(Mask, VT));
5264         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5265                                     SDLoc(N0.getOperand(0)),
5266                                     N0.getOperand(0).getValueType(), ExtLoad);
5267         CombineTo(N, And);
5268         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5269         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5270                         ISD::ZERO_EXTEND);
5271         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5272       }
5273     }
5274   }
5275
5276   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5277   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5278   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5279       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5280     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5281     EVT MemVT = LN0->getMemoryVT();
5282     if ((!LegalOperations && !LN0->isVolatile()) ||
5283         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5284       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5285                                        LN0->getChain(),
5286                                        LN0->getBasePtr(), MemVT,
5287                                        LN0->getMemOperand());
5288       CombineTo(N, ExtLoad);
5289       CombineTo(N0.getNode(),
5290                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5291                             ExtLoad),
5292                 ExtLoad.getValue(1));
5293       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5294     }
5295   }
5296
5297   if (N0.getOpcode() == ISD::SETCC) {
5298     if (!LegalOperations && VT.isVector() &&
5299         N0.getValueType().getVectorElementType() == MVT::i1) {
5300       EVT N0VT = N0.getOperand(0).getValueType();
5301       if (getSetCCResultType(N0VT) == N0.getValueType())
5302         return SDValue();
5303
5304       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5305       // Only do this before legalize for now.
5306       EVT EltVT = VT.getVectorElementType();
5307       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5308                                     DAG.getConstant(1, EltVT));
5309       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5310         // We know that the # elements of the results is the same as the
5311         // # elements of the compare (and the # elements of the compare result
5312         // for that matter).  Check to see that they are the same size.  If so,
5313         // we know that the element size of the sext'd result matches the
5314         // element size of the compare operands.
5315         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5316                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5317                                          N0.getOperand(1),
5318                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5319                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5320                                        OneOps));
5321
5322       // If the desired elements are smaller or larger than the source
5323       // elements we can use a matching integer vector type and then
5324       // truncate/sign extend
5325       EVT MatchingElementType =
5326         EVT::getIntegerVT(*DAG.getContext(),
5327                           N0VT.getScalarType().getSizeInBits());
5328       EVT MatchingVectorType =
5329         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5330                          N0VT.getVectorNumElements());
5331       SDValue VsetCC =
5332         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5333                       N0.getOperand(1),
5334                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5335       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5336                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5337                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5338     }
5339
5340     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5341     SDValue SCC =
5342       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5343                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5344                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5345     if (SCC.getNode()) return SCC;
5346   }
5347
5348   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5349   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5350       isa<ConstantSDNode>(N0.getOperand(1)) &&
5351       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5352       N0.hasOneUse()) {
5353     SDValue ShAmt = N0.getOperand(1);
5354     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5355     if (N0.getOpcode() == ISD::SHL) {
5356       SDValue InnerZExt = N0.getOperand(0);
5357       // If the original shl may be shifting out bits, do not perform this
5358       // transformation.
5359       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5360         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5361       if (ShAmtVal > KnownZeroBits)
5362         return SDValue();
5363     }
5364
5365     SDLoc DL(N);
5366
5367     // Ensure that the shift amount is wide enough for the shifted value.
5368     if (VT.getSizeInBits() >= 256)
5369       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5370
5371     return DAG.getNode(N0.getOpcode(), DL, VT,
5372                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5373                        ShAmt);
5374   }
5375
5376   return SDValue();
5377 }
5378
5379 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5380   SDValue N0 = N->getOperand(0);
5381   EVT VT = N->getValueType(0);
5382
5383   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5384                                               LegalOperations))
5385     return SDValue(Res, 0);
5386
5387   // fold (aext (aext x)) -> (aext x)
5388   // fold (aext (zext x)) -> (zext x)
5389   // fold (aext (sext x)) -> (sext x)
5390   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5391       N0.getOpcode() == ISD::ZERO_EXTEND ||
5392       N0.getOpcode() == ISD::SIGN_EXTEND)
5393     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5394
5395   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5396   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5397   if (N0.getOpcode() == ISD::TRUNCATE) {
5398     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5399     if (NarrowLoad.getNode()) {
5400       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5401       if (NarrowLoad.getNode() != N0.getNode()) {
5402         CombineTo(N0.getNode(), NarrowLoad);
5403         // CombineTo deleted the truncate, if needed, but not what's under it.
5404         AddToWorkList(oye);
5405       }
5406       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5407     }
5408   }
5409
5410   // fold (aext (truncate x))
5411   if (N0.getOpcode() == ISD::TRUNCATE) {
5412     SDValue TruncOp = N0.getOperand(0);
5413     if (TruncOp.getValueType() == VT)
5414       return TruncOp; // x iff x size == zext size.
5415     if (TruncOp.getValueType().bitsGT(VT))
5416       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5417     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5418   }
5419
5420   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5421   // if the trunc is not free.
5422   if (N0.getOpcode() == ISD::AND &&
5423       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5424       N0.getOperand(1).getOpcode() == ISD::Constant &&
5425       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5426                           N0.getValueType())) {
5427     SDValue X = N0.getOperand(0).getOperand(0);
5428     if (X.getValueType().bitsLT(VT)) {
5429       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5430     } else if (X.getValueType().bitsGT(VT)) {
5431       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5432     }
5433     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5434     Mask = Mask.zext(VT.getSizeInBits());
5435     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5436                        X, DAG.getConstant(Mask, VT));
5437   }
5438
5439   // fold (aext (load x)) -> (aext (truncate (extload x)))
5440   // None of the supported targets knows how to perform load and any_ext
5441   // on vectors in one instruction.  We only perform this transformation on
5442   // scalars.
5443   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5444       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5445       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5446        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5447     bool DoXform = true;
5448     SmallVector<SDNode*, 4> SetCCs;
5449     if (!N0.hasOneUse())
5450       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5451     if (DoXform) {
5452       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5453       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5454                                        LN0->getChain(),
5455                                        LN0->getBasePtr(), N0.getValueType(),
5456                                        LN0->getMemOperand());
5457       CombineTo(N, ExtLoad);
5458       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5459                                   N0.getValueType(), ExtLoad);
5460       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5461       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5462                       ISD::ANY_EXTEND);
5463       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5464     }
5465   }
5466
5467   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5468   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5469   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5470   if (N0.getOpcode() == ISD::LOAD &&
5471       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5472       N0.hasOneUse()) {
5473     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5474     ISD::LoadExtType ExtType = LN0->getExtensionType();
5475     EVT MemVT = LN0->getMemoryVT();
5476     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5477       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5478                                        VT, LN0->getChain(), LN0->getBasePtr(),
5479                                        MemVT, LN0->getMemOperand());
5480       CombineTo(N, ExtLoad);
5481       CombineTo(N0.getNode(),
5482                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5483                             N0.getValueType(), ExtLoad),
5484                 ExtLoad.getValue(1));
5485       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5486     }
5487   }
5488
5489   if (N0.getOpcode() == ISD::SETCC) {
5490     // For vectors:
5491     // aext(setcc) -> vsetcc
5492     // aext(setcc) -> truncate(vsetcc)
5493     // aext(setcc) -> aext(vsetcc)
5494     // Only do this before legalize for now.
5495     if (VT.isVector() && !LegalOperations) {
5496       EVT N0VT = N0.getOperand(0).getValueType();
5497         // We know that the # elements of the results is the same as the
5498         // # elements of the compare (and the # elements of the compare result
5499         // for that matter).  Check to see that they are the same size.  If so,
5500         // we know that the element size of the sext'd result matches the
5501         // element size of the compare operands.
5502       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5503         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5504                              N0.getOperand(1),
5505                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5506       // If the desired elements are smaller or larger than the source
5507       // elements we can use a matching integer vector type and then
5508       // truncate/any extend
5509       else {
5510         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5511         SDValue VsetCC =
5512           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5513                         N0.getOperand(1),
5514                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5515         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5516       }
5517     }
5518
5519     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5520     SDValue SCC =
5521       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5522                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5523                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5524     if (SCC.getNode())
5525       return SCC;
5526   }
5527
5528   return SDValue();
5529 }
5530
5531 /// GetDemandedBits - See if the specified operand can be simplified with the
5532 /// knowledge that only the bits specified by Mask are used.  If so, return the
5533 /// simpler operand, otherwise return a null SDValue.
5534 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5535   switch (V.getOpcode()) {
5536   default: break;
5537   case ISD::Constant: {
5538     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5539     assert(CV && "Const value should be ConstSDNode.");
5540     const APInt &CVal = CV->getAPIntValue();
5541     APInt NewVal = CVal & Mask;
5542     if (NewVal != CVal)
5543       return DAG.getConstant(NewVal, V.getValueType());
5544     break;
5545   }
5546   case ISD::OR:
5547   case ISD::XOR:
5548     // If the LHS or RHS don't contribute bits to the or, drop them.
5549     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5550       return V.getOperand(1);
5551     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5552       return V.getOperand(0);
5553     break;
5554   case ISD::SRL:
5555     // Only look at single-use SRLs.
5556     if (!V.getNode()->hasOneUse())
5557       break;
5558     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5559       // See if we can recursively simplify the LHS.
5560       unsigned Amt = RHSC->getZExtValue();
5561
5562       // Watch out for shift count overflow though.
5563       if (Amt >= Mask.getBitWidth()) break;
5564       APInt NewMask = Mask << Amt;
5565       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5566       if (SimplifyLHS.getNode())
5567         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5568                            SimplifyLHS, V.getOperand(1));
5569     }
5570   }
5571   return SDValue();
5572 }
5573
5574 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5575 /// bits and then truncated to a narrower type and where N is a multiple
5576 /// of number of bits of the narrower type, transform it to a narrower load
5577 /// from address + N / num of bits of new type. If the result is to be
5578 /// extended, also fold the extension to form a extending load.
5579 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5580   unsigned Opc = N->getOpcode();
5581
5582   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5583   SDValue N0 = N->getOperand(0);
5584   EVT VT = N->getValueType(0);
5585   EVT ExtVT = VT;
5586
5587   // This transformation isn't valid for vector loads.
5588   if (VT.isVector())
5589     return SDValue();
5590
5591   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5592   // extended to VT.
5593   if (Opc == ISD::SIGN_EXTEND_INREG) {
5594     ExtType = ISD::SEXTLOAD;
5595     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5596   } else if (Opc == ISD::SRL) {
5597     // Another special-case: SRL is basically zero-extending a narrower value.
5598     ExtType = ISD::ZEXTLOAD;
5599     N0 = SDValue(N, 0);
5600     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5601     if (!N01) return SDValue();
5602     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5603                               VT.getSizeInBits() - N01->getZExtValue());
5604   }
5605   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5606     return SDValue();
5607
5608   unsigned EVTBits = ExtVT.getSizeInBits();
5609
5610   // Do not generate loads of non-round integer types since these can
5611   // be expensive (and would be wrong if the type is not byte sized).
5612   if (!ExtVT.isRound())
5613     return SDValue();
5614
5615   unsigned ShAmt = 0;
5616   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5617     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5618       ShAmt = N01->getZExtValue();
5619       // Is the shift amount a multiple of size of VT?
5620       if ((ShAmt & (EVTBits-1)) == 0) {
5621         N0 = N0.getOperand(0);
5622         // Is the load width a multiple of size of VT?
5623         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5624           return SDValue();
5625       }
5626
5627       // At this point, we must have a load or else we can't do the transform.
5628       if (!isa<LoadSDNode>(N0)) return SDValue();
5629
5630       // Because a SRL must be assumed to *need* to zero-extend the high bits
5631       // (as opposed to anyext the high bits), we can't combine the zextload
5632       // lowering of SRL and an sextload.
5633       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5634         return SDValue();
5635
5636       // If the shift amount is larger than the input type then we're not
5637       // accessing any of the loaded bytes.  If the load was a zextload/extload
5638       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5639       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5640         return SDValue();
5641     }
5642   }
5643
5644   // If the load is shifted left (and the result isn't shifted back right),
5645   // we can fold the truncate through the shift.
5646   unsigned ShLeftAmt = 0;
5647   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5648       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5649     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5650       ShLeftAmt = N01->getZExtValue();
5651       N0 = N0.getOperand(0);
5652     }
5653   }
5654
5655   // If we haven't found a load, we can't narrow it.  Don't transform one with
5656   // multiple uses, this would require adding a new load.
5657   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5658     return SDValue();
5659
5660   // Don't change the width of a volatile load.
5661   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5662   if (LN0->isVolatile())
5663     return SDValue();
5664
5665   // Verify that we are actually reducing a load width here.
5666   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5667     return SDValue();
5668
5669   // For the transform to be legal, the load must produce only two values
5670   // (the value loaded and the chain).  Don't transform a pre-increment
5671   // load, for example, which produces an extra value.  Otherwise the
5672   // transformation is not equivalent, and the downstream logic to replace
5673   // uses gets things wrong.
5674   if (LN0->getNumValues() > 2)
5675     return SDValue();
5676
5677   // If the load that we're shrinking is an extload and we're not just
5678   // discarding the extension we can't simply shrink the load. Bail.
5679   // TODO: It would be possible to merge the extensions in some cases.
5680   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5681       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5682     return SDValue();
5683
5684   EVT PtrType = N0.getOperand(1).getValueType();
5685
5686   if (PtrType == MVT::Untyped || PtrType.isExtended())
5687     // It's not possible to generate a constant of extended or untyped type.
5688     return SDValue();
5689
5690   // For big endian targets, we need to adjust the offset to the pointer to
5691   // load the correct bytes.
5692   if (TLI.isBigEndian()) {
5693     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5694     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5695     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5696   }
5697
5698   uint64_t PtrOff = ShAmt / 8;
5699   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5700   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5701                                PtrType, LN0->getBasePtr(),
5702                                DAG.getConstant(PtrOff, PtrType));
5703   AddToWorkList(NewPtr.getNode());
5704
5705   SDValue Load;
5706   if (ExtType == ISD::NON_EXTLOAD)
5707     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5708                         LN0->getPointerInfo().getWithOffset(PtrOff),
5709                         LN0->isVolatile(), LN0->isNonTemporal(),
5710                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5711   else
5712     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5713                           LN0->getPointerInfo().getWithOffset(PtrOff),
5714                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5715                           NewAlign, LN0->getTBAAInfo());
5716
5717   // Replace the old load's chain with the new load's chain.
5718   WorkListRemover DeadNodes(*this);
5719   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5720
5721   // Shift the result left, if we've swallowed a left shift.
5722   SDValue Result = Load;
5723   if (ShLeftAmt != 0) {
5724     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5725     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5726       ShImmTy = VT;
5727     // If the shift amount is as large as the result size (but, presumably,
5728     // no larger than the source) then the useful bits of the result are
5729     // zero; we can't simply return the shortened shift, because the result
5730     // of that operation is undefined.
5731     if (ShLeftAmt >= VT.getSizeInBits())
5732       Result = DAG.getConstant(0, VT);
5733     else
5734       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5735                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5736   }
5737
5738   // Return the new loaded value.
5739   return Result;
5740 }
5741
5742 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5743   SDValue N0 = N->getOperand(0);
5744   SDValue N1 = N->getOperand(1);
5745   EVT VT = N->getValueType(0);
5746   EVT EVT = cast<VTSDNode>(N1)->getVT();
5747   unsigned VTBits = VT.getScalarType().getSizeInBits();
5748   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5749
5750   // fold (sext_in_reg c1) -> c1
5751   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5752     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5753
5754   // If the input is already sign extended, just drop the extension.
5755   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5756     return N0;
5757
5758   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5759   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5760       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5761     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5762                        N0.getOperand(0), N1);
5763
5764   // fold (sext_in_reg (sext x)) -> (sext x)
5765   // fold (sext_in_reg (aext x)) -> (sext x)
5766   // if x is small enough.
5767   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5768     SDValue N00 = N0.getOperand(0);
5769     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5770         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5771       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5772   }
5773
5774   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5775   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5776     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5777
5778   // fold operands of sext_in_reg based on knowledge that the top bits are not
5779   // demanded.
5780   if (SimplifyDemandedBits(SDValue(N, 0)))
5781     return SDValue(N, 0);
5782
5783   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5784   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5785   SDValue NarrowLoad = ReduceLoadWidth(N);
5786   if (NarrowLoad.getNode())
5787     return NarrowLoad;
5788
5789   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5790   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5791   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5792   if (N0.getOpcode() == ISD::SRL) {
5793     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5794       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5795         // We can turn this into an SRA iff the input to the SRL is already sign
5796         // extended enough.
5797         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5798         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5799           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5800                              N0.getOperand(0), N0.getOperand(1));
5801       }
5802   }
5803
5804   // fold (sext_inreg (extload x)) -> (sextload x)
5805   if (ISD::isEXTLoad(N0.getNode()) &&
5806       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5807       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5808       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5809        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5810     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5811     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5812                                      LN0->getChain(),
5813                                      LN0->getBasePtr(), EVT,
5814                                      LN0->getMemOperand());
5815     CombineTo(N, ExtLoad);
5816     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5817     AddToWorkList(ExtLoad.getNode());
5818     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5819   }
5820   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5821   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5822       N0.hasOneUse() &&
5823       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5824       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5825        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5826     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5827     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5828                                      LN0->getChain(),
5829                                      LN0->getBasePtr(), EVT,
5830                                      LN0->getMemOperand());
5831     CombineTo(N, ExtLoad);
5832     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5833     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5834   }
5835
5836   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5837   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5838     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5839                                        N0.getOperand(1), false);
5840     if (BSwap.getNode())
5841       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5842                          BSwap, N1);
5843   }
5844
5845   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5846   // into a build_vector.
5847   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5848     SmallVector<SDValue, 8> Elts;
5849     unsigned NumElts = N0->getNumOperands();
5850     unsigned ShAmt = VTBits - EVTBits;
5851
5852     for (unsigned i = 0; i != NumElts; ++i) {
5853       SDValue Op = N0->getOperand(i);
5854       if (Op->getOpcode() == ISD::UNDEF) {
5855         Elts.push_back(Op);
5856         continue;
5857       }
5858
5859       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5860       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5861       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5862                                      Op.getValueType()));
5863     }
5864
5865     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5866   }
5867
5868   return SDValue();
5869 }
5870
5871 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5872   SDValue N0 = N->getOperand(0);
5873   EVT VT = N->getValueType(0);
5874   bool isLE = TLI.isLittleEndian();
5875
5876   // noop truncate
5877   if (N0.getValueType() == N->getValueType(0))
5878     return N0;
5879   // fold (truncate c1) -> c1
5880   if (isa<ConstantSDNode>(N0))
5881     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5882   // fold (truncate (truncate x)) -> (truncate x)
5883   if (N0.getOpcode() == ISD::TRUNCATE)
5884     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5885   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5886   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5887       N0.getOpcode() == ISD::SIGN_EXTEND ||
5888       N0.getOpcode() == ISD::ANY_EXTEND) {
5889     if (N0.getOperand(0).getValueType().bitsLT(VT))
5890       // if the source is smaller than the dest, we still need an extend
5891       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5892                          N0.getOperand(0));
5893     if (N0.getOperand(0).getValueType().bitsGT(VT))
5894       // if the source is larger than the dest, than we just need the truncate
5895       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5896     // if the source and dest are the same type, we can drop both the extend
5897     // and the truncate.
5898     return N0.getOperand(0);
5899   }
5900
5901   // Fold extract-and-trunc into a narrow extract. For example:
5902   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5903   //   i32 y = TRUNCATE(i64 x)
5904   //        -- becomes --
5905   //   v16i8 b = BITCAST (v2i64 val)
5906   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5907   //
5908   // Note: We only run this optimization after type legalization (which often
5909   // creates this pattern) and before operation legalization after which
5910   // we need to be more careful about the vector instructions that we generate.
5911   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5912       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5913
5914     EVT VecTy = N0.getOperand(0).getValueType();
5915     EVT ExTy = N0.getValueType();
5916     EVT TrTy = N->getValueType(0);
5917
5918     unsigned NumElem = VecTy.getVectorNumElements();
5919     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5920
5921     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5922     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5923
5924     SDValue EltNo = N0->getOperand(1);
5925     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5926       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5927       EVT IndexTy = TLI.getVectorIdxTy();
5928       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5929
5930       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5931                               NVT, N0.getOperand(0));
5932
5933       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5934                          SDLoc(N), TrTy, V,
5935                          DAG.getConstant(Index, IndexTy));
5936     }
5937   }
5938
5939   // Fold a series of buildvector, bitcast, and truncate if possible.
5940   // For example fold
5941   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5942   //   (2xi32 (buildvector x, y)).
5943   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5944       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5945       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5946       N0.getOperand(0).hasOneUse()) {
5947
5948     SDValue BuildVect = N0.getOperand(0);
5949     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5950     EVT TruncVecEltTy = VT.getVectorElementType();
5951
5952     // Check that the element types match.
5953     if (BuildVectEltTy == TruncVecEltTy) {
5954       // Now we only need to compute the offset of the truncated elements.
5955       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5956       unsigned TruncVecNumElts = VT.getVectorNumElements();
5957       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5958
5959       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5960              "Invalid number of elements");
5961
5962       SmallVector<SDValue, 8> Opnds;
5963       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5964         Opnds.push_back(BuildVect.getOperand(i));
5965
5966       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
5967     }
5968   }
5969
5970   // See if we can simplify the input to this truncate through knowledge that
5971   // only the low bits are being used.
5972   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5973   // Currently we only perform this optimization on scalars because vectors
5974   // may have different active low bits.
5975   if (!VT.isVector()) {
5976     SDValue Shorter =
5977       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5978                                                VT.getSizeInBits()));
5979     if (Shorter.getNode())
5980       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5981   }
5982   // fold (truncate (load x)) -> (smaller load x)
5983   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5984   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5985     SDValue Reduced = ReduceLoadWidth(N);
5986     if (Reduced.getNode())
5987       return Reduced;
5988     // Handle the case where the load remains an extending load even
5989     // after truncation.
5990     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5991       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5992       if (!LN0->isVolatile() &&
5993           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5994         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5995                                          VT, LN0->getChain(), LN0->getBasePtr(),
5996                                          LN0->getMemoryVT(),
5997                                          LN0->getMemOperand());
5998         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5999         return NewLoad;
6000       }
6001     }
6002   }
6003   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6004   // where ... are all 'undef'.
6005   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6006     SmallVector<EVT, 8> VTs;
6007     SDValue V;
6008     unsigned Idx = 0;
6009     unsigned NumDefs = 0;
6010
6011     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6012       SDValue X = N0.getOperand(i);
6013       if (X.getOpcode() != ISD::UNDEF) {
6014         V = X;
6015         Idx = i;
6016         NumDefs++;
6017       }
6018       // Stop if more than one members are non-undef.
6019       if (NumDefs > 1)
6020         break;
6021       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6022                                      VT.getVectorElementType(),
6023                                      X.getValueType().getVectorNumElements()));
6024     }
6025
6026     if (NumDefs == 0)
6027       return DAG.getUNDEF(VT);
6028
6029     if (NumDefs == 1) {
6030       assert(V.getNode() && "The single defined operand is empty!");
6031       SmallVector<SDValue, 8> Opnds;
6032       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6033         if (i != Idx) {
6034           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6035           continue;
6036         }
6037         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6038         AddToWorkList(NV.getNode());
6039         Opnds.push_back(NV);
6040       }
6041       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6042     }
6043   }
6044
6045   // Simplify the operands using demanded-bits information.
6046   if (!VT.isVector() &&
6047       SimplifyDemandedBits(SDValue(N, 0)))
6048     return SDValue(N, 0);
6049
6050   return SDValue();
6051 }
6052
6053 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6054   SDValue Elt = N->getOperand(i);
6055   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6056     return Elt.getNode();
6057   return Elt.getOperand(Elt.getResNo()).getNode();
6058 }
6059
6060 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6061 /// if load locations are consecutive.
6062 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6063   assert(N->getOpcode() == ISD::BUILD_PAIR);
6064
6065   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6066   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6067   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6068       LD1->getAddressSpace() != LD2->getAddressSpace())
6069     return SDValue();
6070   EVT LD1VT = LD1->getValueType(0);
6071
6072   if (ISD::isNON_EXTLoad(LD2) &&
6073       LD2->hasOneUse() &&
6074       // If both are volatile this would reduce the number of volatile loads.
6075       // If one is volatile it might be ok, but play conservative and bail out.
6076       !LD1->isVolatile() &&
6077       !LD2->isVolatile() &&
6078       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6079     unsigned Align = LD1->getAlignment();
6080     unsigned NewAlign = TLI.getDataLayout()->
6081       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6082
6083     if (NewAlign <= Align &&
6084         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6085       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6086                          LD1->getBasePtr(), LD1->getPointerInfo(),
6087                          false, false, false, Align);
6088   }
6089
6090   return SDValue();
6091 }
6092
6093 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6094   SDValue N0 = N->getOperand(0);
6095   EVT VT = N->getValueType(0);
6096
6097   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6098   // Only do this before legalize, since afterward the target may be depending
6099   // on the bitconvert.
6100   // First check to see if this is all constant.
6101   if (!LegalTypes &&
6102       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6103       VT.isVector()) {
6104     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6105
6106     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6107     assert(!DestEltVT.isVector() &&
6108            "Element type of vector ValueType must not be vector!");
6109     if (isSimple)
6110       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6111   }
6112
6113   // If the input is a constant, let getNode fold it.
6114   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6115     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6116     if (Res.getNode() != N) {
6117       if (!LegalOperations ||
6118           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6119         return Res;
6120
6121       // Folding it resulted in an illegal node, and it's too late to
6122       // do that. Clean up the old node and forego the transformation.
6123       // Ideally this won't happen very often, because instcombine
6124       // and the earlier dagcombine runs (where illegal nodes are
6125       // permitted) should have folded most of them already.
6126       DAG.DeleteNode(Res.getNode());
6127     }
6128   }
6129
6130   // (conv (conv x, t1), t2) -> (conv x, t2)
6131   if (N0.getOpcode() == ISD::BITCAST)
6132     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6133                        N0.getOperand(0));
6134
6135   // fold (conv (load x)) -> (load (conv*)x)
6136   // If the resultant load doesn't need a higher alignment than the original!
6137   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6138       // Do not change the width of a volatile load.
6139       !cast<LoadSDNode>(N0)->isVolatile() &&
6140       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6141       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6142     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6143     unsigned Align = TLI.getDataLayout()->
6144       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6145     unsigned OrigAlign = LN0->getAlignment();
6146
6147     if (Align <= OrigAlign) {
6148       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6149                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6150                                  LN0->isVolatile(), LN0->isNonTemporal(),
6151                                  LN0->isInvariant(), OrigAlign,
6152                                  LN0->getTBAAInfo());
6153       AddToWorkList(N);
6154       CombineTo(N0.getNode(),
6155                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6156                             N0.getValueType(), Load),
6157                 Load.getValue(1));
6158       return Load;
6159     }
6160   }
6161
6162   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6163   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6164   // This often reduces constant pool loads.
6165   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6166        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6167       N0.getNode()->hasOneUse() && VT.isInteger() &&
6168       !VT.isVector() && !N0.getValueType().isVector()) {
6169     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6170                                   N0.getOperand(0));
6171     AddToWorkList(NewConv.getNode());
6172
6173     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6174     if (N0.getOpcode() == ISD::FNEG)
6175       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6176                          NewConv, DAG.getConstant(SignBit, VT));
6177     assert(N0.getOpcode() == ISD::FABS);
6178     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6179                        NewConv, DAG.getConstant(~SignBit, VT));
6180   }
6181
6182   // fold (bitconvert (fcopysign cst, x)) ->
6183   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6184   // Note that we don't handle (copysign x, cst) because this can always be
6185   // folded to an fneg or fabs.
6186   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6187       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6188       VT.isInteger() && !VT.isVector()) {
6189     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6190     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6191     if (isTypeLegal(IntXVT)) {
6192       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6193                               IntXVT, N0.getOperand(1));
6194       AddToWorkList(X.getNode());
6195
6196       // If X has a different width than the result/lhs, sext it or truncate it.
6197       unsigned VTWidth = VT.getSizeInBits();
6198       if (OrigXWidth < VTWidth) {
6199         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6200         AddToWorkList(X.getNode());
6201       } else if (OrigXWidth > VTWidth) {
6202         // To get the sign bit in the right place, we have to shift it right
6203         // before truncating.
6204         X = DAG.getNode(ISD::SRL, SDLoc(X),
6205                         X.getValueType(), X,
6206                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6207         AddToWorkList(X.getNode());
6208         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6209         AddToWorkList(X.getNode());
6210       }
6211
6212       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6213       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6214                       X, DAG.getConstant(SignBit, VT));
6215       AddToWorkList(X.getNode());
6216
6217       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6218                                 VT, N0.getOperand(0));
6219       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6220                         Cst, DAG.getConstant(~SignBit, VT));
6221       AddToWorkList(Cst.getNode());
6222
6223       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6224     }
6225   }
6226
6227   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6228   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6229     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6230     if (CombineLD.getNode())
6231       return CombineLD;
6232   }
6233
6234   return SDValue();
6235 }
6236
6237 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6238   EVT VT = N->getValueType(0);
6239   return CombineConsecutiveLoads(N, VT);
6240 }
6241
6242 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6243 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6244 /// destination element value type.
6245 SDValue DAGCombiner::
6246 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6247   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6248
6249   // If this is already the right type, we're done.
6250   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6251
6252   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6253   unsigned DstBitSize = DstEltVT.getSizeInBits();
6254
6255   // If this is a conversion of N elements of one type to N elements of another
6256   // type, convert each element.  This handles FP<->INT cases.
6257   if (SrcBitSize == DstBitSize) {
6258     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6259                               BV->getValueType(0).getVectorNumElements());
6260
6261     // Due to the FP element handling below calling this routine recursively,
6262     // we can end up with a scalar-to-vector node here.
6263     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6264       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6265                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6266                                      DstEltVT, BV->getOperand(0)));
6267
6268     SmallVector<SDValue, 8> Ops;
6269     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6270       SDValue Op = BV->getOperand(i);
6271       // If the vector element type is not legal, the BUILD_VECTOR operands
6272       // are promoted and implicitly truncated.  Make that explicit here.
6273       if (Op.getValueType() != SrcEltVT)
6274         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6275       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6276                                 DstEltVT, Op));
6277       AddToWorkList(Ops.back().getNode());
6278     }
6279     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6280   }
6281
6282   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6283   // handle annoying details of growing/shrinking FP values, we convert them to
6284   // int first.
6285   if (SrcEltVT.isFloatingPoint()) {
6286     // Convert the input float vector to a int vector where the elements are the
6287     // same sizes.
6288     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6289     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6290     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6291     SrcEltVT = IntVT;
6292   }
6293
6294   // Now we know the input is an integer vector.  If the output is a FP type,
6295   // convert to integer first, then to FP of the right size.
6296   if (DstEltVT.isFloatingPoint()) {
6297     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6298     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6299     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6300
6301     // Next, convert to FP elements of the same size.
6302     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6303   }
6304
6305   // Okay, we know the src/dst types are both integers of differing types.
6306   // Handling growing first.
6307   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6308   if (SrcBitSize < DstBitSize) {
6309     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6310
6311     SmallVector<SDValue, 8> Ops;
6312     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6313          i += NumInputsPerOutput) {
6314       bool isLE = TLI.isLittleEndian();
6315       APInt NewBits = APInt(DstBitSize, 0);
6316       bool EltIsUndef = true;
6317       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6318         // Shift the previously computed bits over.
6319         NewBits <<= SrcBitSize;
6320         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6321         if (Op.getOpcode() == ISD::UNDEF) continue;
6322         EltIsUndef = false;
6323
6324         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6325                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6326       }
6327
6328       if (EltIsUndef)
6329         Ops.push_back(DAG.getUNDEF(DstEltVT));
6330       else
6331         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6332     }
6333
6334     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6335     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6336   }
6337
6338   // Finally, this must be the case where we are shrinking elements: each input
6339   // turns into multiple outputs.
6340   bool isS2V = ISD::isScalarToVector(BV);
6341   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6342   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6343                             NumOutputsPerInput*BV->getNumOperands());
6344   SmallVector<SDValue, 8> Ops;
6345
6346   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6347     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6348       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6349         Ops.push_back(DAG.getUNDEF(DstEltVT));
6350       continue;
6351     }
6352
6353     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6354                   getAPIntValue().zextOrTrunc(SrcBitSize);
6355
6356     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6357       APInt ThisVal = OpVal.trunc(DstBitSize);
6358       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6359       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6360         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6361         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6362                            Ops[0]);
6363       OpVal = OpVal.lshr(DstBitSize);
6364     }
6365
6366     // For big endian targets, swap the order of the pieces of each element.
6367     if (TLI.isBigEndian())
6368       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6369   }
6370
6371   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6372 }
6373
6374 SDValue DAGCombiner::visitFADD(SDNode *N) {
6375   SDValue N0 = N->getOperand(0);
6376   SDValue N1 = N->getOperand(1);
6377   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6378   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6379   EVT VT = N->getValueType(0);
6380
6381   // fold vector ops
6382   if (VT.isVector()) {
6383     SDValue FoldedVOp = SimplifyVBinOp(N);
6384     if (FoldedVOp.getNode()) return FoldedVOp;
6385   }
6386
6387   // fold (fadd c1, c2) -> c1 + c2
6388   if (N0CFP && N1CFP)
6389     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6390   // canonicalize constant to RHS
6391   if (N0CFP && !N1CFP)
6392     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6393   // fold (fadd A, 0) -> A
6394   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6395       N1CFP->getValueAPF().isZero())
6396     return N0;
6397   // fold (fadd A, (fneg B)) -> (fsub A, B)
6398   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6399     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6400     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6401                        GetNegatedExpression(N1, DAG, LegalOperations));
6402   // fold (fadd (fneg A), B) -> (fsub B, A)
6403   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6404     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6405     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6406                        GetNegatedExpression(N0, DAG, LegalOperations));
6407
6408   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6409   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6410       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6411       isa<ConstantFPSDNode>(N0.getOperand(1)))
6412     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6413                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6414                                    N0.getOperand(1), N1));
6415
6416   // No FP constant should be created after legalization as Instruction
6417   // Selection pass has hard time in dealing with FP constant.
6418   //
6419   // We don't need test this condition for transformation like following, as
6420   // the DAG being transformed implies it is legal to take FP constant as
6421   // operand.
6422   //
6423   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6424   //
6425   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6426
6427   // If allow, fold (fadd (fneg x), x) -> 0.0
6428   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6429       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6430     return DAG.getConstantFP(0.0, VT);
6431
6432     // If allow, fold (fadd x, (fneg x)) -> 0.0
6433   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6434       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6435     return DAG.getConstantFP(0.0, VT);
6436
6437   // In unsafe math mode, we can fold chains of FADD's of the same value
6438   // into multiplications.  This transform is not safe in general because
6439   // we are reducing the number of rounding steps.
6440   if (DAG.getTarget().Options.UnsafeFPMath &&
6441       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6442       !N0CFP && !N1CFP) {
6443     if (N0.getOpcode() == ISD::FMUL) {
6444       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6445       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6446
6447       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6448       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6449         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6450                                      SDValue(CFP00, 0),
6451                                      DAG.getConstantFP(1.0, VT));
6452         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6453                            N1, NewCFP);
6454       }
6455
6456       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6457       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6458         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6459                                      SDValue(CFP01, 0),
6460                                      DAG.getConstantFP(1.0, VT));
6461         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6462                            N1, NewCFP);
6463       }
6464
6465       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6466       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6467           N1.getOperand(0) == N1.getOperand(1) &&
6468           N0.getOperand(1) == N1.getOperand(0)) {
6469         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6470                                      SDValue(CFP00, 0),
6471                                      DAG.getConstantFP(2.0, VT));
6472         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6473                            N0.getOperand(1), NewCFP);
6474       }
6475
6476       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6477       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6478           N1.getOperand(0) == N1.getOperand(1) &&
6479           N0.getOperand(0) == N1.getOperand(0)) {
6480         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6481                                      SDValue(CFP01, 0),
6482                                      DAG.getConstantFP(2.0, VT));
6483         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6484                            N0.getOperand(0), NewCFP);
6485       }
6486     }
6487
6488     if (N1.getOpcode() == ISD::FMUL) {
6489       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6490       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6491
6492       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6493       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6494         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6495                                      SDValue(CFP10, 0),
6496                                      DAG.getConstantFP(1.0, VT));
6497         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6498                            N0, NewCFP);
6499       }
6500
6501       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6502       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6503         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6504                                      SDValue(CFP11, 0),
6505                                      DAG.getConstantFP(1.0, VT));
6506         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6507                            N0, NewCFP);
6508       }
6509
6510
6511       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6512       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6513           N0.getOperand(0) == N0.getOperand(1) &&
6514           N1.getOperand(1) == N0.getOperand(0)) {
6515         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6516                                      SDValue(CFP10, 0),
6517                                      DAG.getConstantFP(2.0, VT));
6518         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6519                            N1.getOperand(1), NewCFP);
6520       }
6521
6522       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6523       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6524           N0.getOperand(0) == N0.getOperand(1) &&
6525           N1.getOperand(0) == N0.getOperand(0)) {
6526         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6527                                      SDValue(CFP11, 0),
6528                                      DAG.getConstantFP(2.0, VT));
6529         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6530                            N1.getOperand(0), NewCFP);
6531       }
6532     }
6533
6534     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6535       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6536       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6537       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6538           (N0.getOperand(0) == N1))
6539         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6540                            N1, DAG.getConstantFP(3.0, VT));
6541     }
6542
6543     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6544       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6545       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6546       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6547           N1.getOperand(0) == N0)
6548         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6549                            N0, DAG.getConstantFP(3.0, VT));
6550     }
6551
6552     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6553     if (AllowNewFpConst &&
6554         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6555         N0.getOperand(0) == N0.getOperand(1) &&
6556         N1.getOperand(0) == N1.getOperand(1) &&
6557         N0.getOperand(0) == N1.getOperand(0))
6558       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6559                          N0.getOperand(0),
6560                          DAG.getConstantFP(4.0, VT));
6561   }
6562
6563   // FADD -> FMA combines:
6564   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6565        DAG.getTarget().Options.UnsafeFPMath) &&
6566       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6567       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6568
6569     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6570     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6571       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6572                          N0.getOperand(0), N0.getOperand(1), N1);
6573
6574     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6575     // Note: Commutes FADD operands.
6576     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6577       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6578                          N1.getOperand(0), N1.getOperand(1), N0);
6579   }
6580
6581   return SDValue();
6582 }
6583
6584 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6585   SDValue N0 = N->getOperand(0);
6586   SDValue N1 = N->getOperand(1);
6587   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6588   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6589   EVT VT = N->getValueType(0);
6590   SDLoc dl(N);
6591
6592   // fold vector ops
6593   if (VT.isVector()) {
6594     SDValue FoldedVOp = SimplifyVBinOp(N);
6595     if (FoldedVOp.getNode()) return FoldedVOp;
6596   }
6597
6598   // fold (fsub c1, c2) -> c1-c2
6599   if (N0CFP && N1CFP)
6600     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6601   // fold (fsub A, 0) -> A
6602   if (DAG.getTarget().Options.UnsafeFPMath &&
6603       N1CFP && N1CFP->getValueAPF().isZero())
6604     return N0;
6605   // fold (fsub 0, B) -> -B
6606   if (DAG.getTarget().Options.UnsafeFPMath &&
6607       N0CFP && N0CFP->getValueAPF().isZero()) {
6608     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6609       return GetNegatedExpression(N1, DAG, LegalOperations);
6610     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6611       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6612   }
6613   // fold (fsub A, (fneg B)) -> (fadd A, B)
6614   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6615     return DAG.getNode(ISD::FADD, dl, VT, N0,
6616                        GetNegatedExpression(N1, DAG, LegalOperations));
6617
6618   // If 'unsafe math' is enabled, fold
6619   //    (fsub x, x) -> 0.0 &
6620   //    (fsub x, (fadd x, y)) -> (fneg y) &
6621   //    (fsub x, (fadd y, x)) -> (fneg y)
6622   if (DAG.getTarget().Options.UnsafeFPMath) {
6623     if (N0 == N1)
6624       return DAG.getConstantFP(0.0f, VT);
6625
6626     if (N1.getOpcode() == ISD::FADD) {
6627       SDValue N10 = N1->getOperand(0);
6628       SDValue N11 = N1->getOperand(1);
6629
6630       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6631                                           &DAG.getTarget().Options))
6632         return GetNegatedExpression(N11, DAG, LegalOperations);
6633
6634       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6635                                           &DAG.getTarget().Options))
6636         return GetNegatedExpression(N10, DAG, LegalOperations);
6637     }
6638   }
6639
6640   // FSUB -> FMA combines:
6641   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6642        DAG.getTarget().Options.UnsafeFPMath) &&
6643       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6644       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6645
6646     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6647     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6648       return DAG.getNode(ISD::FMA, dl, VT,
6649                          N0.getOperand(0), N0.getOperand(1),
6650                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6651
6652     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6653     // Note: Commutes FSUB operands.
6654     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6655       return DAG.getNode(ISD::FMA, dl, VT,
6656                          DAG.getNode(ISD::FNEG, dl, VT,
6657                          N1.getOperand(0)),
6658                          N1.getOperand(1), N0);
6659
6660     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6661     if (N0.getOpcode() == ISD::FNEG &&
6662         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6663         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6664       SDValue N00 = N0.getOperand(0).getOperand(0);
6665       SDValue N01 = N0.getOperand(0).getOperand(1);
6666       return DAG.getNode(ISD::FMA, dl, VT,
6667                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6668                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6669     }
6670   }
6671
6672   return SDValue();
6673 }
6674
6675 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6676   SDValue N0 = N->getOperand(0);
6677   SDValue N1 = N->getOperand(1);
6678   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6679   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6680   EVT VT = N->getValueType(0);
6681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6682
6683   // fold vector ops
6684   if (VT.isVector()) {
6685     SDValue FoldedVOp = SimplifyVBinOp(N);
6686     if (FoldedVOp.getNode()) return FoldedVOp;
6687   }
6688
6689   // fold (fmul c1, c2) -> c1*c2
6690   if (N0CFP && N1CFP)
6691     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6692   // canonicalize constant to RHS
6693   if (N0CFP && !N1CFP)
6694     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6695   // fold (fmul A, 0) -> 0
6696   if (DAG.getTarget().Options.UnsafeFPMath &&
6697       N1CFP && N1CFP->getValueAPF().isZero())
6698     return N1;
6699   // fold (fmul A, 0) -> 0, vector edition.
6700   if (DAG.getTarget().Options.UnsafeFPMath &&
6701       ISD::isBuildVectorAllZeros(N1.getNode()))
6702     return N1;
6703   // fold (fmul A, 1.0) -> A
6704   if (N1CFP && N1CFP->isExactlyValue(1.0))
6705     return N0;
6706   // fold (fmul X, 2.0) -> (fadd X, X)
6707   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6708     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6709   // fold (fmul X, -1.0) -> (fneg X)
6710   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6711     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6712       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6713
6714   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6715   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6716                                        &DAG.getTarget().Options)) {
6717     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6718                                          &DAG.getTarget().Options)) {
6719       // Both can be negated for free, check to see if at least one is cheaper
6720       // negated.
6721       if (LHSNeg == 2 || RHSNeg == 2)
6722         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6723                            GetNegatedExpression(N0, DAG, LegalOperations),
6724                            GetNegatedExpression(N1, DAG, LegalOperations));
6725     }
6726   }
6727
6728   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6729   if (DAG.getTarget().Options.UnsafeFPMath &&
6730       N1CFP && N0.getOpcode() == ISD::FMUL &&
6731       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6732     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6733                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6734                                    N0.getOperand(1), N1));
6735
6736   return SDValue();
6737 }
6738
6739 SDValue DAGCombiner::visitFMA(SDNode *N) {
6740   SDValue N0 = N->getOperand(0);
6741   SDValue N1 = N->getOperand(1);
6742   SDValue N2 = N->getOperand(2);
6743   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6744   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6745   EVT VT = N->getValueType(0);
6746   SDLoc dl(N);
6747
6748   if (DAG.getTarget().Options.UnsafeFPMath) {
6749     if (N0CFP && N0CFP->isZero())
6750       return N2;
6751     if (N1CFP && N1CFP->isZero())
6752       return N2;
6753   }
6754   if (N0CFP && N0CFP->isExactlyValue(1.0))
6755     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6756   if (N1CFP && N1CFP->isExactlyValue(1.0))
6757     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6758
6759   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6760   if (N0CFP && !N1CFP)
6761     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6762
6763   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6764   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6765       N2.getOpcode() == ISD::FMUL &&
6766       N0 == N2.getOperand(0) &&
6767       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6768     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6769                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6770   }
6771
6772
6773   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6774   if (DAG.getTarget().Options.UnsafeFPMath &&
6775       N0.getOpcode() == ISD::FMUL && N1CFP &&
6776       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6777     return DAG.getNode(ISD::FMA, dl, VT,
6778                        N0.getOperand(0),
6779                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6780                        N2);
6781   }
6782
6783   // (fma x, 1, y) -> (fadd x, y)
6784   // (fma x, -1, y) -> (fadd (fneg x), y)
6785   if (N1CFP) {
6786     if (N1CFP->isExactlyValue(1.0))
6787       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6788
6789     if (N1CFP->isExactlyValue(-1.0) &&
6790         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6791       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6792       AddToWorkList(RHSNeg.getNode());
6793       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6794     }
6795   }
6796
6797   // (fma x, c, x) -> (fmul x, (c+1))
6798   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6799     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6800                        DAG.getNode(ISD::FADD, dl, VT,
6801                                    N1, DAG.getConstantFP(1.0, VT)));
6802
6803   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6804   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6805       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6806     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6807                        DAG.getNode(ISD::FADD, dl, VT,
6808                                    N1, DAG.getConstantFP(-1.0, VT)));
6809
6810
6811   return SDValue();
6812 }
6813
6814 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6815   SDValue N0 = N->getOperand(0);
6816   SDValue N1 = N->getOperand(1);
6817   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6818   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6819   EVT VT = N->getValueType(0);
6820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6821
6822   // fold vector ops
6823   if (VT.isVector()) {
6824     SDValue FoldedVOp = SimplifyVBinOp(N);
6825     if (FoldedVOp.getNode()) return FoldedVOp;
6826   }
6827
6828   // fold (fdiv c1, c2) -> c1/c2
6829   if (N0CFP && N1CFP)
6830     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6831
6832   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6833   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6834     // Compute the reciprocal 1.0 / c2.
6835     APFloat N1APF = N1CFP->getValueAPF();
6836     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6837     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6838     // Only do the transform if the reciprocal is a legal fp immediate that
6839     // isn't too nasty (eg NaN, denormal, ...).
6840     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6841         (!LegalOperations ||
6842          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6843          // backend)... we should handle this gracefully after Legalize.
6844          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6845          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6846          TLI.isFPImmLegal(Recip, VT)))
6847       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6848                          DAG.getConstantFP(Recip, VT));
6849   }
6850
6851   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6852   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6853                                        &DAG.getTarget().Options)) {
6854     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6855                                          &DAG.getTarget().Options)) {
6856       // Both can be negated for free, check to see if at least one is cheaper
6857       // negated.
6858       if (LHSNeg == 2 || RHSNeg == 2)
6859         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6860                            GetNegatedExpression(N0, DAG, LegalOperations),
6861                            GetNegatedExpression(N1, DAG, LegalOperations));
6862     }
6863   }
6864
6865   return SDValue();
6866 }
6867
6868 SDValue DAGCombiner::visitFREM(SDNode *N) {
6869   SDValue N0 = N->getOperand(0);
6870   SDValue N1 = N->getOperand(1);
6871   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6872   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6873   EVT VT = N->getValueType(0);
6874
6875   // fold (frem c1, c2) -> fmod(c1,c2)
6876   if (N0CFP && N1CFP)
6877     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6878
6879   return SDValue();
6880 }
6881
6882 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6883   SDValue N0 = N->getOperand(0);
6884   SDValue N1 = N->getOperand(1);
6885   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6886   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6887   EVT VT = N->getValueType(0);
6888
6889   if (N0CFP && N1CFP)  // Constant fold
6890     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6891
6892   if (N1CFP) {
6893     const APFloat& V = N1CFP->getValueAPF();
6894     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6895     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6896     if (!V.isNegative()) {
6897       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6898         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6899     } else {
6900       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6901         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6902                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6903     }
6904   }
6905
6906   // copysign(fabs(x), y) -> copysign(x, y)
6907   // copysign(fneg(x), y) -> copysign(x, y)
6908   // copysign(copysign(x,z), y) -> copysign(x, y)
6909   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6910       N0.getOpcode() == ISD::FCOPYSIGN)
6911     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6912                        N0.getOperand(0), N1);
6913
6914   // copysign(x, abs(y)) -> abs(x)
6915   if (N1.getOpcode() == ISD::FABS)
6916     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6917
6918   // copysign(x, copysign(y,z)) -> copysign(x, z)
6919   if (N1.getOpcode() == ISD::FCOPYSIGN)
6920     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6921                        N0, N1.getOperand(1));
6922
6923   // copysign(x, fp_extend(y)) -> copysign(x, y)
6924   // copysign(x, fp_round(y)) -> copysign(x, y)
6925   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6926     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6927                        N0, N1.getOperand(0));
6928
6929   return SDValue();
6930 }
6931
6932 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6933   SDValue N0 = N->getOperand(0);
6934   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6935   EVT VT = N->getValueType(0);
6936   EVT OpVT = N0.getValueType();
6937
6938   // fold (sint_to_fp c1) -> c1fp
6939   if (N0C &&
6940       // ...but only if the target supports immediate floating-point values
6941       (!LegalOperations ||
6942        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6943     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6944
6945   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6946   // but UINT_TO_FP is legal on this target, try to convert.
6947   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6948       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6949     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6950     if (DAG.SignBitIsZero(N0))
6951       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6952   }
6953
6954   // The next optimizations are desirable only if SELECT_CC can be lowered.
6955   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6956   // having to say they don't support SELECT_CC on every type the DAG knows
6957   // about, since there is no way to mark an opcode illegal at all value types
6958   // (See also visitSELECT)
6959   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6960     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6961     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6962         !VT.isVector() &&
6963         (!LegalOperations ||
6964          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6965       SDValue Ops[] =
6966         { N0.getOperand(0), N0.getOperand(1),
6967           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6968           N0.getOperand(2) };
6969       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6970     }
6971
6972     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6973     //      (select_cc x, y, 1.0, 0.0,, cc)
6974     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6975         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6976         (!LegalOperations ||
6977          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6978       SDValue Ops[] =
6979         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6980           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6981           N0.getOperand(0).getOperand(2) };
6982       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6983     }
6984   }
6985
6986   return SDValue();
6987 }
6988
6989 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6990   SDValue N0 = N->getOperand(0);
6991   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6992   EVT VT = N->getValueType(0);
6993   EVT OpVT = N0.getValueType();
6994
6995   // fold (uint_to_fp c1) -> c1fp
6996   if (N0C &&
6997       // ...but only if the target supports immediate floating-point values
6998       (!LegalOperations ||
6999        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7000     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7001
7002   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7003   // but SINT_TO_FP is legal on this target, try to convert.
7004   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7005       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7006     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7007     if (DAG.SignBitIsZero(N0))
7008       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7009   }
7010
7011   // The next optimizations are desirable only if SELECT_CC can be lowered.
7012   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7013   // having to say they don't support SELECT_CC on every type the DAG knows
7014   // about, since there is no way to mark an opcode illegal at all value types
7015   // (See also visitSELECT)
7016   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7017     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7018
7019     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7020         (!LegalOperations ||
7021          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7022       SDValue Ops[] =
7023         { N0.getOperand(0), N0.getOperand(1),
7024           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7025           N0.getOperand(2) };
7026       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7027     }
7028   }
7029
7030   return SDValue();
7031 }
7032
7033 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7034   SDValue N0 = N->getOperand(0);
7035   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7036   EVT VT = N->getValueType(0);
7037
7038   // fold (fp_to_sint c1fp) -> c1
7039   if (N0CFP)
7040     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7041
7042   return SDValue();
7043 }
7044
7045 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7046   SDValue N0 = N->getOperand(0);
7047   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7048   EVT VT = N->getValueType(0);
7049
7050   // fold (fp_to_uint c1fp) -> c1
7051   if (N0CFP)
7052     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7053
7054   return SDValue();
7055 }
7056
7057 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7058   SDValue N0 = N->getOperand(0);
7059   SDValue N1 = N->getOperand(1);
7060   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7061   EVT VT = N->getValueType(0);
7062
7063   // fold (fp_round c1fp) -> c1fp
7064   if (N0CFP)
7065     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7066
7067   // fold (fp_round (fp_extend x)) -> x
7068   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7069     return N0.getOperand(0);
7070
7071   // fold (fp_round (fp_round x)) -> (fp_round x)
7072   if (N0.getOpcode() == ISD::FP_ROUND) {
7073     // This is a value preserving truncation if both round's are.
7074     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7075                    N0.getNode()->getConstantOperandVal(1) == 1;
7076     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7077                        DAG.getIntPtrConstant(IsTrunc));
7078   }
7079
7080   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7081   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7082     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7083                               N0.getOperand(0), N1);
7084     AddToWorkList(Tmp.getNode());
7085     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7086                        Tmp, N0.getOperand(1));
7087   }
7088
7089   return SDValue();
7090 }
7091
7092 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7093   SDValue N0 = N->getOperand(0);
7094   EVT VT = N->getValueType(0);
7095   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7096   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7097
7098   // fold (fp_round_inreg c1fp) -> c1fp
7099   if (N0CFP && isTypeLegal(EVT)) {
7100     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7101     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7102   }
7103
7104   return SDValue();
7105 }
7106
7107 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7108   SDValue N0 = N->getOperand(0);
7109   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7110   EVT VT = N->getValueType(0);
7111
7112   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7113   if (N->hasOneUse() &&
7114       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7115     return SDValue();
7116
7117   // fold (fp_extend c1fp) -> c1fp
7118   if (N0CFP)
7119     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7120
7121   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7122   // value of X.
7123   if (N0.getOpcode() == ISD::FP_ROUND
7124       && N0.getNode()->getConstantOperandVal(1) == 1) {
7125     SDValue In = N0.getOperand(0);
7126     if (In.getValueType() == VT) return In;
7127     if (VT.bitsLT(In.getValueType()))
7128       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7129                          In, N0.getOperand(1));
7130     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7131   }
7132
7133   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7134   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7135       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7136        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7137     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7138     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7139                                      LN0->getChain(),
7140                                      LN0->getBasePtr(), N0.getValueType(),
7141                                      LN0->getMemOperand());
7142     CombineTo(N, ExtLoad);
7143     CombineTo(N0.getNode(),
7144               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7145                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7146               ExtLoad.getValue(1));
7147     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7148   }
7149
7150   return SDValue();
7151 }
7152
7153 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7154   SDValue N0 = N->getOperand(0);
7155   EVT VT = N->getValueType(0);
7156
7157   if (VT.isVector()) {
7158     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7159     if (FoldedVOp.getNode()) return FoldedVOp;
7160   }
7161
7162   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7163                          &DAG.getTarget().Options))
7164     return GetNegatedExpression(N0, DAG, LegalOperations);
7165
7166   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7167   // constant pool values.
7168   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7169       !VT.isVector() &&
7170       N0.getNode()->hasOneUse() &&
7171       N0.getOperand(0).getValueType().isInteger()) {
7172     SDValue Int = N0.getOperand(0);
7173     EVT IntVT = Int.getValueType();
7174     if (IntVT.isInteger() && !IntVT.isVector()) {
7175       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7176               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7177       AddToWorkList(Int.getNode());
7178       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7179                          VT, Int);
7180     }
7181   }
7182
7183   // (fneg (fmul c, x)) -> (fmul -c, x)
7184   if (N0.getOpcode() == ISD::FMUL) {
7185     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7186     if (CFP1)
7187       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7188                          N0.getOperand(0),
7189                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7190                                      N0.getOperand(1)));
7191   }
7192
7193   return SDValue();
7194 }
7195
7196 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7197   SDValue N0 = N->getOperand(0);
7198   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7199   EVT VT = N->getValueType(0);
7200
7201   // fold (fceil c1) -> fceil(c1)
7202   if (N0CFP)
7203     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7204
7205   return SDValue();
7206 }
7207
7208 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7209   SDValue N0 = N->getOperand(0);
7210   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7211   EVT VT = N->getValueType(0);
7212
7213   // fold (ftrunc c1) -> ftrunc(c1)
7214   if (N0CFP)
7215     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7216
7217   return SDValue();
7218 }
7219
7220 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7221   SDValue N0 = N->getOperand(0);
7222   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7223   EVT VT = N->getValueType(0);
7224
7225   // fold (ffloor c1) -> ffloor(c1)
7226   if (N0CFP)
7227     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7228
7229   return SDValue();
7230 }
7231
7232 SDValue DAGCombiner::visitFABS(SDNode *N) {
7233   SDValue N0 = N->getOperand(0);
7234   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7235   EVT VT = N->getValueType(0);
7236
7237   if (VT.isVector()) {
7238     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7239     if (FoldedVOp.getNode()) return FoldedVOp;
7240   }
7241
7242   // fold (fabs c1) -> fabs(c1)
7243   if (N0CFP)
7244     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7245   // fold (fabs (fabs x)) -> (fabs x)
7246   if (N0.getOpcode() == ISD::FABS)
7247     return N->getOperand(0);
7248   // fold (fabs (fneg x)) -> (fabs x)
7249   // fold (fabs (fcopysign x, y)) -> (fabs x)
7250   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7251     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7252
7253   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7254   // constant pool values.
7255   if (!TLI.isFAbsFree(VT) &&
7256       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7257       N0.getOperand(0).getValueType().isInteger() &&
7258       !N0.getOperand(0).getValueType().isVector()) {
7259     SDValue Int = N0.getOperand(0);
7260     EVT IntVT = Int.getValueType();
7261     if (IntVT.isInteger() && !IntVT.isVector()) {
7262       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7263              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7264       AddToWorkList(Int.getNode());
7265       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7266                          N->getValueType(0), Int);
7267     }
7268   }
7269
7270   return SDValue();
7271 }
7272
7273 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7274   SDValue Chain = N->getOperand(0);
7275   SDValue N1 = N->getOperand(1);
7276   SDValue N2 = N->getOperand(2);
7277
7278   // If N is a constant we could fold this into a fallthrough or unconditional
7279   // branch. However that doesn't happen very often in normal code, because
7280   // Instcombine/SimplifyCFG should have handled the available opportunities.
7281   // If we did this folding here, it would be necessary to update the
7282   // MachineBasicBlock CFG, which is awkward.
7283
7284   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7285   // on the target.
7286   if (N1.getOpcode() == ISD::SETCC &&
7287       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7288                                    N1.getOperand(0).getValueType())) {
7289     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7290                        Chain, N1.getOperand(2),
7291                        N1.getOperand(0), N1.getOperand(1), N2);
7292   }
7293
7294   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7295       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7296        (N1.getOperand(0).hasOneUse() &&
7297         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7298     SDNode *Trunc = nullptr;
7299     if (N1.getOpcode() == ISD::TRUNCATE) {
7300       // Look pass the truncate.
7301       Trunc = N1.getNode();
7302       N1 = N1.getOperand(0);
7303     }
7304
7305     // Match this pattern so that we can generate simpler code:
7306     //
7307     //   %a = ...
7308     //   %b = and i32 %a, 2
7309     //   %c = srl i32 %b, 1
7310     //   brcond i32 %c ...
7311     //
7312     // into
7313     //
7314     //   %a = ...
7315     //   %b = and i32 %a, 2
7316     //   %c = setcc eq %b, 0
7317     //   brcond %c ...
7318     //
7319     // This applies only when the AND constant value has one bit set and the
7320     // SRL constant is equal to the log2 of the AND constant. The back-end is
7321     // smart enough to convert the result into a TEST/JMP sequence.
7322     SDValue Op0 = N1.getOperand(0);
7323     SDValue Op1 = N1.getOperand(1);
7324
7325     if (Op0.getOpcode() == ISD::AND &&
7326         Op1.getOpcode() == ISD::Constant) {
7327       SDValue AndOp1 = Op0.getOperand(1);
7328
7329       if (AndOp1.getOpcode() == ISD::Constant) {
7330         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7331
7332         if (AndConst.isPowerOf2() &&
7333             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7334           SDValue SetCC =
7335             DAG.getSetCC(SDLoc(N),
7336                          getSetCCResultType(Op0.getValueType()),
7337                          Op0, DAG.getConstant(0, Op0.getValueType()),
7338                          ISD::SETNE);
7339
7340           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7341                                           MVT::Other, Chain, SetCC, N2);
7342           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7343           // will convert it back to (X & C1) >> C2.
7344           CombineTo(N, NewBRCond, false);
7345           // Truncate is dead.
7346           if (Trunc) {
7347             removeFromWorkList(Trunc);
7348             DAG.DeleteNode(Trunc);
7349           }
7350           // Replace the uses of SRL with SETCC
7351           WorkListRemover DeadNodes(*this);
7352           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7353           removeFromWorkList(N1.getNode());
7354           DAG.DeleteNode(N1.getNode());
7355           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7356         }
7357       }
7358     }
7359
7360     if (Trunc)
7361       // Restore N1 if the above transformation doesn't match.
7362       N1 = N->getOperand(1);
7363   }
7364
7365   // Transform br(xor(x, y)) -> br(x != y)
7366   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7367   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7368     SDNode *TheXor = N1.getNode();
7369     SDValue Op0 = TheXor->getOperand(0);
7370     SDValue Op1 = TheXor->getOperand(1);
7371     if (Op0.getOpcode() == Op1.getOpcode()) {
7372       // Avoid missing important xor optimizations.
7373       SDValue Tmp = visitXOR(TheXor);
7374       if (Tmp.getNode()) {
7375         if (Tmp.getNode() != TheXor) {
7376           DEBUG(dbgs() << "\nReplacing.8 ";
7377                 TheXor->dump(&DAG);
7378                 dbgs() << "\nWith: ";
7379                 Tmp.getNode()->dump(&DAG);
7380                 dbgs() << '\n');
7381           WorkListRemover DeadNodes(*this);
7382           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7383           removeFromWorkList(TheXor);
7384           DAG.DeleteNode(TheXor);
7385           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7386                              MVT::Other, Chain, Tmp, N2);
7387         }
7388
7389         // visitXOR has changed XOR's operands or replaced the XOR completely,
7390         // bail out.
7391         return SDValue(N, 0);
7392       }
7393     }
7394
7395     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7396       bool Equal = false;
7397       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7398         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7399             Op0.getOpcode() == ISD::XOR) {
7400           TheXor = Op0.getNode();
7401           Equal = true;
7402         }
7403
7404       EVT SetCCVT = N1.getValueType();
7405       if (LegalTypes)
7406         SetCCVT = getSetCCResultType(SetCCVT);
7407       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7408                                    SetCCVT,
7409                                    Op0, Op1,
7410                                    Equal ? ISD::SETEQ : ISD::SETNE);
7411       // Replace the uses of XOR with SETCC
7412       WorkListRemover DeadNodes(*this);
7413       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7414       removeFromWorkList(N1.getNode());
7415       DAG.DeleteNode(N1.getNode());
7416       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7417                          MVT::Other, Chain, SetCC, N2);
7418     }
7419   }
7420
7421   return SDValue();
7422 }
7423
7424 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7425 //
7426 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7427   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7428   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7429
7430   // If N is a constant we could fold this into a fallthrough or unconditional
7431   // branch. However that doesn't happen very often in normal code, because
7432   // Instcombine/SimplifyCFG should have handled the available opportunities.
7433   // If we did this folding here, it would be necessary to update the
7434   // MachineBasicBlock CFG, which is awkward.
7435
7436   // Use SimplifySetCC to simplify SETCC's.
7437   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7438                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7439                                false);
7440   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7441
7442   // fold to a simpler setcc
7443   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7444     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7445                        N->getOperand(0), Simp.getOperand(2),
7446                        Simp.getOperand(0), Simp.getOperand(1),
7447                        N->getOperand(4));
7448
7449   return SDValue();
7450 }
7451
7452 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7453 /// uses N as its base pointer and that N may be folded in the load / store
7454 /// addressing mode.
7455 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7456                                     SelectionDAG &DAG,
7457                                     const TargetLowering &TLI) {
7458   EVT VT;
7459   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7460     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7461       return false;
7462     VT = Use->getValueType(0);
7463   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7464     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7465       return false;
7466     VT = ST->getValue().getValueType();
7467   } else
7468     return false;
7469
7470   TargetLowering::AddrMode AM;
7471   if (N->getOpcode() == ISD::ADD) {
7472     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7473     if (Offset)
7474       // [reg +/- imm]
7475       AM.BaseOffs = Offset->getSExtValue();
7476     else
7477       // [reg +/- reg]
7478       AM.Scale = 1;
7479   } else if (N->getOpcode() == ISD::SUB) {
7480     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7481     if (Offset)
7482       // [reg +/- imm]
7483       AM.BaseOffs = -Offset->getSExtValue();
7484     else
7485       // [reg +/- reg]
7486       AM.Scale = 1;
7487   } else
7488     return false;
7489
7490   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7491 }
7492
7493 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7494 /// pre-indexed load / store when the base pointer is an add or subtract
7495 /// and it has other uses besides the load / store. After the
7496 /// transformation, the new indexed load / store has effectively folded
7497 /// the add / subtract in and all of its other uses are redirected to the
7498 /// new load / store.
7499 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7500   if (Level < AfterLegalizeDAG)
7501     return false;
7502
7503   bool isLoad = true;
7504   SDValue Ptr;
7505   EVT VT;
7506   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7507     if (LD->isIndexed())
7508       return false;
7509     VT = LD->getMemoryVT();
7510     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7511         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7512       return false;
7513     Ptr = LD->getBasePtr();
7514   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7515     if (ST->isIndexed())
7516       return false;
7517     VT = ST->getMemoryVT();
7518     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7519         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7520       return false;
7521     Ptr = ST->getBasePtr();
7522     isLoad = false;
7523   } else {
7524     return false;
7525   }
7526
7527   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7528   // out.  There is no reason to make this a preinc/predec.
7529   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7530       Ptr.getNode()->hasOneUse())
7531     return false;
7532
7533   // Ask the target to do addressing mode selection.
7534   SDValue BasePtr;
7535   SDValue Offset;
7536   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7537   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7538     return false;
7539
7540   // Backends without true r+i pre-indexed forms may need to pass a
7541   // constant base with a variable offset so that constant coercion
7542   // will work with the patterns in canonical form.
7543   bool Swapped = false;
7544   if (isa<ConstantSDNode>(BasePtr)) {
7545     std::swap(BasePtr, Offset);
7546     Swapped = true;
7547   }
7548
7549   // Don't create a indexed load / store with zero offset.
7550   if (isa<ConstantSDNode>(Offset) &&
7551       cast<ConstantSDNode>(Offset)->isNullValue())
7552     return false;
7553
7554   // Try turning it into a pre-indexed load / store except when:
7555   // 1) The new base ptr is a frame index.
7556   // 2) If N is a store and the new base ptr is either the same as or is a
7557   //    predecessor of the value being stored.
7558   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7559   //    that would create a cycle.
7560   // 4) All uses are load / store ops that use it as old base ptr.
7561
7562   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7563   // (plus the implicit offset) to a register to preinc anyway.
7564   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7565     return false;
7566
7567   // Check #2.
7568   if (!isLoad) {
7569     SDValue Val = cast<StoreSDNode>(N)->getValue();
7570     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7571       return false;
7572   }
7573
7574   // If the offset is a constant, there may be other adds of constants that
7575   // can be folded with this one. We should do this to avoid having to keep
7576   // a copy of the original base pointer.
7577   SmallVector<SDNode *, 16> OtherUses;
7578   if (isa<ConstantSDNode>(Offset))
7579     for (SDNode *Use : BasePtr.getNode()->uses()) {
7580       if (Use == Ptr.getNode())
7581         continue;
7582
7583       if (Use->isPredecessorOf(N))
7584         continue;
7585
7586       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7587         OtherUses.clear();
7588         break;
7589       }
7590
7591       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7592       if (Op1.getNode() == BasePtr.getNode())
7593         std::swap(Op0, Op1);
7594       assert(Op0.getNode() == BasePtr.getNode() &&
7595              "Use of ADD/SUB but not an operand");
7596
7597       if (!isa<ConstantSDNode>(Op1)) {
7598         OtherUses.clear();
7599         break;
7600       }
7601
7602       // FIXME: In some cases, we can be smarter about this.
7603       if (Op1.getValueType() != Offset.getValueType()) {
7604         OtherUses.clear();
7605         break;
7606       }
7607
7608       OtherUses.push_back(Use);
7609     }
7610
7611   if (Swapped)
7612     std::swap(BasePtr, Offset);
7613
7614   // Now check for #3 and #4.
7615   bool RealUse = false;
7616
7617   // Caches for hasPredecessorHelper
7618   SmallPtrSet<const SDNode *, 32> Visited;
7619   SmallVector<const SDNode *, 16> Worklist;
7620
7621   for (SDNode *Use : Ptr.getNode()->uses()) {
7622     if (Use == N)
7623       continue;
7624     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7625       return false;
7626
7627     // If Ptr may be folded in addressing mode of other use, then it's
7628     // not profitable to do this transformation.
7629     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7630       RealUse = true;
7631   }
7632
7633   if (!RealUse)
7634     return false;
7635
7636   SDValue Result;
7637   if (isLoad)
7638     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7639                                 BasePtr, Offset, AM);
7640   else
7641     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7642                                  BasePtr, Offset, AM);
7643   ++PreIndexedNodes;
7644   ++NodesCombined;
7645   DEBUG(dbgs() << "\nReplacing.4 ";
7646         N->dump(&DAG);
7647         dbgs() << "\nWith: ";
7648         Result.getNode()->dump(&DAG);
7649         dbgs() << '\n');
7650   WorkListRemover DeadNodes(*this);
7651   if (isLoad) {
7652     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7653     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7654   } else {
7655     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7656   }
7657
7658   // Finally, since the node is now dead, remove it from the graph.
7659   DAG.DeleteNode(N);
7660
7661   if (Swapped)
7662     std::swap(BasePtr, Offset);
7663
7664   // Replace other uses of BasePtr that can be updated to use Ptr
7665   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7666     unsigned OffsetIdx = 1;
7667     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7668       OffsetIdx = 0;
7669     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7670            BasePtr.getNode() && "Expected BasePtr operand");
7671
7672     // We need to replace ptr0 in the following expression:
7673     //   x0 * offset0 + y0 * ptr0 = t0
7674     // knowing that
7675     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7676     //
7677     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7678     // indexed load/store and the expresion that needs to be re-written.
7679     //
7680     // Therefore, we have:
7681     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7682
7683     ConstantSDNode *CN =
7684       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7685     int X0, X1, Y0, Y1;
7686     APInt Offset0 = CN->getAPIntValue();
7687     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7688
7689     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7690     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7691     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7692     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7693
7694     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7695
7696     APInt CNV = Offset0;
7697     if (X0 < 0) CNV = -CNV;
7698     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7699     else CNV = CNV - Offset1;
7700
7701     // We can now generate the new expression.
7702     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7703     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7704
7705     SDValue NewUse = DAG.getNode(Opcode,
7706                                  SDLoc(OtherUses[i]),
7707                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7708     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7709     removeFromWorkList(OtherUses[i]);
7710     DAG.DeleteNode(OtherUses[i]);
7711   }
7712
7713   // Replace the uses of Ptr with uses of the updated base value.
7714   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7715   removeFromWorkList(Ptr.getNode());
7716   DAG.DeleteNode(Ptr.getNode());
7717
7718   return true;
7719 }
7720
7721 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7722 /// add / sub of the base pointer node into a post-indexed load / store.
7723 /// The transformation folded the add / subtract into the new indexed
7724 /// load / store effectively and all of its uses are redirected to the
7725 /// new load / store.
7726 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7727   if (Level < AfterLegalizeDAG)
7728     return false;
7729
7730   bool isLoad = true;
7731   SDValue Ptr;
7732   EVT VT;
7733   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7734     if (LD->isIndexed())
7735       return false;
7736     VT = LD->getMemoryVT();
7737     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7738         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7739       return false;
7740     Ptr = LD->getBasePtr();
7741   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7742     if (ST->isIndexed())
7743       return false;
7744     VT = ST->getMemoryVT();
7745     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7746         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7747       return false;
7748     Ptr = ST->getBasePtr();
7749     isLoad = false;
7750   } else {
7751     return false;
7752   }
7753
7754   if (Ptr.getNode()->hasOneUse())
7755     return false;
7756
7757   for (SDNode *Op : Ptr.getNode()->uses()) {
7758     if (Op == N ||
7759         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7760       continue;
7761
7762     SDValue BasePtr;
7763     SDValue Offset;
7764     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7765     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7766       // Don't create a indexed load / store with zero offset.
7767       if (isa<ConstantSDNode>(Offset) &&
7768           cast<ConstantSDNode>(Offset)->isNullValue())
7769         continue;
7770
7771       // Try turning it into a post-indexed load / store except when
7772       // 1) All uses are load / store ops that use it as base ptr (and
7773       //    it may be folded as addressing mmode).
7774       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7775       //    nor a successor of N. Otherwise, if Op is folded that would
7776       //    create a cycle.
7777
7778       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7779         continue;
7780
7781       // Check for #1.
7782       bool TryNext = false;
7783       for (SDNode *Use : BasePtr.getNode()->uses()) {
7784         if (Use == Ptr.getNode())
7785           continue;
7786
7787         // If all the uses are load / store addresses, then don't do the
7788         // transformation.
7789         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7790           bool RealUse = false;
7791           for (SDNode *UseUse : Use->uses()) {
7792             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7793               RealUse = true;
7794           }
7795
7796           if (!RealUse) {
7797             TryNext = true;
7798             break;
7799           }
7800         }
7801       }
7802
7803       if (TryNext)
7804         continue;
7805
7806       // Check for #2
7807       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7808         SDValue Result = isLoad
7809           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7810                                BasePtr, Offset, AM)
7811           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7812                                 BasePtr, Offset, AM);
7813         ++PostIndexedNodes;
7814         ++NodesCombined;
7815         DEBUG(dbgs() << "\nReplacing.5 ";
7816               N->dump(&DAG);
7817               dbgs() << "\nWith: ";
7818               Result.getNode()->dump(&DAG);
7819               dbgs() << '\n');
7820         WorkListRemover DeadNodes(*this);
7821         if (isLoad) {
7822           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7823           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7824         } else {
7825           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7826         }
7827
7828         // Finally, since the node is now dead, remove it from the graph.
7829         DAG.DeleteNode(N);
7830
7831         // Replace the uses of Use with uses of the updated base value.
7832         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7833                                       Result.getValue(isLoad ? 1 : 0));
7834         removeFromWorkList(Op);
7835         DAG.DeleteNode(Op);
7836         return true;
7837       }
7838     }
7839   }
7840
7841   return false;
7842 }
7843
7844 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7845   LoadSDNode *LD  = cast<LoadSDNode>(N);
7846   SDValue Chain = LD->getChain();
7847   SDValue Ptr   = LD->getBasePtr();
7848
7849   // If load is not volatile and there are no uses of the loaded value (and
7850   // the updated indexed value in case of indexed loads), change uses of the
7851   // chain value into uses of the chain input (i.e. delete the dead load).
7852   if (!LD->isVolatile()) {
7853     if (N->getValueType(1) == MVT::Other) {
7854       // Unindexed loads.
7855       if (!N->hasAnyUseOfValue(0)) {
7856         // It's not safe to use the two value CombineTo variant here. e.g.
7857         // v1, chain2 = load chain1, loc
7858         // v2, chain3 = load chain2, loc
7859         // v3         = add v2, c
7860         // Now we replace use of chain2 with chain1.  This makes the second load
7861         // isomorphic to the one we are deleting, and thus makes this load live.
7862         DEBUG(dbgs() << "\nReplacing.6 ";
7863               N->dump(&DAG);
7864               dbgs() << "\nWith chain: ";
7865               Chain.getNode()->dump(&DAG);
7866               dbgs() << "\n");
7867         WorkListRemover DeadNodes(*this);
7868         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7869
7870         if (N->use_empty()) {
7871           removeFromWorkList(N);
7872           DAG.DeleteNode(N);
7873         }
7874
7875         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7876       }
7877     } else {
7878       // Indexed loads.
7879       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7880       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7881         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7882         DEBUG(dbgs() << "\nReplacing.7 ";
7883               N->dump(&DAG);
7884               dbgs() << "\nWith: ";
7885               Undef.getNode()->dump(&DAG);
7886               dbgs() << " and 2 other values\n");
7887         WorkListRemover DeadNodes(*this);
7888         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7889         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7890                                       DAG.getUNDEF(N->getValueType(1)));
7891         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7892         removeFromWorkList(N);
7893         DAG.DeleteNode(N);
7894         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7895       }
7896     }
7897   }
7898
7899   // If this load is directly stored, replace the load value with the stored
7900   // value.
7901   // TODO: Handle store large -> read small portion.
7902   // TODO: Handle TRUNCSTORE/LOADEXT
7903   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7904     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7905       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7906       if (PrevST->getBasePtr() == Ptr &&
7907           PrevST->getValue().getValueType() == N->getValueType(0))
7908       return CombineTo(N, Chain.getOperand(1), Chain);
7909     }
7910   }
7911
7912   // Try to infer better alignment information than the load already has.
7913   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7914     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7915       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7916         SDValue NewLoad =
7917                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7918                               LD->getValueType(0),
7919                               Chain, Ptr, LD->getPointerInfo(),
7920                               LD->getMemoryVT(),
7921                               LD->isVolatile(), LD->isNonTemporal(), Align,
7922                               LD->getTBAAInfo());
7923         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7924       }
7925     }
7926   }
7927
7928   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7929     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7930 #ifndef NDEBUG
7931   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7932       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7933     UseAA = false;
7934 #endif
7935   if (UseAA && LD->isUnindexed()) {
7936     // Walk up chain skipping non-aliasing memory nodes.
7937     SDValue BetterChain = FindBetterChain(N, Chain);
7938
7939     // If there is a better chain.
7940     if (Chain != BetterChain) {
7941       SDValue ReplLoad;
7942
7943       // Replace the chain to void dependency.
7944       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7945         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7946                                BetterChain, Ptr, LD->getMemOperand());
7947       } else {
7948         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7949                                   LD->getValueType(0),
7950                                   BetterChain, Ptr, LD->getMemoryVT(),
7951                                   LD->getMemOperand());
7952       }
7953
7954       // Create token factor to keep old chain connected.
7955       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7956                                   MVT::Other, Chain, ReplLoad.getValue(1));
7957
7958       // Make sure the new and old chains are cleaned up.
7959       AddToWorkList(Token.getNode());
7960
7961       // Replace uses with load result and token factor. Don't add users
7962       // to work list.
7963       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7964     }
7965   }
7966
7967   // Try transforming N to an indexed load.
7968   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7969     return SDValue(N, 0);
7970
7971   // Try to slice up N to more direct loads if the slices are mapped to
7972   // different register banks or pairing can take place.
7973   if (SliceUpLoad(N))
7974     return SDValue(N, 0);
7975
7976   return SDValue();
7977 }
7978
7979 namespace {
7980 /// \brief Helper structure used to slice a load in smaller loads.
7981 /// Basically a slice is obtained from the following sequence:
7982 /// Origin = load Ty1, Base
7983 /// Shift = srl Ty1 Origin, CstTy Amount
7984 /// Inst = trunc Shift to Ty2
7985 ///
7986 /// Then, it will be rewriten into:
7987 /// Slice = load SliceTy, Base + SliceOffset
7988 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7989 ///
7990 /// SliceTy is deduced from the number of bits that are actually used to
7991 /// build Inst.
7992 struct LoadedSlice {
7993   /// \brief Helper structure used to compute the cost of a slice.
7994   struct Cost {
7995     /// Are we optimizing for code size.
7996     bool ForCodeSize;
7997     /// Various cost.
7998     unsigned Loads;
7999     unsigned Truncates;
8000     unsigned CrossRegisterBanksCopies;
8001     unsigned ZExts;
8002     unsigned Shift;
8003
8004     Cost(bool ForCodeSize = false)
8005         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8006           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8007
8008     /// \brief Get the cost of one isolated slice.
8009     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8010         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8011           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8012       EVT TruncType = LS.Inst->getValueType(0);
8013       EVT LoadedType = LS.getLoadedType();
8014       if (TruncType != LoadedType &&
8015           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8016         ZExts = 1;
8017     }
8018
8019     /// \brief Account for slicing gain in the current cost.
8020     /// Slicing provide a few gains like removing a shift or a
8021     /// truncate. This method allows to grow the cost of the original
8022     /// load with the gain from this slice.
8023     void addSliceGain(const LoadedSlice &LS) {
8024       // Each slice saves a truncate.
8025       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8026       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8027                               LS.Inst->getOperand(0).getValueType()))
8028         ++Truncates;
8029       // If there is a shift amount, this slice gets rid of it.
8030       if (LS.Shift)
8031         ++Shift;
8032       // If this slice can merge a cross register bank copy, account for it.
8033       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8034         ++CrossRegisterBanksCopies;
8035     }
8036
8037     Cost &operator+=(const Cost &RHS) {
8038       Loads += RHS.Loads;
8039       Truncates += RHS.Truncates;
8040       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8041       ZExts += RHS.ZExts;
8042       Shift += RHS.Shift;
8043       return *this;
8044     }
8045
8046     bool operator==(const Cost &RHS) const {
8047       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8048              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8049              ZExts == RHS.ZExts && Shift == RHS.Shift;
8050     }
8051
8052     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8053
8054     bool operator<(const Cost &RHS) const {
8055       // Assume cross register banks copies are as expensive as loads.
8056       // FIXME: Do we want some more target hooks?
8057       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8058       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8059       // Unless we are optimizing for code size, consider the
8060       // expensive operation first.
8061       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8062         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8063       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8064              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8065     }
8066
8067     bool operator>(const Cost &RHS) const { return RHS < *this; }
8068
8069     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8070
8071     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8072   };
8073   // The last instruction that represent the slice. This should be a
8074   // truncate instruction.
8075   SDNode *Inst;
8076   // The original load instruction.
8077   LoadSDNode *Origin;
8078   // The right shift amount in bits from the original load.
8079   unsigned Shift;
8080   // The DAG from which Origin came from.
8081   // This is used to get some contextual information about legal types, etc.
8082   SelectionDAG *DAG;
8083
8084   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8085               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8086       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8087
8088   LoadedSlice(const LoadedSlice &LS)
8089       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8090
8091   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8092   /// \return Result is \p BitWidth and has used bits set to 1 and
8093   ///         not used bits set to 0.
8094   APInt getUsedBits() const {
8095     // Reproduce the trunc(lshr) sequence:
8096     // - Start from the truncated value.
8097     // - Zero extend to the desired bit width.
8098     // - Shift left.
8099     assert(Origin && "No original load to compare against.");
8100     unsigned BitWidth = Origin->getValueSizeInBits(0);
8101     assert(Inst && "This slice is not bound to an instruction");
8102     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8103            "Extracted slice is bigger than the whole type!");
8104     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8105     UsedBits.setAllBits();
8106     UsedBits = UsedBits.zext(BitWidth);
8107     UsedBits <<= Shift;
8108     return UsedBits;
8109   }
8110
8111   /// \brief Get the size of the slice to be loaded in bytes.
8112   unsigned getLoadedSize() const {
8113     unsigned SliceSize = getUsedBits().countPopulation();
8114     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8115     return SliceSize / 8;
8116   }
8117
8118   /// \brief Get the type that will be loaded for this slice.
8119   /// Note: This may not be the final type for the slice.
8120   EVT getLoadedType() const {
8121     assert(DAG && "Missing context");
8122     LLVMContext &Ctxt = *DAG->getContext();
8123     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8124   }
8125
8126   /// \brief Get the alignment of the load used for this slice.
8127   unsigned getAlignment() const {
8128     unsigned Alignment = Origin->getAlignment();
8129     unsigned Offset = getOffsetFromBase();
8130     if (Offset != 0)
8131       Alignment = MinAlign(Alignment, Alignment + Offset);
8132     return Alignment;
8133   }
8134
8135   /// \brief Check if this slice can be rewritten with legal operations.
8136   bool isLegal() const {
8137     // An invalid slice is not legal.
8138     if (!Origin || !Inst || !DAG)
8139       return false;
8140
8141     // Offsets are for indexed load only, we do not handle that.
8142     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8143       return false;
8144
8145     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8146
8147     // Check that the type is legal.
8148     EVT SliceType = getLoadedType();
8149     if (!TLI.isTypeLegal(SliceType))
8150       return false;
8151
8152     // Check that the load is legal for this type.
8153     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8154       return false;
8155
8156     // Check that the offset can be computed.
8157     // 1. Check its type.
8158     EVT PtrType = Origin->getBasePtr().getValueType();
8159     if (PtrType == MVT::Untyped || PtrType.isExtended())
8160       return false;
8161
8162     // 2. Check that it fits in the immediate.
8163     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8164       return false;
8165
8166     // 3. Check that the computation is legal.
8167     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8168       return false;
8169
8170     // Check that the zext is legal if it needs one.
8171     EVT TruncateType = Inst->getValueType(0);
8172     if (TruncateType != SliceType &&
8173         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8174       return false;
8175
8176     return true;
8177   }
8178
8179   /// \brief Get the offset in bytes of this slice in the original chunk of
8180   /// bits.
8181   /// \pre DAG != nullptr.
8182   uint64_t getOffsetFromBase() const {
8183     assert(DAG && "Missing context.");
8184     bool IsBigEndian =
8185         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8186     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8187     uint64_t Offset = Shift / 8;
8188     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8189     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8190            "The size of the original loaded type is not a multiple of a"
8191            " byte.");
8192     // If Offset is bigger than TySizeInBytes, it means we are loading all
8193     // zeros. This should have been optimized before in the process.
8194     assert(TySizeInBytes > Offset &&
8195            "Invalid shift amount for given loaded size");
8196     if (IsBigEndian)
8197       Offset = TySizeInBytes - Offset - getLoadedSize();
8198     return Offset;
8199   }
8200
8201   /// \brief Generate the sequence of instructions to load the slice
8202   /// represented by this object and redirect the uses of this slice to
8203   /// this new sequence of instructions.
8204   /// \pre this->Inst && this->Origin are valid Instructions and this
8205   /// object passed the legal check: LoadedSlice::isLegal returned true.
8206   /// \return The last instruction of the sequence used to load the slice.
8207   SDValue loadSlice() const {
8208     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8209     const SDValue &OldBaseAddr = Origin->getBasePtr();
8210     SDValue BaseAddr = OldBaseAddr;
8211     // Get the offset in that chunk of bytes w.r.t. the endianess.
8212     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8213     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8214     if (Offset) {
8215       // BaseAddr = BaseAddr + Offset.
8216       EVT ArithType = BaseAddr.getValueType();
8217       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8218                               DAG->getConstant(Offset, ArithType));
8219     }
8220
8221     // Create the type of the loaded slice according to its size.
8222     EVT SliceType = getLoadedType();
8223
8224     // Create the load for the slice.
8225     SDValue LastInst = DAG->getLoad(
8226         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8227         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8228         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8229     // If the final type is not the same as the loaded type, this means that
8230     // we have to pad with zero. Create a zero extend for that.
8231     EVT FinalType = Inst->getValueType(0);
8232     if (SliceType != FinalType)
8233       LastInst =
8234           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8235     return LastInst;
8236   }
8237
8238   /// \brief Check if this slice can be merged with an expensive cross register
8239   /// bank copy. E.g.,
8240   /// i = load i32
8241   /// f = bitcast i32 i to float
8242   bool canMergeExpensiveCrossRegisterBankCopy() const {
8243     if (!Inst || !Inst->hasOneUse())
8244       return false;
8245     SDNode *Use = *Inst->use_begin();
8246     if (Use->getOpcode() != ISD::BITCAST)
8247       return false;
8248     assert(DAG && "Missing context");
8249     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8250     EVT ResVT = Use->getValueType(0);
8251     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8252     const TargetRegisterClass *ArgRC =
8253         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8254     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8255       return false;
8256
8257     // At this point, we know that we perform a cross-register-bank copy.
8258     // Check if it is expensive.
8259     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8260     // Assume bitcasts are cheap, unless both register classes do not
8261     // explicitly share a common sub class.
8262     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8263       return false;
8264
8265     // Check if it will be merged with the load.
8266     // 1. Check the alignment constraint.
8267     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8268         ResVT.getTypeForEVT(*DAG->getContext()));
8269
8270     if (RequiredAlignment > getAlignment())
8271       return false;
8272
8273     // 2. Check that the load is a legal operation for that type.
8274     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8275       return false;
8276
8277     // 3. Check that we do not have a zext in the way.
8278     if (Inst->getValueType(0) != getLoadedType())
8279       return false;
8280
8281     return true;
8282   }
8283 };
8284 }
8285
8286 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8287 /// \p UsedBits looks like 0..0 1..1 0..0.
8288 static bool areUsedBitsDense(const APInt &UsedBits) {
8289   // If all the bits are one, this is dense!
8290   if (UsedBits.isAllOnesValue())
8291     return true;
8292
8293   // Get rid of the unused bits on the right.
8294   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8295   // Get rid of the unused bits on the left.
8296   if (NarrowedUsedBits.countLeadingZeros())
8297     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8298   // Check that the chunk of bits is completely used.
8299   return NarrowedUsedBits.isAllOnesValue();
8300 }
8301
8302 /// \brief Check whether or not \p First and \p Second are next to each other
8303 /// in memory. This means that there is no hole between the bits loaded
8304 /// by \p First and the bits loaded by \p Second.
8305 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8306                                      const LoadedSlice &Second) {
8307   assert(First.Origin == Second.Origin && First.Origin &&
8308          "Unable to match different memory origins.");
8309   APInt UsedBits = First.getUsedBits();
8310   assert((UsedBits & Second.getUsedBits()) == 0 &&
8311          "Slices are not supposed to overlap.");
8312   UsedBits |= Second.getUsedBits();
8313   return areUsedBitsDense(UsedBits);
8314 }
8315
8316 /// \brief Adjust the \p GlobalLSCost according to the target
8317 /// paring capabilities and the layout of the slices.
8318 /// \pre \p GlobalLSCost should account for at least as many loads as
8319 /// there is in the slices in \p LoadedSlices.
8320 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8321                                  LoadedSlice::Cost &GlobalLSCost) {
8322   unsigned NumberOfSlices = LoadedSlices.size();
8323   // If there is less than 2 elements, no pairing is possible.
8324   if (NumberOfSlices < 2)
8325     return;
8326
8327   // Sort the slices so that elements that are likely to be next to each
8328   // other in memory are next to each other in the list.
8329   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8330             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8331     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8332     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8333   });
8334   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8335   // First (resp. Second) is the first (resp. Second) potentially candidate
8336   // to be placed in a paired load.
8337   const LoadedSlice *First = nullptr;
8338   const LoadedSlice *Second = nullptr;
8339   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8340                 // Set the beginning of the pair.
8341                                                            First = Second) {
8342
8343     Second = &LoadedSlices[CurrSlice];
8344
8345     // If First is NULL, it means we start a new pair.
8346     // Get to the next slice.
8347     if (!First)
8348       continue;
8349
8350     EVT LoadedType = First->getLoadedType();
8351
8352     // If the types of the slices are different, we cannot pair them.
8353     if (LoadedType != Second->getLoadedType())
8354       continue;
8355
8356     // Check if the target supplies paired loads for this type.
8357     unsigned RequiredAlignment = 0;
8358     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8359       // move to the next pair, this type is hopeless.
8360       Second = nullptr;
8361       continue;
8362     }
8363     // Check if we meet the alignment requirement.
8364     if (RequiredAlignment > First->getAlignment())
8365       continue;
8366
8367     // Check that both loads are next to each other in memory.
8368     if (!areSlicesNextToEachOther(*First, *Second))
8369       continue;
8370
8371     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8372     --GlobalLSCost.Loads;
8373     // Move to the next pair.
8374     Second = nullptr;
8375   }
8376 }
8377
8378 /// \brief Check the profitability of all involved LoadedSlice.
8379 /// Currently, it is considered profitable if there is exactly two
8380 /// involved slices (1) which are (2) next to each other in memory, and
8381 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8382 ///
8383 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8384 /// the elements themselves.
8385 ///
8386 /// FIXME: When the cost model will be mature enough, we can relax
8387 /// constraints (1) and (2).
8388 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8389                                 const APInt &UsedBits, bool ForCodeSize) {
8390   unsigned NumberOfSlices = LoadedSlices.size();
8391   if (StressLoadSlicing)
8392     return NumberOfSlices > 1;
8393
8394   // Check (1).
8395   if (NumberOfSlices != 2)
8396     return false;
8397
8398   // Check (2).
8399   if (!areUsedBitsDense(UsedBits))
8400     return false;
8401
8402   // Check (3).
8403   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8404   // The original code has one big load.
8405   OrigCost.Loads = 1;
8406   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8407     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8408     // Accumulate the cost of all the slices.
8409     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8410     GlobalSlicingCost += SliceCost;
8411
8412     // Account as cost in the original configuration the gain obtained
8413     // with the current slices.
8414     OrigCost.addSliceGain(LS);
8415   }
8416
8417   // If the target supports paired load, adjust the cost accordingly.
8418   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8419   return OrigCost > GlobalSlicingCost;
8420 }
8421
8422 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8423 /// operations, split it in the various pieces being extracted.
8424 ///
8425 /// This sort of thing is introduced by SROA.
8426 /// This slicing takes care not to insert overlapping loads.
8427 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8428 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8429   if (Level < AfterLegalizeDAG)
8430     return false;
8431
8432   LoadSDNode *LD = cast<LoadSDNode>(N);
8433   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8434       !LD->getValueType(0).isInteger())
8435     return false;
8436
8437   // Keep track of already used bits to detect overlapping values.
8438   // In that case, we will just abort the transformation.
8439   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8440
8441   SmallVector<LoadedSlice, 4> LoadedSlices;
8442
8443   // Check if this load is used as several smaller chunks of bits.
8444   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8445   // of computation for each trunc.
8446   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8447        UI != UIEnd; ++UI) {
8448     // Skip the uses of the chain.
8449     if (UI.getUse().getResNo() != 0)
8450       continue;
8451
8452     SDNode *User = *UI;
8453     unsigned Shift = 0;
8454
8455     // Check if this is a trunc(lshr).
8456     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8457         isa<ConstantSDNode>(User->getOperand(1))) {
8458       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8459       User = *User->use_begin();
8460     }
8461
8462     // At this point, User is a Truncate, iff we encountered, trunc or
8463     // trunc(lshr).
8464     if (User->getOpcode() != ISD::TRUNCATE)
8465       return false;
8466
8467     // The width of the type must be a power of 2 and greater than 8-bits.
8468     // Otherwise the load cannot be represented in LLVM IR.
8469     // Moreover, if we shifted with a non-8-bits multiple, the slice
8470     // will be across several bytes. We do not support that.
8471     unsigned Width = User->getValueSizeInBits(0);
8472     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8473       return 0;
8474
8475     // Build the slice for this chain of computations.
8476     LoadedSlice LS(User, LD, Shift, &DAG);
8477     APInt CurrentUsedBits = LS.getUsedBits();
8478
8479     // Check if this slice overlaps with another.
8480     if ((CurrentUsedBits & UsedBits) != 0)
8481       return false;
8482     // Update the bits used globally.
8483     UsedBits |= CurrentUsedBits;
8484
8485     // Check if the new slice would be legal.
8486     if (!LS.isLegal())
8487       return false;
8488
8489     // Record the slice.
8490     LoadedSlices.push_back(LS);
8491   }
8492
8493   // Abort slicing if it does not seem to be profitable.
8494   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8495     return false;
8496
8497   ++SlicedLoads;
8498
8499   // Rewrite each chain to use an independent load.
8500   // By construction, each chain can be represented by a unique load.
8501
8502   // Prepare the argument for the new token factor for all the slices.
8503   SmallVector<SDValue, 8> ArgChains;
8504   for (SmallVectorImpl<LoadedSlice>::const_iterator
8505            LSIt = LoadedSlices.begin(),
8506            LSItEnd = LoadedSlices.end();
8507        LSIt != LSItEnd; ++LSIt) {
8508     SDValue SliceInst = LSIt->loadSlice();
8509     CombineTo(LSIt->Inst, SliceInst, true);
8510     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8511       SliceInst = SliceInst.getOperand(0);
8512     assert(SliceInst->getOpcode() == ISD::LOAD &&
8513            "It takes more than a zext to get to the loaded slice!!");
8514     ArgChains.push_back(SliceInst.getValue(1));
8515   }
8516
8517   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8518                               ArgChains);
8519   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8520   return true;
8521 }
8522
8523 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8524 /// load is having specific bytes cleared out.  If so, return the byte size
8525 /// being masked out and the shift amount.
8526 static std::pair<unsigned, unsigned>
8527 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8528   std::pair<unsigned, unsigned> Result(0, 0);
8529
8530   // Check for the structure we're looking for.
8531   if (V->getOpcode() != ISD::AND ||
8532       !isa<ConstantSDNode>(V->getOperand(1)) ||
8533       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8534     return Result;
8535
8536   // Check the chain and pointer.
8537   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8538   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8539
8540   // The store should be chained directly to the load or be an operand of a
8541   // tokenfactor.
8542   if (LD == Chain.getNode())
8543     ; // ok.
8544   else if (Chain->getOpcode() != ISD::TokenFactor)
8545     return Result; // Fail.
8546   else {
8547     bool isOk = false;
8548     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8549       if (Chain->getOperand(i).getNode() == LD) {
8550         isOk = true;
8551         break;
8552       }
8553     if (!isOk) return Result;
8554   }
8555
8556   // This only handles simple types.
8557   if (V.getValueType() != MVT::i16 &&
8558       V.getValueType() != MVT::i32 &&
8559       V.getValueType() != MVT::i64)
8560     return Result;
8561
8562   // Check the constant mask.  Invert it so that the bits being masked out are
8563   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8564   // follow the sign bit for uniformity.
8565   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8566   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8567   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8568   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8569   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8570   if (NotMaskLZ == 64) return Result;  // All zero mask.
8571
8572   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8573   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8574     return Result;
8575
8576   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8577   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8578     NotMaskLZ -= 64-V.getValueSizeInBits();
8579
8580   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8581   switch (MaskedBytes) {
8582   case 1:
8583   case 2:
8584   case 4: break;
8585   default: return Result; // All one mask, or 5-byte mask.
8586   }
8587
8588   // Verify that the first bit starts at a multiple of mask so that the access
8589   // is aligned the same as the access width.
8590   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8591
8592   Result.first = MaskedBytes;
8593   Result.second = NotMaskTZ/8;
8594   return Result;
8595 }
8596
8597
8598 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8599 /// provides a value as specified by MaskInfo.  If so, replace the specified
8600 /// store with a narrower store of truncated IVal.
8601 static SDNode *
8602 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8603                                 SDValue IVal, StoreSDNode *St,
8604                                 DAGCombiner *DC) {
8605   unsigned NumBytes = MaskInfo.first;
8606   unsigned ByteShift = MaskInfo.second;
8607   SelectionDAG &DAG = DC->getDAG();
8608
8609   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8610   // that uses this.  If not, this is not a replacement.
8611   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8612                                   ByteShift*8, (ByteShift+NumBytes)*8);
8613   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8614
8615   // Check that it is legal on the target to do this.  It is legal if the new
8616   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8617   // legalization.
8618   MVT VT = MVT::getIntegerVT(NumBytes*8);
8619   if (!DC->isTypeLegal(VT))
8620     return nullptr;
8621
8622   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8623   // shifted by ByteShift and truncated down to NumBytes.
8624   if (ByteShift)
8625     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8626                        DAG.getConstant(ByteShift*8,
8627                                     DC->getShiftAmountTy(IVal.getValueType())));
8628
8629   // Figure out the offset for the store and the alignment of the access.
8630   unsigned StOffset;
8631   unsigned NewAlign = St->getAlignment();
8632
8633   if (DAG.getTargetLoweringInfo().isLittleEndian())
8634     StOffset = ByteShift;
8635   else
8636     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8637
8638   SDValue Ptr = St->getBasePtr();
8639   if (StOffset) {
8640     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8641                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8642     NewAlign = MinAlign(NewAlign, StOffset);
8643   }
8644
8645   // Truncate down to the new size.
8646   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8647
8648   ++OpsNarrowed;
8649   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8650                       St->getPointerInfo().getWithOffset(StOffset),
8651                       false, false, NewAlign).getNode();
8652 }
8653
8654
8655 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8656 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8657 /// of the loaded bits, try narrowing the load and store if it would end up
8658 /// being a win for performance or code size.
8659 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8660   StoreSDNode *ST  = cast<StoreSDNode>(N);
8661   if (ST->isVolatile())
8662     return SDValue();
8663
8664   SDValue Chain = ST->getChain();
8665   SDValue Value = ST->getValue();
8666   SDValue Ptr   = ST->getBasePtr();
8667   EVT VT = Value.getValueType();
8668
8669   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8670     return SDValue();
8671
8672   unsigned Opc = Value.getOpcode();
8673
8674   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8675   // is a byte mask indicating a consecutive number of bytes, check to see if
8676   // Y is known to provide just those bytes.  If so, we try to replace the
8677   // load + replace + store sequence with a single (narrower) store, which makes
8678   // the load dead.
8679   if (Opc == ISD::OR) {
8680     std::pair<unsigned, unsigned> MaskedLoad;
8681     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8682     if (MaskedLoad.first)
8683       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8684                                                   Value.getOperand(1), ST,this))
8685         return SDValue(NewST, 0);
8686
8687     // Or is commutative, so try swapping X and Y.
8688     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8689     if (MaskedLoad.first)
8690       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8691                                                   Value.getOperand(0), ST,this))
8692         return SDValue(NewST, 0);
8693   }
8694
8695   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8696       Value.getOperand(1).getOpcode() != ISD::Constant)
8697     return SDValue();
8698
8699   SDValue N0 = Value.getOperand(0);
8700   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8701       Chain == SDValue(N0.getNode(), 1)) {
8702     LoadSDNode *LD = cast<LoadSDNode>(N0);
8703     if (LD->getBasePtr() != Ptr ||
8704         LD->getPointerInfo().getAddrSpace() !=
8705         ST->getPointerInfo().getAddrSpace())
8706       return SDValue();
8707
8708     // Find the type to narrow it the load / op / store to.
8709     SDValue N1 = Value.getOperand(1);
8710     unsigned BitWidth = N1.getValueSizeInBits();
8711     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8712     if (Opc == ISD::AND)
8713       Imm ^= APInt::getAllOnesValue(BitWidth);
8714     if (Imm == 0 || Imm.isAllOnesValue())
8715       return SDValue();
8716     unsigned ShAmt = Imm.countTrailingZeros();
8717     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8718     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8719     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8720     while (NewBW < BitWidth &&
8721            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8722              TLI.isNarrowingProfitable(VT, NewVT))) {
8723       NewBW = NextPowerOf2(NewBW);
8724       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8725     }
8726     if (NewBW >= BitWidth)
8727       return SDValue();
8728
8729     // If the lsb changed does not start at the type bitwidth boundary,
8730     // start at the previous one.
8731     if (ShAmt % NewBW)
8732       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8733     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8734                                    std::min(BitWidth, ShAmt + NewBW));
8735     if ((Imm & Mask) == Imm) {
8736       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8737       if (Opc == ISD::AND)
8738         NewImm ^= APInt::getAllOnesValue(NewBW);
8739       uint64_t PtrOff = ShAmt / 8;
8740       // For big endian targets, we need to adjust the offset to the pointer to
8741       // load the correct bytes.
8742       if (TLI.isBigEndian())
8743         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8744
8745       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8746       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8747       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8748         return SDValue();
8749
8750       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8751                                    Ptr.getValueType(), Ptr,
8752                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8753       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8754                                   LD->getChain(), NewPtr,
8755                                   LD->getPointerInfo().getWithOffset(PtrOff),
8756                                   LD->isVolatile(), LD->isNonTemporal(),
8757                                   LD->isInvariant(), NewAlign,
8758                                   LD->getTBAAInfo());
8759       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8760                                    DAG.getConstant(NewImm, NewVT));
8761       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8762                                    NewVal, NewPtr,
8763                                    ST->getPointerInfo().getWithOffset(PtrOff),
8764                                    false, false, NewAlign);
8765
8766       AddToWorkList(NewPtr.getNode());
8767       AddToWorkList(NewLD.getNode());
8768       AddToWorkList(NewVal.getNode());
8769       WorkListRemover DeadNodes(*this);
8770       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8771       ++OpsNarrowed;
8772       return NewST;
8773     }
8774   }
8775
8776   return SDValue();
8777 }
8778
8779 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8780 /// if the load value isn't used by any other operations, then consider
8781 /// transforming the pair to integer load / store operations if the target
8782 /// deems the transformation profitable.
8783 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8784   StoreSDNode *ST  = cast<StoreSDNode>(N);
8785   SDValue Chain = ST->getChain();
8786   SDValue Value = ST->getValue();
8787   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8788       Value.hasOneUse() &&
8789       Chain == SDValue(Value.getNode(), 1)) {
8790     LoadSDNode *LD = cast<LoadSDNode>(Value);
8791     EVT VT = LD->getMemoryVT();
8792     if (!VT.isFloatingPoint() ||
8793         VT != ST->getMemoryVT() ||
8794         LD->isNonTemporal() ||
8795         ST->isNonTemporal() ||
8796         LD->getPointerInfo().getAddrSpace() != 0 ||
8797         ST->getPointerInfo().getAddrSpace() != 0)
8798       return SDValue();
8799
8800     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8801     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8802         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8803         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8804         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8805       return SDValue();
8806
8807     unsigned LDAlign = LD->getAlignment();
8808     unsigned STAlign = ST->getAlignment();
8809     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8810     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8811     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8812       return SDValue();
8813
8814     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8815                                 LD->getChain(), LD->getBasePtr(),
8816                                 LD->getPointerInfo(),
8817                                 false, false, false, LDAlign);
8818
8819     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8820                                  NewLD, ST->getBasePtr(),
8821                                  ST->getPointerInfo(),
8822                                  false, false, STAlign);
8823
8824     AddToWorkList(NewLD.getNode());
8825     AddToWorkList(NewST.getNode());
8826     WorkListRemover DeadNodes(*this);
8827     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8828     ++LdStFP2Int;
8829     return NewST;
8830   }
8831
8832   return SDValue();
8833 }
8834
8835 /// Helper struct to parse and store a memory address as base + index + offset.
8836 /// We ignore sign extensions when it is safe to do so.
8837 /// The following two expressions are not equivalent. To differentiate we need
8838 /// to store whether there was a sign extension involved in the index
8839 /// computation.
8840 ///  (load (i64 add (i64 copyfromreg %c)
8841 ///                 (i64 signextend (add (i8 load %index)
8842 ///                                      (i8 1))))
8843 /// vs
8844 ///
8845 /// (load (i64 add (i64 copyfromreg %c)
8846 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8847 ///                                         (i32 1)))))
8848 struct BaseIndexOffset {
8849   SDValue Base;
8850   SDValue Index;
8851   int64_t Offset;
8852   bool IsIndexSignExt;
8853
8854   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8855
8856   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8857                   bool IsIndexSignExt) :
8858     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8859
8860   bool equalBaseIndex(const BaseIndexOffset &Other) {
8861     return Other.Base == Base && Other.Index == Index &&
8862       Other.IsIndexSignExt == IsIndexSignExt;
8863   }
8864
8865   /// Parses tree in Ptr for base, index, offset addresses.
8866   static BaseIndexOffset match(SDValue Ptr) {
8867     bool IsIndexSignExt = false;
8868
8869     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8870     // instruction, then it could be just the BASE or everything else we don't
8871     // know how to handle. Just use Ptr as BASE and give up.
8872     if (Ptr->getOpcode() != ISD::ADD)
8873       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8874
8875     // We know that we have at least an ADD instruction. Try to pattern match
8876     // the simple case of BASE + OFFSET.
8877     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8878       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8879       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8880                               IsIndexSignExt);
8881     }
8882
8883     // Inside a loop the current BASE pointer is calculated using an ADD and a
8884     // MUL instruction. In this case Ptr is the actual BASE pointer.
8885     // (i64 add (i64 %array_ptr)
8886     //          (i64 mul (i64 %induction_var)
8887     //                   (i64 %element_size)))
8888     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8889       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8890
8891     // Look at Base + Index + Offset cases.
8892     SDValue Base = Ptr->getOperand(0);
8893     SDValue IndexOffset = Ptr->getOperand(1);
8894
8895     // Skip signextends.
8896     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8897       IndexOffset = IndexOffset->getOperand(0);
8898       IsIndexSignExt = true;
8899     }
8900
8901     // Either the case of Base + Index (no offset) or something else.
8902     if (IndexOffset->getOpcode() != ISD::ADD)
8903       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8904
8905     // Now we have the case of Base + Index + offset.
8906     SDValue Index = IndexOffset->getOperand(0);
8907     SDValue Offset = IndexOffset->getOperand(1);
8908
8909     if (!isa<ConstantSDNode>(Offset))
8910       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8911
8912     // Ignore signextends.
8913     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8914       Index = Index->getOperand(0);
8915       IsIndexSignExt = true;
8916     } else IsIndexSignExt = false;
8917
8918     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8919     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8920   }
8921 };
8922
8923 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8924 /// is located in a sequence of memory operations connected by a chain.
8925 struct MemOpLink {
8926   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8927     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8928   // Ptr to the mem node.
8929   LSBaseSDNode *MemNode;
8930   // Offset from the base ptr.
8931   int64_t OffsetFromBase;
8932   // What is the sequence number of this mem node.
8933   // Lowest mem operand in the DAG starts at zero.
8934   unsigned SequenceNum;
8935 };
8936
8937 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8938   EVT MemVT = St->getMemoryVT();
8939   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8940   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8941     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8942
8943   // Don't merge vectors into wider inputs.
8944   if (MemVT.isVector() || !MemVT.isSimple())
8945     return false;
8946
8947   // Perform an early exit check. Do not bother looking at stored values that
8948   // are not constants or loads.
8949   SDValue StoredVal = St->getValue();
8950   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8951   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8952       !IsLoadSrc)
8953     return false;
8954
8955   // Only look at ends of store sequences.
8956   SDValue Chain = SDValue(St, 1);
8957   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8958     return false;
8959
8960   // This holds the base pointer, index, and the offset in bytes from the base
8961   // pointer.
8962   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8963
8964   // We must have a base and an offset.
8965   if (!BasePtr.Base.getNode())
8966     return false;
8967
8968   // Do not handle stores to undef base pointers.
8969   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8970     return false;
8971
8972   // Save the LoadSDNodes that we find in the chain.
8973   // We need to make sure that these nodes do not interfere with
8974   // any of the store nodes.
8975   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8976
8977   // Save the StoreSDNodes that we find in the chain.
8978   SmallVector<MemOpLink, 8> StoreNodes;
8979
8980   // Walk up the chain and look for nodes with offsets from the same
8981   // base pointer. Stop when reaching an instruction with a different kind
8982   // or instruction which has a different base pointer.
8983   unsigned Seq = 0;
8984   StoreSDNode *Index = St;
8985   while (Index) {
8986     // If the chain has more than one use, then we can't reorder the mem ops.
8987     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8988       break;
8989
8990     // Find the base pointer and offset for this memory node.
8991     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8992
8993     // Check that the base pointer is the same as the original one.
8994     if (!Ptr.equalBaseIndex(BasePtr))
8995       break;
8996
8997     // Check that the alignment is the same.
8998     if (Index->getAlignment() != St->getAlignment())
8999       break;
9000
9001     // The memory operands must not be volatile.
9002     if (Index->isVolatile() || Index->isIndexed())
9003       break;
9004
9005     // No truncation.
9006     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9007       if (St->isTruncatingStore())
9008         break;
9009
9010     // The stored memory type must be the same.
9011     if (Index->getMemoryVT() != MemVT)
9012       break;
9013
9014     // We do not allow unaligned stores because we want to prevent overriding
9015     // stores.
9016     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9017       break;
9018
9019     // We found a potential memory operand to merge.
9020     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9021
9022     // Find the next memory operand in the chain. If the next operand in the
9023     // chain is a store then move up and continue the scan with the next
9024     // memory operand. If the next operand is a load save it and use alias
9025     // information to check if it interferes with anything.
9026     SDNode *NextInChain = Index->getChain().getNode();
9027     while (1) {
9028       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9029         // We found a store node. Use it for the next iteration.
9030         Index = STn;
9031         break;
9032       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9033         if (Ldn->isVolatile()) {
9034           Index = nullptr;
9035           break;
9036         }
9037
9038         // Save the load node for later. Continue the scan.
9039         AliasLoadNodes.push_back(Ldn);
9040         NextInChain = Ldn->getChain().getNode();
9041         continue;
9042       } else {
9043         Index = nullptr;
9044         break;
9045       }
9046     }
9047   }
9048
9049   // Check if there is anything to merge.
9050   if (StoreNodes.size() < 2)
9051     return false;
9052
9053   // Sort the memory operands according to their distance from the base pointer.
9054   std::sort(StoreNodes.begin(), StoreNodes.end(),
9055             [](MemOpLink LHS, MemOpLink RHS) {
9056     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9057            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9058             LHS.SequenceNum > RHS.SequenceNum);
9059   });
9060
9061   // Scan the memory operations on the chain and find the first non-consecutive
9062   // store memory address.
9063   unsigned LastConsecutiveStore = 0;
9064   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9065   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9066
9067     // Check that the addresses are consecutive starting from the second
9068     // element in the list of stores.
9069     if (i > 0) {
9070       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9071       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9072         break;
9073     }
9074
9075     bool Alias = false;
9076     // Check if this store interferes with any of the loads that we found.
9077     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9078       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9079         Alias = true;
9080         break;
9081       }
9082     // We found a load that alias with this store. Stop the sequence.
9083     if (Alias)
9084       break;
9085
9086     // Mark this node as useful.
9087     LastConsecutiveStore = i;
9088   }
9089
9090   // The node with the lowest store address.
9091   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9092
9093   // Store the constants into memory as one consecutive store.
9094   if (!IsLoadSrc) {
9095     unsigned LastLegalType = 0;
9096     unsigned LastLegalVectorType = 0;
9097     bool NonZero = false;
9098     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9099       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9100       SDValue StoredVal = St->getValue();
9101
9102       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9103         NonZero |= !C->isNullValue();
9104       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9105         NonZero |= !C->getConstantFPValue()->isNullValue();
9106       } else {
9107         // Non-constant.
9108         break;
9109       }
9110
9111       // Find a legal type for the constant store.
9112       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9113       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9114       if (TLI.isTypeLegal(StoreTy))
9115         LastLegalType = i+1;
9116       // Or check whether a truncstore is legal.
9117       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9118                TargetLowering::TypePromoteInteger) {
9119         EVT LegalizedStoredValueTy =
9120           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9121         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9122           LastLegalType = i+1;
9123       }
9124
9125       // Find a legal type for the vector store.
9126       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9127       if (TLI.isTypeLegal(Ty))
9128         LastLegalVectorType = i + 1;
9129     }
9130
9131     // We only use vectors if the constant is known to be zero and the
9132     // function is not marked with the noimplicitfloat attribute.
9133     if (NonZero || NoVectors)
9134       LastLegalVectorType = 0;
9135
9136     // Check if we found a legal integer type to store.
9137     if (LastLegalType == 0 && LastLegalVectorType == 0)
9138       return false;
9139
9140     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9141     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9142
9143     // Make sure we have something to merge.
9144     if (NumElem < 2)
9145       return false;
9146
9147     unsigned EarliestNodeUsed = 0;
9148     for (unsigned i=0; i < NumElem; ++i) {
9149       // Find a chain for the new wide-store operand. Notice that some
9150       // of the store nodes that we found may not be selected for inclusion
9151       // in the wide store. The chain we use needs to be the chain of the
9152       // earliest store node which is *used* and replaced by the wide store.
9153       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9154         EarliestNodeUsed = i;
9155     }
9156
9157     // The earliest Node in the DAG.
9158     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9159     SDLoc DL(StoreNodes[0].MemNode);
9160
9161     SDValue StoredVal;
9162     if (UseVector) {
9163       // Find a legal type for the vector store.
9164       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9165       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9166       StoredVal = DAG.getConstant(0, Ty);
9167     } else {
9168       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9169       APInt StoreInt(StoreBW, 0);
9170
9171       // Construct a single integer constant which is made of the smaller
9172       // constant inputs.
9173       bool IsLE = TLI.isLittleEndian();
9174       for (unsigned i = 0; i < NumElem ; ++i) {
9175         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9176         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9177         SDValue Val = St->getValue();
9178         StoreInt<<=ElementSizeBytes*8;
9179         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9180           StoreInt|=C->getAPIntValue().zext(StoreBW);
9181         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9182           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9183         } else {
9184           assert(false && "Invalid constant element type");
9185         }
9186       }
9187
9188       // Create the new Load and Store operations.
9189       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9190       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9191     }
9192
9193     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9194                                     FirstInChain->getBasePtr(),
9195                                     FirstInChain->getPointerInfo(),
9196                                     false, false,
9197                                     FirstInChain->getAlignment());
9198
9199     // Replace the first store with the new store
9200     CombineTo(EarliestOp, NewStore);
9201     // Erase all other stores.
9202     for (unsigned i = 0; i < NumElem ; ++i) {
9203       if (StoreNodes[i].MemNode == EarliestOp)
9204         continue;
9205       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9206       // ReplaceAllUsesWith will replace all uses that existed when it was
9207       // called, but graph optimizations may cause new ones to appear. For
9208       // example, the case in pr14333 looks like
9209       //
9210       //  St's chain -> St -> another store -> X
9211       //
9212       // And the only difference from St to the other store is the chain.
9213       // When we change it's chain to be St's chain they become identical,
9214       // get CSEed and the net result is that X is now a use of St.
9215       // Since we know that St is redundant, just iterate.
9216       while (!St->use_empty())
9217         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9218       removeFromWorkList(St);
9219       DAG.DeleteNode(St);
9220     }
9221
9222     return true;
9223   }
9224
9225   // Below we handle the case of multiple consecutive stores that
9226   // come from multiple consecutive loads. We merge them into a single
9227   // wide load and a single wide store.
9228
9229   // Look for load nodes which are used by the stored values.
9230   SmallVector<MemOpLink, 8> LoadNodes;
9231
9232   // Find acceptable loads. Loads need to have the same chain (token factor),
9233   // must not be zext, volatile, indexed, and they must be consecutive.
9234   BaseIndexOffset LdBasePtr;
9235   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9236     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9237     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9238     if (!Ld) break;
9239
9240     // Loads must only have one use.
9241     if (!Ld->hasNUsesOfValue(1, 0))
9242       break;
9243
9244     // Check that the alignment is the same as the stores.
9245     if (Ld->getAlignment() != St->getAlignment())
9246       break;
9247
9248     // The memory operands must not be volatile.
9249     if (Ld->isVolatile() || Ld->isIndexed())
9250       break;
9251
9252     // We do not accept ext loads.
9253     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9254       break;
9255
9256     // The stored memory type must be the same.
9257     if (Ld->getMemoryVT() != MemVT)
9258       break;
9259
9260     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9261     // If this is not the first ptr that we check.
9262     if (LdBasePtr.Base.getNode()) {
9263       // The base ptr must be the same.
9264       if (!LdPtr.equalBaseIndex(LdBasePtr))
9265         break;
9266     } else {
9267       // Check that all other base pointers are the same as this one.
9268       LdBasePtr = LdPtr;
9269     }
9270
9271     // We found a potential memory operand to merge.
9272     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9273   }
9274
9275   if (LoadNodes.size() < 2)
9276     return false;
9277
9278   // Scan the memory operations on the chain and find the first non-consecutive
9279   // load memory address. These variables hold the index in the store node
9280   // array.
9281   unsigned LastConsecutiveLoad = 0;
9282   // This variable refers to the size and not index in the array.
9283   unsigned LastLegalVectorType = 0;
9284   unsigned LastLegalIntegerType = 0;
9285   StartAddress = LoadNodes[0].OffsetFromBase;
9286   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9287   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9288     // All loads much share the same chain.
9289     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9290       break;
9291
9292     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9293     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9294       break;
9295     LastConsecutiveLoad = i;
9296
9297     // Find a legal type for the vector store.
9298     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9299     if (TLI.isTypeLegal(StoreTy))
9300       LastLegalVectorType = i + 1;
9301
9302     // Find a legal type for the integer store.
9303     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9304     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9305     if (TLI.isTypeLegal(StoreTy))
9306       LastLegalIntegerType = i + 1;
9307     // Or check whether a truncstore and extload is legal.
9308     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9309              TargetLowering::TypePromoteInteger) {
9310       EVT LegalizedStoredValueTy =
9311         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9312       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9313           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9314           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9315           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9316         LastLegalIntegerType = i+1;
9317     }
9318   }
9319
9320   // Only use vector types if the vector type is larger than the integer type.
9321   // If they are the same, use integers.
9322   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9323   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9324
9325   // We add +1 here because the LastXXX variables refer to location while
9326   // the NumElem refers to array/index size.
9327   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9328   NumElem = std::min(LastLegalType, NumElem);
9329
9330   if (NumElem < 2)
9331     return false;
9332
9333   // The earliest Node in the DAG.
9334   unsigned EarliestNodeUsed = 0;
9335   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9336   for (unsigned i=1; i<NumElem; ++i) {
9337     // Find a chain for the new wide-store operand. Notice that some
9338     // of the store nodes that we found may not be selected for inclusion
9339     // in the wide store. The chain we use needs to be the chain of the
9340     // earliest store node which is *used* and replaced by the wide store.
9341     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9342       EarliestNodeUsed = i;
9343   }
9344
9345   // Find if it is better to use vectors or integers to load and store
9346   // to memory.
9347   EVT JointMemOpVT;
9348   if (UseVectorTy) {
9349     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9350   } else {
9351     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9352     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9353   }
9354
9355   SDLoc LoadDL(LoadNodes[0].MemNode);
9356   SDLoc StoreDL(StoreNodes[0].MemNode);
9357
9358   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9359   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9360                                 FirstLoad->getChain(),
9361                                 FirstLoad->getBasePtr(),
9362                                 FirstLoad->getPointerInfo(),
9363                                 false, false, false,
9364                                 FirstLoad->getAlignment());
9365
9366   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9367                                   FirstInChain->getBasePtr(),
9368                                   FirstInChain->getPointerInfo(), false, false,
9369                                   FirstInChain->getAlignment());
9370
9371   // Replace one of the loads with the new load.
9372   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9373   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9374                                 SDValue(NewLoad.getNode(), 1));
9375
9376   // Remove the rest of the load chains.
9377   for (unsigned i = 1; i < NumElem ; ++i) {
9378     // Replace all chain users of the old load nodes with the chain of the new
9379     // load node.
9380     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9381     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9382   }
9383
9384   // Replace the first store with the new store.
9385   CombineTo(EarliestOp, NewStore);
9386   // Erase all other stores.
9387   for (unsigned i = 0; i < NumElem ; ++i) {
9388     // Remove all Store nodes.
9389     if (StoreNodes[i].MemNode == EarliestOp)
9390       continue;
9391     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9392     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9393     removeFromWorkList(St);
9394     DAG.DeleteNode(St);
9395   }
9396
9397   return true;
9398 }
9399
9400 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9401   StoreSDNode *ST  = cast<StoreSDNode>(N);
9402   SDValue Chain = ST->getChain();
9403   SDValue Value = ST->getValue();
9404   SDValue Ptr   = ST->getBasePtr();
9405
9406   // If this is a store of a bit convert, store the input value if the
9407   // resultant store does not need a higher alignment than the original.
9408   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9409       ST->isUnindexed()) {
9410     unsigned OrigAlign = ST->getAlignment();
9411     EVT SVT = Value.getOperand(0).getValueType();
9412     unsigned Align = TLI.getDataLayout()->
9413       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9414     if (Align <= OrigAlign &&
9415         ((!LegalOperations && !ST->isVolatile()) ||
9416          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9417       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9418                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9419                           ST->isNonTemporal(), OrigAlign,
9420                           ST->getTBAAInfo());
9421   }
9422
9423   // Turn 'store undef, Ptr' -> nothing.
9424   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9425     return Chain;
9426
9427   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9428   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9429     // NOTE: If the original store is volatile, this transform must not increase
9430     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9431     // processor operation but an i64 (which is not legal) requires two.  So the
9432     // transform should not be done in this case.
9433     if (Value.getOpcode() != ISD::TargetConstantFP) {
9434       SDValue Tmp;
9435       switch (CFP->getSimpleValueType(0).SimpleTy) {
9436       default: llvm_unreachable("Unknown FP type");
9437       case MVT::f16:    // We don't do this for these yet.
9438       case MVT::f80:
9439       case MVT::f128:
9440       case MVT::ppcf128:
9441         break;
9442       case MVT::f32:
9443         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9444             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9445           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9446                               bitcastToAPInt().getZExtValue(), MVT::i32);
9447           return DAG.getStore(Chain, SDLoc(N), Tmp,
9448                               Ptr, ST->getMemOperand());
9449         }
9450         break;
9451       case MVT::f64:
9452         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9453              !ST->isVolatile()) ||
9454             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9455           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9456                                 getZExtValue(), MVT::i64);
9457           return DAG.getStore(Chain, SDLoc(N), Tmp,
9458                               Ptr, ST->getMemOperand());
9459         }
9460
9461         if (!ST->isVolatile() &&
9462             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9463           // Many FP stores are not made apparent until after legalize, e.g. for
9464           // argument passing.  Since this is so common, custom legalize the
9465           // 64-bit integer store into two 32-bit stores.
9466           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9467           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9468           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9469           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9470
9471           unsigned Alignment = ST->getAlignment();
9472           bool isVolatile = ST->isVolatile();
9473           bool isNonTemporal = ST->isNonTemporal();
9474           const MDNode *TBAAInfo = ST->getTBAAInfo();
9475
9476           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9477                                      Ptr, ST->getPointerInfo(),
9478                                      isVolatile, isNonTemporal,
9479                                      ST->getAlignment(), TBAAInfo);
9480           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9481                             DAG.getConstant(4, Ptr.getValueType()));
9482           Alignment = MinAlign(Alignment, 4U);
9483           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9484                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9485                                      isVolatile, isNonTemporal,
9486                                      Alignment, TBAAInfo);
9487           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9488                              St0, St1);
9489         }
9490
9491         break;
9492       }
9493     }
9494   }
9495
9496   // Try to infer better alignment information than the store already has.
9497   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9498     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9499       if (Align > ST->getAlignment())
9500         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9501                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9502                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9503                                  ST->getTBAAInfo());
9504     }
9505   }
9506
9507   // Try transforming a pair floating point load / store ops to integer
9508   // load / store ops.
9509   SDValue NewST = TransformFPLoadStorePair(N);
9510   if (NewST.getNode())
9511     return NewST;
9512
9513   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9514     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9515 #ifndef NDEBUG
9516   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9517       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9518     UseAA = false;
9519 #endif
9520   if (UseAA && ST->isUnindexed()) {
9521     // Walk up chain skipping non-aliasing memory nodes.
9522     SDValue BetterChain = FindBetterChain(N, Chain);
9523
9524     // If there is a better chain.
9525     if (Chain != BetterChain) {
9526       SDValue ReplStore;
9527
9528       // Replace the chain to avoid dependency.
9529       if (ST->isTruncatingStore()) {
9530         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9531                                       ST->getMemoryVT(), ST->getMemOperand());
9532       } else {
9533         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9534                                  ST->getMemOperand());
9535       }
9536
9537       // Create token to keep both nodes around.
9538       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9539                                   MVT::Other, Chain, ReplStore);
9540
9541       // Make sure the new and old chains are cleaned up.
9542       AddToWorkList(Token.getNode());
9543
9544       // Don't add users to work list.
9545       return CombineTo(N, Token, false);
9546     }
9547   }
9548
9549   // Try transforming N to an indexed store.
9550   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9551     return SDValue(N, 0);
9552
9553   // FIXME: is there such a thing as a truncating indexed store?
9554   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9555       Value.getValueType().isInteger()) {
9556     // See if we can simplify the input to this truncstore with knowledge that
9557     // only the low bits are being used.  For example:
9558     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9559     SDValue Shorter =
9560       GetDemandedBits(Value,
9561                       APInt::getLowBitsSet(
9562                         Value.getValueType().getScalarType().getSizeInBits(),
9563                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9564     AddToWorkList(Value.getNode());
9565     if (Shorter.getNode())
9566       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9567                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9568
9569     // Otherwise, see if we can simplify the operation with
9570     // SimplifyDemandedBits, which only works if the value has a single use.
9571     if (SimplifyDemandedBits(Value,
9572                         APInt::getLowBitsSet(
9573                           Value.getValueType().getScalarType().getSizeInBits(),
9574                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9575       return SDValue(N, 0);
9576   }
9577
9578   // If this is a load followed by a store to the same location, then the store
9579   // is dead/noop.
9580   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9581     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9582         ST->isUnindexed() && !ST->isVolatile() &&
9583         // There can't be any side effects between the load and store, such as
9584         // a call or store.
9585         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9586       // The store is dead, remove it.
9587       return Chain;
9588     }
9589   }
9590
9591   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9592   // truncating store.  We can do this even if this is already a truncstore.
9593   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9594       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9595       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9596                             ST->getMemoryVT())) {
9597     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9598                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9599   }
9600
9601   // Only perform this optimization before the types are legal, because we
9602   // don't want to perform this optimization on every DAGCombine invocation.
9603   if (!LegalTypes) {
9604     bool EverChanged = false;
9605
9606     do {
9607       // There can be multiple store sequences on the same chain.
9608       // Keep trying to merge store sequences until we are unable to do so
9609       // or until we merge the last store on the chain.
9610       bool Changed = MergeConsecutiveStores(ST);
9611       EverChanged |= Changed;
9612       if (!Changed) break;
9613     } while (ST->getOpcode() != ISD::DELETED_NODE);
9614
9615     if (EverChanged)
9616       return SDValue(N, 0);
9617   }
9618
9619   return ReduceLoadOpStoreWidth(N);
9620 }
9621
9622 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9623   SDValue InVec = N->getOperand(0);
9624   SDValue InVal = N->getOperand(1);
9625   SDValue EltNo = N->getOperand(2);
9626   SDLoc dl(N);
9627
9628   // If the inserted element is an UNDEF, just use the input vector.
9629   if (InVal.getOpcode() == ISD::UNDEF)
9630     return InVec;
9631
9632   EVT VT = InVec.getValueType();
9633
9634   // If we can't generate a legal BUILD_VECTOR, exit
9635   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9636     return SDValue();
9637
9638   // Check that we know which element is being inserted
9639   if (!isa<ConstantSDNode>(EltNo))
9640     return SDValue();
9641   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9642
9643   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9644   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9645   // vector elements.
9646   SmallVector<SDValue, 8> Ops;
9647   // Do not combine these two vectors if the output vector will not replace
9648   // the input vector.
9649   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9650     Ops.append(InVec.getNode()->op_begin(),
9651                InVec.getNode()->op_end());
9652   } else if (InVec.getOpcode() == ISD::UNDEF) {
9653     unsigned NElts = VT.getVectorNumElements();
9654     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9655   } else {
9656     return SDValue();
9657   }
9658
9659   // Insert the element
9660   if (Elt < Ops.size()) {
9661     // All the operands of BUILD_VECTOR must have the same type;
9662     // we enforce that here.
9663     EVT OpVT = Ops[0].getValueType();
9664     if (InVal.getValueType() != OpVT)
9665       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9666                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9667                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9668     Ops[Elt] = InVal;
9669   }
9670
9671   // Return the new vector
9672   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9673 }
9674
9675 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9676   // (vextract (scalar_to_vector val, 0) -> val
9677   SDValue InVec = N->getOperand(0);
9678   EVT VT = InVec.getValueType();
9679   EVT NVT = N->getValueType(0);
9680
9681   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9682     // Check if the result type doesn't match the inserted element type. A
9683     // SCALAR_TO_VECTOR may truncate the inserted element and the
9684     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9685     SDValue InOp = InVec.getOperand(0);
9686     if (InOp.getValueType() != NVT) {
9687       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9688       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9689     }
9690     return InOp;
9691   }
9692
9693   SDValue EltNo = N->getOperand(1);
9694   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9695
9696   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9697   // We only perform this optimization before the op legalization phase because
9698   // we may introduce new vector instructions which are not backed by TD
9699   // patterns. For example on AVX, extracting elements from a wide vector
9700   // without using extract_subvector. However, if we can find an underlying
9701   // scalar value, then we can always use that.
9702   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9703       && ConstEltNo) {
9704     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9705     int NumElem = VT.getVectorNumElements();
9706     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9707     // Find the new index to extract from.
9708     int OrigElt = SVOp->getMaskElt(Elt);
9709
9710     // Extracting an undef index is undef.
9711     if (OrigElt == -1)
9712       return DAG.getUNDEF(NVT);
9713
9714     // Select the right vector half to extract from.
9715     SDValue SVInVec;
9716     if (OrigElt < NumElem) {
9717       SVInVec = InVec->getOperand(0);
9718     } else {
9719       SVInVec = InVec->getOperand(1);
9720       OrigElt -= NumElem;
9721     }
9722
9723     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9724       SDValue InOp = SVInVec.getOperand(OrigElt);
9725       if (InOp.getValueType() != NVT) {
9726         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9727         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9728       }
9729
9730       return InOp;
9731     }
9732
9733     // FIXME: We should handle recursing on other vector shuffles and
9734     // scalar_to_vector here as well.
9735
9736     if (!LegalOperations) {
9737       EVT IndexTy = TLI.getVectorIdxTy();
9738       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9739                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9740     }
9741   }
9742
9743   // Perform only after legalization to ensure build_vector / vector_shuffle
9744   // optimizations have already been done.
9745   if (!LegalOperations) return SDValue();
9746
9747   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9748   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9749   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9750
9751   if (ConstEltNo) {
9752     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9753     bool NewLoad = false;
9754     bool BCNumEltsChanged = false;
9755     EVT ExtVT = VT.getVectorElementType();
9756     EVT LVT = ExtVT;
9757
9758     // If the result of load has to be truncated, then it's not necessarily
9759     // profitable.
9760     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9761       return SDValue();
9762
9763     if (InVec.getOpcode() == ISD::BITCAST) {
9764       // Don't duplicate a load with other uses.
9765       if (!InVec.hasOneUse())
9766         return SDValue();
9767
9768       EVT BCVT = InVec.getOperand(0).getValueType();
9769       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9770         return SDValue();
9771       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9772         BCNumEltsChanged = true;
9773       InVec = InVec.getOperand(0);
9774       ExtVT = BCVT.getVectorElementType();
9775       NewLoad = true;
9776     }
9777
9778     LoadSDNode *LN0 = nullptr;
9779     const ShuffleVectorSDNode *SVN = nullptr;
9780     if (ISD::isNormalLoad(InVec.getNode())) {
9781       LN0 = cast<LoadSDNode>(InVec);
9782     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9783                InVec.getOperand(0).getValueType() == ExtVT &&
9784                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9785       // Don't duplicate a load with other uses.
9786       if (!InVec.hasOneUse())
9787         return SDValue();
9788
9789       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9790     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9791       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9792       // =>
9793       // (load $addr+1*size)
9794
9795       // Don't duplicate a load with other uses.
9796       if (!InVec.hasOneUse())
9797         return SDValue();
9798
9799       // If the bit convert changed the number of elements, it is unsafe
9800       // to examine the mask.
9801       if (BCNumEltsChanged)
9802         return SDValue();
9803
9804       // Select the input vector, guarding against out of range extract vector.
9805       unsigned NumElems = VT.getVectorNumElements();
9806       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9807       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
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         InVec = InVec.getOperand(0);
9815       }
9816       if (ISD::isNormalLoad(InVec.getNode())) {
9817         LN0 = cast<LoadSDNode>(InVec);
9818         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9819       }
9820     }
9821
9822     // Make sure we found a non-volatile load and the extractelement is
9823     // the only use.
9824     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9825       return SDValue();
9826
9827     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9828     if (Elt == -1)
9829       return DAG.getUNDEF(LVT);
9830
9831     unsigned Align = LN0->getAlignment();
9832     if (NewLoad) {
9833       // Check the resultant load doesn't need a higher alignment than the
9834       // original load.
9835       unsigned NewAlign =
9836         TLI.getDataLayout()
9837             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9838
9839       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9840         return SDValue();
9841
9842       Align = NewAlign;
9843     }
9844
9845     SDValue NewPtr = LN0->getBasePtr();
9846     unsigned PtrOff = 0;
9847
9848     if (Elt) {
9849       PtrOff = LVT.getSizeInBits() * Elt / 8;
9850       EVT PtrType = NewPtr.getValueType();
9851       if (TLI.isBigEndian())
9852         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9853       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9854                            DAG.getConstant(PtrOff, PtrType));
9855     }
9856
9857     // The replacement we need to do here is a little tricky: we need to
9858     // replace an extractelement of a load with a load.
9859     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9860     // Note that this replacement assumes that the extractvalue is the only
9861     // use of the load; that's okay because we don't want to perform this
9862     // transformation in other cases anyway.
9863     SDValue Load;
9864     SDValue Chain;
9865     if (NVT.bitsGT(LVT)) {
9866       // If the result type of vextract is wider than the load, then issue an
9867       // extending load instead.
9868       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9869         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9870       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9871                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9872                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9873                             Align, LN0->getTBAAInfo());
9874       Chain = Load.getValue(1);
9875     } else {
9876       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9877                          LN0->getPointerInfo().getWithOffset(PtrOff),
9878                          LN0->isVolatile(), LN0->isNonTemporal(),
9879                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9880       Chain = Load.getValue(1);
9881       if (NVT.bitsLT(LVT))
9882         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9883       else
9884         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9885     }
9886     WorkListRemover DeadNodes(*this);
9887     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9888     SDValue To[] = { Load, Chain };
9889     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9890     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9891     // worklist explicitly as well.
9892     AddToWorkList(Load.getNode());
9893     AddUsersToWorkList(Load.getNode()); // Add users too
9894     // Make sure to revisit this node to clean it up; it will usually be dead.
9895     AddToWorkList(N);
9896     return SDValue(N, 0);
9897   }
9898
9899   return SDValue();
9900 }
9901
9902 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9903 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9904   // We perform this optimization post type-legalization because
9905   // the type-legalizer often scalarizes integer-promoted vectors.
9906   // Performing this optimization before may create bit-casts which
9907   // will be type-legalized to complex code sequences.
9908   // We perform this optimization only before the operation legalizer because we
9909   // may introduce illegal operations.
9910   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9911     return SDValue();
9912
9913   unsigned NumInScalars = N->getNumOperands();
9914   SDLoc dl(N);
9915   EVT VT = N->getValueType(0);
9916
9917   // Check to see if this is a BUILD_VECTOR of a bunch of values
9918   // which come from any_extend or zero_extend nodes. If so, we can create
9919   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9920   // optimizations. We do not handle sign-extend because we can't fill the sign
9921   // using shuffles.
9922   EVT SourceType = MVT::Other;
9923   bool AllAnyExt = true;
9924
9925   for (unsigned i = 0; i != NumInScalars; ++i) {
9926     SDValue In = N->getOperand(i);
9927     // Ignore undef inputs.
9928     if (In.getOpcode() == ISD::UNDEF) continue;
9929
9930     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9931     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9932
9933     // Abort if the element is not an extension.
9934     if (!ZeroExt && !AnyExt) {
9935       SourceType = MVT::Other;
9936       break;
9937     }
9938
9939     // The input is a ZeroExt or AnyExt. Check the original type.
9940     EVT InTy = In.getOperand(0).getValueType();
9941
9942     // Check that all of the widened source types are the same.
9943     if (SourceType == MVT::Other)
9944       // First time.
9945       SourceType = InTy;
9946     else if (InTy != SourceType) {
9947       // Multiple income types. Abort.
9948       SourceType = MVT::Other;
9949       break;
9950     }
9951
9952     // Check if all of the extends are ANY_EXTENDs.
9953     AllAnyExt &= AnyExt;
9954   }
9955
9956   // In order to have valid types, all of the inputs must be extended from the
9957   // same source type and all of the inputs must be any or zero extend.
9958   // Scalar sizes must be a power of two.
9959   EVT OutScalarTy = VT.getScalarType();
9960   bool ValidTypes = SourceType != MVT::Other &&
9961                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9962                  isPowerOf2_32(SourceType.getSizeInBits());
9963
9964   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9965   // turn into a single shuffle instruction.
9966   if (!ValidTypes)
9967     return SDValue();
9968
9969   bool isLE = TLI.isLittleEndian();
9970   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9971   assert(ElemRatio > 1 && "Invalid element size ratio");
9972   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9973                                DAG.getConstant(0, SourceType);
9974
9975   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9976   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9977
9978   // Populate the new build_vector
9979   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9980     SDValue Cast = N->getOperand(i);
9981     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9982             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9983             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9984     SDValue In;
9985     if (Cast.getOpcode() == ISD::UNDEF)
9986       In = DAG.getUNDEF(SourceType);
9987     else
9988       In = Cast->getOperand(0);
9989     unsigned Index = isLE ? (i * ElemRatio) :
9990                             (i * ElemRatio + (ElemRatio - 1));
9991
9992     assert(Index < Ops.size() && "Invalid index");
9993     Ops[Index] = In;
9994   }
9995
9996   // The type of the new BUILD_VECTOR node.
9997   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9998   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9999          "Invalid vector size");
10000   // Check if the new vector type is legal.
10001   if (!isTypeLegal(VecVT)) return SDValue();
10002
10003   // Make the new BUILD_VECTOR.
10004   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10005
10006   // The new BUILD_VECTOR node has the potential to be further optimized.
10007   AddToWorkList(BV.getNode());
10008   // Bitcast to the desired type.
10009   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10010 }
10011
10012 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10013   EVT VT = N->getValueType(0);
10014
10015   unsigned NumInScalars = N->getNumOperands();
10016   SDLoc dl(N);
10017
10018   EVT SrcVT = MVT::Other;
10019   unsigned Opcode = ISD::DELETED_NODE;
10020   unsigned NumDefs = 0;
10021
10022   for (unsigned i = 0; i != NumInScalars; ++i) {
10023     SDValue In = N->getOperand(i);
10024     unsigned Opc = In.getOpcode();
10025
10026     if (Opc == ISD::UNDEF)
10027       continue;
10028
10029     // If all scalar values are floats and converted from integers.
10030     if (Opcode == ISD::DELETED_NODE &&
10031         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10032       Opcode = Opc;
10033     }
10034
10035     if (Opc != Opcode)
10036       return SDValue();
10037
10038     EVT InVT = In.getOperand(0).getValueType();
10039
10040     // If all scalar values are typed differently, bail out. It's chosen to
10041     // simplify BUILD_VECTOR of integer types.
10042     if (SrcVT == MVT::Other)
10043       SrcVT = InVT;
10044     if (SrcVT != InVT)
10045       return SDValue();
10046     NumDefs++;
10047   }
10048
10049   // If the vector has just one element defined, it's not worth to fold it into
10050   // a vectorized one.
10051   if (NumDefs < 2)
10052     return SDValue();
10053
10054   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10055          && "Should only handle conversion from integer to float.");
10056   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10057
10058   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10059
10060   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10061     return SDValue();
10062
10063   SmallVector<SDValue, 8> Opnds;
10064   for (unsigned i = 0; i != NumInScalars; ++i) {
10065     SDValue In = N->getOperand(i);
10066
10067     if (In.getOpcode() == ISD::UNDEF)
10068       Opnds.push_back(DAG.getUNDEF(SrcVT));
10069     else
10070       Opnds.push_back(In.getOperand(0));
10071   }
10072   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10073   AddToWorkList(BV.getNode());
10074
10075   return DAG.getNode(Opcode, dl, VT, BV);
10076 }
10077
10078 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10079   unsigned NumInScalars = N->getNumOperands();
10080   SDLoc dl(N);
10081   EVT VT = N->getValueType(0);
10082
10083   // A vector built entirely of undefs is undef.
10084   if (ISD::allOperandsUndef(N))
10085     return DAG.getUNDEF(VT);
10086
10087   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10088   if (V.getNode())
10089     return V;
10090
10091   V = reduceBuildVecConvertToConvertBuildVec(N);
10092   if (V.getNode())
10093     return V;
10094
10095   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10096   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10097   // at most two distinct vectors, turn this into a shuffle node.
10098
10099   // May only combine to shuffle after legalize if shuffle is legal.
10100   if (LegalOperations &&
10101       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10102     return SDValue();
10103
10104   SDValue VecIn1, VecIn2;
10105   for (unsigned i = 0; i != NumInScalars; ++i) {
10106     // Ignore undef inputs.
10107     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10108
10109     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10110     // constant index, bail out.
10111     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10112         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10113       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10114       break;
10115     }
10116
10117     // We allow up to two distinct input vectors.
10118     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10119     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10120       continue;
10121
10122     if (!VecIn1.getNode()) {
10123       VecIn1 = ExtractedFromVec;
10124     } else if (!VecIn2.getNode()) {
10125       VecIn2 = ExtractedFromVec;
10126     } else {
10127       // Too many inputs.
10128       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10129       break;
10130     }
10131   }
10132
10133     // If everything is good, we can make a shuffle operation.
10134   if (VecIn1.getNode()) {
10135     SmallVector<int, 8> Mask;
10136     for (unsigned i = 0; i != NumInScalars; ++i) {
10137       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10138         Mask.push_back(-1);
10139         continue;
10140       }
10141
10142       // If extracting from the first vector, just use the index directly.
10143       SDValue Extract = N->getOperand(i);
10144       SDValue ExtVal = Extract.getOperand(1);
10145       if (Extract.getOperand(0) == VecIn1) {
10146         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10147         if (ExtIndex > VT.getVectorNumElements())
10148           return SDValue();
10149
10150         Mask.push_back(ExtIndex);
10151         continue;
10152       }
10153
10154       // Otherwise, use InIdx + VecSize
10155       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10156       Mask.push_back(Idx+NumInScalars);
10157     }
10158
10159     // We can't generate a shuffle node with mismatched input and output types.
10160     // Attempt to transform a single input vector to the correct type.
10161     if ((VT != VecIn1.getValueType())) {
10162       // We don't support shuffeling between TWO values of different types.
10163       if (VecIn2.getNode())
10164         return SDValue();
10165
10166       // We only support widening of vectors which are half the size of the
10167       // output registers. For example XMM->YMM widening on X86 with AVX.
10168       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10169         return SDValue();
10170
10171       // If the input vector type has a different base type to the output
10172       // vector type, bail out.
10173       if (VecIn1.getValueType().getVectorElementType() !=
10174           VT.getVectorElementType())
10175         return SDValue();
10176
10177       // Widen the input vector by adding undef values.
10178       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10179                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10180     }
10181
10182     // If VecIn2 is unused then change it to undef.
10183     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10184
10185     // Check that we were able to transform all incoming values to the same
10186     // type.
10187     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10188         VecIn1.getValueType() != VT)
10189           return SDValue();
10190
10191     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10192     if (!isTypeLegal(VT))
10193       return SDValue();
10194
10195     // Return the new VECTOR_SHUFFLE node.
10196     SDValue Ops[2];
10197     Ops[0] = VecIn1;
10198     Ops[1] = VecIn2;
10199     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10200   }
10201
10202   return SDValue();
10203 }
10204
10205 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10206   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10207   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10208   // inputs come from at most two distinct vectors, turn this into a shuffle
10209   // node.
10210
10211   // If we only have one input vector, we don't need to do any concatenation.
10212   if (N->getNumOperands() == 1)
10213     return N->getOperand(0);
10214
10215   // Check if all of the operands are undefs.
10216   EVT VT = N->getValueType(0);
10217   if (ISD::allOperandsUndef(N))
10218     return DAG.getUNDEF(VT);
10219
10220   // Optimize concat_vectors where one of the vectors is undef.
10221   if (N->getNumOperands() == 2 &&
10222       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10223     SDValue In = N->getOperand(0);
10224     assert(In.getValueType().isVector() && "Must concat vectors");
10225
10226     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10227     if (In->getOpcode() == ISD::BITCAST &&
10228         !In->getOperand(0)->getValueType(0).isVector()) {
10229       SDValue Scalar = In->getOperand(0);
10230       EVT SclTy = Scalar->getValueType(0);
10231
10232       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10233         return SDValue();
10234
10235       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10236                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10237       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10238         return SDValue();
10239
10240       SDLoc dl = SDLoc(N);
10241       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10242       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10243     }
10244   }
10245
10246   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10247   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10248   if (N->getNumOperands() == 2 &&
10249       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10250       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10251     EVT VT = N->getValueType(0);
10252     SDValue N0 = N->getOperand(0);
10253     SDValue N1 = N->getOperand(1);
10254     SmallVector<SDValue, 8> Opnds;
10255     unsigned BuildVecNumElts =  N0.getNumOperands();
10256
10257     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10258       Opnds.push_back(N0.getOperand(i));
10259     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10260       Opnds.push_back(N1.getOperand(i));
10261
10262     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10263   }
10264
10265   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10266   // nodes often generate nop CONCAT_VECTOR nodes.
10267   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10268   // place the incoming vectors at the exact same location.
10269   SDValue SingleSource = SDValue();
10270   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10271
10272   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10273     SDValue Op = N->getOperand(i);
10274
10275     if (Op.getOpcode() == ISD::UNDEF)
10276       continue;
10277
10278     // Check if this is the identity extract:
10279     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10280       return SDValue();
10281
10282     // Find the single incoming vector for the extract_subvector.
10283     if (SingleSource.getNode()) {
10284       if (Op.getOperand(0) != SingleSource)
10285         return SDValue();
10286     } else {
10287       SingleSource = Op.getOperand(0);
10288
10289       // Check the source type is the same as the type of the result.
10290       // If not, this concat may extend the vector, so we can not
10291       // optimize it away.
10292       if (SingleSource.getValueType() != N->getValueType(0))
10293         return SDValue();
10294     }
10295
10296     unsigned IdentityIndex = i * PartNumElem;
10297     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10298     // The extract index must be constant.
10299     if (!CS)
10300       return SDValue();
10301
10302     // Check that we are reading from the identity index.
10303     if (CS->getZExtValue() != IdentityIndex)
10304       return SDValue();
10305   }
10306
10307   if (SingleSource.getNode())
10308     return SingleSource;
10309
10310   return SDValue();
10311 }
10312
10313 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10314   EVT NVT = N->getValueType(0);
10315   SDValue V = N->getOperand(0);
10316
10317   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10318     // Combine:
10319     //    (extract_subvec (concat V1, V2, ...), i)
10320     // Into:
10321     //    Vi if possible
10322     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10323     // type.
10324     if (V->getOperand(0).getValueType() != NVT)
10325       return SDValue();
10326     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10327     unsigned NumElems = NVT.getVectorNumElements();
10328     assert((Idx % NumElems) == 0 &&
10329            "IDX in concat is not a multiple of the result vector length.");
10330     return V->getOperand(Idx / NumElems);
10331   }
10332
10333   // Skip bitcasting
10334   if (V->getOpcode() == ISD::BITCAST)
10335     V = V.getOperand(0);
10336
10337   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10338     SDLoc dl(N);
10339     // Handle only simple case where vector being inserted and vector
10340     // being extracted are of same type, and are half size of larger vectors.
10341     EVT BigVT = V->getOperand(0).getValueType();
10342     EVT SmallVT = V->getOperand(1).getValueType();
10343     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10344       return SDValue();
10345
10346     // Only handle cases where both indexes are constants with the same type.
10347     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10348     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10349
10350     if (InsIdx && ExtIdx &&
10351         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10352         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10353       // Combine:
10354       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10355       // Into:
10356       //    indices are equal or bit offsets are equal => V1
10357       //    otherwise => (extract_subvec V1, ExtIdx)
10358       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10359           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10360         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10361       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10362                          DAG.getNode(ISD::BITCAST, dl,
10363                                      N->getOperand(0).getValueType(),
10364                                      V->getOperand(0)), N->getOperand(1));
10365     }
10366   }
10367
10368   return SDValue();
10369 }
10370
10371 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10372 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10373   EVT VT = N->getValueType(0);
10374   unsigned NumElts = VT.getVectorNumElements();
10375
10376   SDValue N0 = N->getOperand(0);
10377   SDValue N1 = N->getOperand(1);
10378   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10379
10380   SmallVector<SDValue, 4> Ops;
10381   EVT ConcatVT = N0.getOperand(0).getValueType();
10382   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10383   unsigned NumConcats = NumElts / NumElemsPerConcat;
10384
10385   // Look at every vector that's inserted. We're looking for exact
10386   // subvector-sized copies from a concatenated vector
10387   for (unsigned I = 0; I != NumConcats; ++I) {
10388     // Make sure we're dealing with a copy.
10389     unsigned Begin = I * NumElemsPerConcat;
10390     bool AllUndef = true, NoUndef = true;
10391     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10392       if (SVN->getMaskElt(J) >= 0)
10393         AllUndef = false;
10394       else
10395         NoUndef = false;
10396     }
10397
10398     if (NoUndef) {
10399       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10400         return SDValue();
10401
10402       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10403         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10404           return SDValue();
10405
10406       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10407       if (FirstElt < N0.getNumOperands())
10408         Ops.push_back(N0.getOperand(FirstElt));
10409       else
10410         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10411
10412     } else if (AllUndef) {
10413       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10414     } else { // Mixed with general masks and undefs, can't do optimization.
10415       return SDValue();
10416     }
10417   }
10418
10419   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10420 }
10421
10422 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10423   EVT VT = N->getValueType(0);
10424   unsigned NumElts = VT.getVectorNumElements();
10425
10426   SDValue N0 = N->getOperand(0);
10427   SDValue N1 = N->getOperand(1);
10428
10429   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10430
10431   // Canonicalize shuffle undef, undef -> undef
10432   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10433     return DAG.getUNDEF(VT);
10434
10435   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10436
10437   // Canonicalize shuffle v, v -> v, undef
10438   if (N0 == N1) {
10439     SmallVector<int, 8> NewMask;
10440     for (unsigned i = 0; i != NumElts; ++i) {
10441       int Idx = SVN->getMaskElt(i);
10442       if (Idx >= (int)NumElts) Idx -= NumElts;
10443       NewMask.push_back(Idx);
10444     }
10445     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10446                                 &NewMask[0]);
10447   }
10448
10449   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10450   if (N0.getOpcode() == ISD::UNDEF) {
10451     SmallVector<int, 8> NewMask;
10452     for (unsigned i = 0; i != NumElts; ++i) {
10453       int Idx = SVN->getMaskElt(i);
10454       if (Idx >= 0) {
10455         if (Idx >= (int)NumElts)
10456           Idx -= NumElts;
10457         else
10458           Idx = -1; // remove reference to lhs
10459       }
10460       NewMask.push_back(Idx);
10461     }
10462     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10463                                 &NewMask[0]);
10464   }
10465
10466   // Remove references to rhs if it is undef
10467   if (N1.getOpcode() == ISD::UNDEF) {
10468     bool Changed = false;
10469     SmallVector<int, 8> NewMask;
10470     for (unsigned i = 0; i != NumElts; ++i) {
10471       int Idx = SVN->getMaskElt(i);
10472       if (Idx >= (int)NumElts) {
10473         Idx = -1;
10474         Changed = true;
10475       }
10476       NewMask.push_back(Idx);
10477     }
10478     if (Changed)
10479       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10480   }
10481
10482   // If it is a splat, check if the argument vector is another splat or a
10483   // build_vector with all scalar elements the same.
10484   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10485     SDNode *V = N0.getNode();
10486
10487     // If this is a bit convert that changes the element type of the vector but
10488     // not the number of vector elements, look through it.  Be careful not to
10489     // look though conversions that change things like v4f32 to v2f64.
10490     if (V->getOpcode() == ISD::BITCAST) {
10491       SDValue ConvInput = V->getOperand(0);
10492       if (ConvInput.getValueType().isVector() &&
10493           ConvInput.getValueType().getVectorNumElements() == NumElts)
10494         V = ConvInput.getNode();
10495     }
10496
10497     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10498       assert(V->getNumOperands() == NumElts &&
10499              "BUILD_VECTOR has wrong number of operands");
10500       SDValue Base;
10501       bool AllSame = true;
10502       for (unsigned i = 0; i != NumElts; ++i) {
10503         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10504           Base = V->getOperand(i);
10505           break;
10506         }
10507       }
10508       // Splat of <u, u, u, u>, return <u, u, u, u>
10509       if (!Base.getNode())
10510         return N0;
10511       for (unsigned i = 0; i != NumElts; ++i) {
10512         if (V->getOperand(i) != Base) {
10513           AllSame = false;
10514           break;
10515         }
10516       }
10517       // Splat of <x, x, x, x>, return <x, x, x, x>
10518       if (AllSame)
10519         return N0;
10520     }
10521   }
10522
10523   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10524       Level < AfterLegalizeVectorOps &&
10525       (N1.getOpcode() == ISD::UNDEF ||
10526       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10527        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10528     SDValue V = partitionShuffleOfConcats(N, DAG);
10529
10530     if (V.getNode())
10531       return V;
10532   }
10533
10534   // If this shuffle node is simply a swizzle of another shuffle node,
10535   // and it reverses the swizzle of the previous shuffle then we can
10536   // optimize shuffle(shuffle(x, undef), undef) -> x.
10537   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10538       N1.getOpcode() == ISD::UNDEF) {
10539
10540     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10541
10542     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10543     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10544       return SDValue();
10545
10546     // The incoming shuffle must be of the same type as the result of the
10547     // current shuffle.
10548     assert(OtherSV->getOperand(0).getValueType() == VT &&
10549            "Shuffle types don't match");
10550
10551     for (unsigned i = 0; i != NumElts; ++i) {
10552       int Idx = SVN->getMaskElt(i);
10553       assert(Idx < (int)NumElts && "Index references undef operand");
10554       // Next, this index comes from the first value, which is the incoming
10555       // shuffle. Adopt the incoming index.
10556       if (Idx >= 0)
10557         Idx = OtherSV->getMaskElt(Idx);
10558
10559       // The combined shuffle must map each index to itself.
10560       if (Idx >= 0 && (unsigned)Idx != i)
10561         return SDValue();
10562     }
10563
10564     return OtherSV->getOperand(0);
10565   }
10566
10567   return SDValue();
10568 }
10569
10570 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10571   SDValue N0 = N->getOperand(0);
10572   SDValue N2 = N->getOperand(2);
10573
10574   // If the input vector is a concatenation, and the insert replaces
10575   // one of the halves, we can optimize into a single concat_vectors.
10576   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10577       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10578     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10579     EVT VT = N->getValueType(0);
10580
10581     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10582     // (concat_vectors Z, Y)
10583     if (InsIdx == 0)
10584       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10585                          N->getOperand(1), N0.getOperand(1));
10586
10587     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10588     // (concat_vectors X, Z)
10589     if (InsIdx == VT.getVectorNumElements()/2)
10590       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10591                          N0.getOperand(0), N->getOperand(1));
10592   }
10593
10594   return SDValue();
10595 }
10596
10597 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10598 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10599 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10600 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10601 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10602   EVT VT = N->getValueType(0);
10603   SDLoc dl(N);
10604   SDValue LHS = N->getOperand(0);
10605   SDValue RHS = N->getOperand(1);
10606   if (N->getOpcode() == ISD::AND) {
10607     if (RHS.getOpcode() == ISD::BITCAST)
10608       RHS = RHS.getOperand(0);
10609     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10610       SmallVector<int, 8> Indices;
10611       unsigned NumElts = RHS.getNumOperands();
10612       for (unsigned i = 0; i != NumElts; ++i) {
10613         SDValue Elt = RHS.getOperand(i);
10614         if (!isa<ConstantSDNode>(Elt))
10615           return SDValue();
10616
10617         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10618           Indices.push_back(i);
10619         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10620           Indices.push_back(NumElts);
10621         else
10622           return SDValue();
10623       }
10624
10625       // Let's see if the target supports this vector_shuffle.
10626       EVT RVT = RHS.getValueType();
10627       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10628         return SDValue();
10629
10630       // Return the new VECTOR_SHUFFLE node.
10631       EVT EltVT = RVT.getVectorElementType();
10632       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10633                                      DAG.getConstant(0, EltVT));
10634       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10635       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10636       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10637       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10638     }
10639   }
10640
10641   return SDValue();
10642 }
10643
10644 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10645 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10646   assert(N->getValueType(0).isVector() &&
10647          "SimplifyVBinOp only works on vectors!");
10648
10649   SDValue LHS = N->getOperand(0);
10650   SDValue RHS = N->getOperand(1);
10651   SDValue Shuffle = XformToShuffleWithZero(N);
10652   if (Shuffle.getNode()) return Shuffle;
10653
10654   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10655   // this operation.
10656   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10657       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10658     // Check if both vectors are constants. If not bail out.
10659     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10660           cast<BuildVectorSDNode>(RHS)->isConstant()))
10661       return SDValue();
10662
10663     SmallVector<SDValue, 8> Ops;
10664     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10665       SDValue LHSOp = LHS.getOperand(i);
10666       SDValue RHSOp = RHS.getOperand(i);
10667
10668       // Can't fold divide by zero.
10669       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10670           N->getOpcode() == ISD::FDIV) {
10671         if ((RHSOp.getOpcode() == ISD::Constant &&
10672              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10673             (RHSOp.getOpcode() == ISD::ConstantFP &&
10674              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10675           break;
10676       }
10677
10678       EVT VT = LHSOp.getValueType();
10679       EVT RVT = RHSOp.getValueType();
10680       if (RVT != VT) {
10681         // Integer BUILD_VECTOR operands may have types larger than the element
10682         // size (e.g., when the element type is not legal).  Prior to type
10683         // legalization, the types may not match between the two BUILD_VECTORS.
10684         // Truncate one of the operands to make them match.
10685         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10686           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10687         } else {
10688           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10689           VT = RVT;
10690         }
10691       }
10692       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10693                                    LHSOp, RHSOp);
10694       if (FoldOp.getOpcode() != ISD::UNDEF &&
10695           FoldOp.getOpcode() != ISD::Constant &&
10696           FoldOp.getOpcode() != ISD::ConstantFP)
10697         break;
10698       Ops.push_back(FoldOp);
10699       AddToWorkList(FoldOp.getNode());
10700     }
10701
10702     if (Ops.size() == LHS.getNumOperands())
10703       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10704   }
10705
10706   return SDValue();
10707 }
10708
10709 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10710 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10711   assert(N->getValueType(0).isVector() &&
10712          "SimplifyVUnaryOp only works on vectors!");
10713
10714   SDValue N0 = N->getOperand(0);
10715
10716   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10717     return SDValue();
10718
10719   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10720   SmallVector<SDValue, 8> Ops;
10721   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10722     SDValue Op = N0.getOperand(i);
10723     if (Op.getOpcode() != ISD::UNDEF &&
10724         Op.getOpcode() != ISD::ConstantFP)
10725       break;
10726     EVT EltVT = Op.getValueType();
10727     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10728     if (FoldOp.getOpcode() != ISD::UNDEF &&
10729         FoldOp.getOpcode() != ISD::ConstantFP)
10730       break;
10731     Ops.push_back(FoldOp);
10732     AddToWorkList(FoldOp.getNode());
10733   }
10734
10735   if (Ops.size() != N0.getNumOperands())
10736     return SDValue();
10737
10738   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10739 }
10740
10741 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10742                                     SDValue N1, SDValue N2){
10743   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10744
10745   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10746                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10747
10748   // If we got a simplified select_cc node back from SimplifySelectCC, then
10749   // break it down into a new SETCC node, and a new SELECT node, and then return
10750   // the SELECT node, since we were called with a SELECT node.
10751   if (SCC.getNode()) {
10752     // Check to see if we got a select_cc back (to turn into setcc/select).
10753     // Otherwise, just return whatever node we got back, like fabs.
10754     if (SCC.getOpcode() == ISD::SELECT_CC) {
10755       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10756                                   N0.getValueType(),
10757                                   SCC.getOperand(0), SCC.getOperand(1),
10758                                   SCC.getOperand(4));
10759       AddToWorkList(SETCC.getNode());
10760       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10761                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10762     }
10763
10764     return SCC;
10765   }
10766   return SDValue();
10767 }
10768
10769 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10770 /// are the two values being selected between, see if we can simplify the
10771 /// select.  Callers of this should assume that TheSelect is deleted if this
10772 /// returns true.  As such, they should return the appropriate thing (e.g. the
10773 /// node) back to the top-level of the DAG combiner loop to avoid it being
10774 /// looked at.
10775 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10776                                     SDValue RHS) {
10777
10778   // Cannot simplify select with vector condition
10779   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10780
10781   // If this is a select from two identical things, try to pull the operation
10782   // through the select.
10783   if (LHS.getOpcode() != RHS.getOpcode() ||
10784       !LHS.hasOneUse() || !RHS.hasOneUse())
10785     return false;
10786
10787   // If this is a load and the token chain is identical, replace the select
10788   // of two loads with a load through a select of the address to load from.
10789   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10790   // constants have been dropped into the constant pool.
10791   if (LHS.getOpcode() == ISD::LOAD) {
10792     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10793     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10794
10795     // Token chains must be identical.
10796     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10797         // Do not let this transformation reduce the number of volatile loads.
10798         LLD->isVolatile() || RLD->isVolatile() ||
10799         // If this is an EXTLOAD, the VT's must match.
10800         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10801         // If this is an EXTLOAD, the kind of extension must match.
10802         (LLD->getExtensionType() != RLD->getExtensionType() &&
10803          // The only exception is if one of the extensions is anyext.
10804          LLD->getExtensionType() != ISD::EXTLOAD &&
10805          RLD->getExtensionType() != ISD::EXTLOAD) ||
10806         // FIXME: this discards src value information.  This is
10807         // over-conservative. It would be beneficial to be able to remember
10808         // both potential memory locations.  Since we are discarding
10809         // src value info, don't do the transformation if the memory
10810         // locations are not in the default address space.
10811         LLD->getPointerInfo().getAddrSpace() != 0 ||
10812         RLD->getPointerInfo().getAddrSpace() != 0 ||
10813         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10814                                       LLD->getBasePtr().getValueType()))
10815       return false;
10816
10817     // Check that the select condition doesn't reach either load.  If so,
10818     // folding this will induce a cycle into the DAG.  If not, this is safe to
10819     // xform, so create a select of the addresses.
10820     SDValue Addr;
10821     if (TheSelect->getOpcode() == ISD::SELECT) {
10822       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10823       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10824           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10825         return false;
10826       // The loads must not depend on one another.
10827       if (LLD->isPredecessorOf(RLD) ||
10828           RLD->isPredecessorOf(LLD))
10829         return false;
10830       Addr = DAG.getSelect(SDLoc(TheSelect),
10831                            LLD->getBasePtr().getValueType(),
10832                            TheSelect->getOperand(0), LLD->getBasePtr(),
10833                            RLD->getBasePtr());
10834     } else {  // Otherwise SELECT_CC
10835       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10836       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10837
10838       if ((LLD->hasAnyUseOfValue(1) &&
10839            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10840           (RLD->hasAnyUseOfValue(1) &&
10841            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10842         return false;
10843
10844       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10845                          LLD->getBasePtr().getValueType(),
10846                          TheSelect->getOperand(0),
10847                          TheSelect->getOperand(1),
10848                          LLD->getBasePtr(), RLD->getBasePtr(),
10849                          TheSelect->getOperand(4));
10850     }
10851
10852     SDValue Load;
10853     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10854       Load = DAG.getLoad(TheSelect->getValueType(0),
10855                          SDLoc(TheSelect),
10856                          // FIXME: Discards pointer and TBAA info.
10857                          LLD->getChain(), Addr, MachinePointerInfo(),
10858                          LLD->isVolatile(), LLD->isNonTemporal(),
10859                          LLD->isInvariant(), LLD->getAlignment());
10860     } else {
10861       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10862                             RLD->getExtensionType() : LLD->getExtensionType(),
10863                             SDLoc(TheSelect),
10864                             TheSelect->getValueType(0),
10865                             // FIXME: Discards pointer and TBAA info.
10866                             LLD->getChain(), Addr, MachinePointerInfo(),
10867                             LLD->getMemoryVT(), LLD->isVolatile(),
10868                             LLD->isNonTemporal(), LLD->getAlignment());
10869     }
10870
10871     // Users of the select now use the result of the load.
10872     CombineTo(TheSelect, Load);
10873
10874     // Users of the old loads now use the new load's chain.  We know the
10875     // old-load value is dead now.
10876     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10877     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10878     return true;
10879   }
10880
10881   return false;
10882 }
10883
10884 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10885 /// where 'cond' is the comparison specified by CC.
10886 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10887                                       SDValue N2, SDValue N3,
10888                                       ISD::CondCode CC, bool NotExtCompare) {
10889   // (x ? y : y) -> y.
10890   if (N2 == N3) return N2;
10891
10892   EVT VT = N2.getValueType();
10893   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10894   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10895   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10896
10897   // Determine if the condition we're dealing with is constant
10898   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10899                               N0, N1, CC, DL, false);
10900   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10901   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10902
10903   // fold select_cc true, x, y -> x
10904   if (SCCC && !SCCC->isNullValue())
10905     return N2;
10906   // fold select_cc false, x, y -> y
10907   if (SCCC && SCCC->isNullValue())
10908     return N3;
10909
10910   // Check to see if we can simplify the select into an fabs node
10911   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10912     // Allow either -0.0 or 0.0
10913     if (CFP->getValueAPF().isZero()) {
10914       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10915       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10916           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10917           N2 == N3.getOperand(0))
10918         return DAG.getNode(ISD::FABS, DL, VT, N0);
10919
10920       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10921       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10922           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10923           N2.getOperand(0) == N3)
10924         return DAG.getNode(ISD::FABS, DL, VT, N3);
10925     }
10926   }
10927
10928   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10929   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10930   // in it.  This is a win when the constant is not otherwise available because
10931   // it replaces two constant pool loads with one.  We only do this if the FP
10932   // type is known to be legal, because if it isn't, then we are before legalize
10933   // types an we want the other legalization to happen first (e.g. to avoid
10934   // messing with soft float) and if the ConstantFP is not legal, because if
10935   // it is legal, we may not need to store the FP constant in a constant pool.
10936   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10937     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10938       if (TLI.isTypeLegal(N2.getValueType()) &&
10939           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10940                TargetLowering::Legal &&
10941            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10942            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10943           // If both constants have multiple uses, then we won't need to do an
10944           // extra load, they are likely around in registers for other users.
10945           (TV->hasOneUse() || FV->hasOneUse())) {
10946         Constant *Elts[] = {
10947           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10948           const_cast<ConstantFP*>(TV->getConstantFPValue())
10949         };
10950         Type *FPTy = Elts[0]->getType();
10951         const DataLayout &TD = *TLI.getDataLayout();
10952
10953         // Create a ConstantArray of the two constants.
10954         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10955         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10956                                             TD.getPrefTypeAlignment(FPTy));
10957         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10958
10959         // Get the offsets to the 0 and 1 element of the array so that we can
10960         // select between them.
10961         SDValue Zero = DAG.getIntPtrConstant(0);
10962         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10963         SDValue One = DAG.getIntPtrConstant(EltSize);
10964
10965         SDValue Cond = DAG.getSetCC(DL,
10966                                     getSetCCResultType(N0.getValueType()),
10967                                     N0, N1, CC);
10968         AddToWorkList(Cond.getNode());
10969         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10970                                           Cond, One, Zero);
10971         AddToWorkList(CstOffset.getNode());
10972         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10973                             CstOffset);
10974         AddToWorkList(CPIdx.getNode());
10975         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10976                            MachinePointerInfo::getConstantPool(), false,
10977                            false, false, Alignment);
10978
10979       }
10980     }
10981
10982   // Check to see if we can perform the "gzip trick", transforming
10983   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10984   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10985       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10986        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10987     EVT XType = N0.getValueType();
10988     EVT AType = N2.getValueType();
10989     if (XType.bitsGE(AType)) {
10990       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10991       // single-bit constant.
10992       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10993         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10994         ShCtV = XType.getSizeInBits()-ShCtV-1;
10995         SDValue ShCt = DAG.getConstant(ShCtV,
10996                                        getShiftAmountTy(N0.getValueType()));
10997         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10998                                     XType, N0, ShCt);
10999         AddToWorkList(Shift.getNode());
11000
11001         if (XType.bitsGT(AType)) {
11002           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11003           AddToWorkList(Shift.getNode());
11004         }
11005
11006         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11007       }
11008
11009       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11010                                   XType, N0,
11011                                   DAG.getConstant(XType.getSizeInBits()-1,
11012                                          getShiftAmountTy(N0.getValueType())));
11013       AddToWorkList(Shift.getNode());
11014
11015       if (XType.bitsGT(AType)) {
11016         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11017         AddToWorkList(Shift.getNode());
11018       }
11019
11020       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11021     }
11022   }
11023
11024   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11025   // where y is has a single bit set.
11026   // A plaintext description would be, we can turn the SELECT_CC into an AND
11027   // when the condition can be materialized as an all-ones register.  Any
11028   // single bit-test can be materialized as an all-ones register with
11029   // shift-left and shift-right-arith.
11030   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11031       N0->getValueType(0) == VT &&
11032       N1C && N1C->isNullValue() &&
11033       N2C && N2C->isNullValue()) {
11034     SDValue AndLHS = N0->getOperand(0);
11035     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11036     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11037       // Shift the tested bit over the sign bit.
11038       APInt AndMask = ConstAndRHS->getAPIntValue();
11039       SDValue ShlAmt =
11040         DAG.getConstant(AndMask.countLeadingZeros(),
11041                         getShiftAmountTy(AndLHS.getValueType()));
11042       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11043
11044       // Now arithmetic right shift it all the way over, so the result is either
11045       // all-ones, or zero.
11046       SDValue ShrAmt =
11047         DAG.getConstant(AndMask.getBitWidth()-1,
11048                         getShiftAmountTy(Shl.getValueType()));
11049       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11050
11051       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11052     }
11053   }
11054
11055   // fold select C, 16, 0 -> shl C, 4
11056   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11057     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11058       TargetLowering::ZeroOrOneBooleanContent) {
11059
11060     // If the caller doesn't want us to simplify this into a zext of a compare,
11061     // don't do it.
11062     if (NotExtCompare && N2C->getAPIntValue() == 1)
11063       return SDValue();
11064
11065     // Get a SetCC of the condition
11066     // NOTE: Don't create a SETCC if it's not legal on this target.
11067     if (!LegalOperations ||
11068         TLI.isOperationLegal(ISD::SETCC,
11069           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11070       SDValue Temp, SCC;
11071       // cast from setcc result type to select result type
11072       if (LegalTypes) {
11073         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11074                             N0, N1, CC);
11075         if (N2.getValueType().bitsLT(SCC.getValueType()))
11076           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11077                                         N2.getValueType());
11078         else
11079           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11080                              N2.getValueType(), SCC);
11081       } else {
11082         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11083         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11084                            N2.getValueType(), SCC);
11085       }
11086
11087       AddToWorkList(SCC.getNode());
11088       AddToWorkList(Temp.getNode());
11089
11090       if (N2C->getAPIntValue() == 1)
11091         return Temp;
11092
11093       // shl setcc result by log2 n2c
11094       return DAG.getNode(
11095           ISD::SHL, DL, N2.getValueType(), Temp,
11096           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11097                           getShiftAmountTy(Temp.getValueType())));
11098     }
11099   }
11100
11101   // Check to see if this is the equivalent of setcc
11102   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11103   // otherwise, go ahead with the folds.
11104   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11105     EVT XType = N0.getValueType();
11106     if (!LegalOperations ||
11107         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11108       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11109       if (Res.getValueType() != VT)
11110         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11111       return Res;
11112     }
11113
11114     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11115     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11116         (!LegalOperations ||
11117          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11118       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11119       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11120                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11121                                        getShiftAmountTy(Ctlz.getValueType())));
11122     }
11123     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11124     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11125       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11126                                   XType, DAG.getConstant(0, XType), N0);
11127       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11128       return DAG.getNode(ISD::SRL, DL, XType,
11129                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11130                          DAG.getConstant(XType.getSizeInBits()-1,
11131                                          getShiftAmountTy(XType)));
11132     }
11133     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11134     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11135       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11136                                  DAG.getConstant(XType.getSizeInBits()-1,
11137                                          getShiftAmountTy(N0.getValueType())));
11138       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11139     }
11140   }
11141
11142   // Check to see if this is an integer abs.
11143   // select_cc setg[te] X,  0,  X, -X ->
11144   // select_cc setgt    X, -1,  X, -X ->
11145   // select_cc setl[te] X,  0, -X,  X ->
11146   // select_cc setlt    X,  1, -X,  X ->
11147   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11148   if (N1C) {
11149     ConstantSDNode *SubC = nullptr;
11150     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11151          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11152         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11153       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11154     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11155               (N1C->isOne() && CC == ISD::SETLT)) &&
11156              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11157       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11158
11159     EVT XType = N0.getValueType();
11160     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11161       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11162                                   N0,
11163                                   DAG.getConstant(XType.getSizeInBits()-1,
11164                                          getShiftAmountTy(N0.getValueType())));
11165       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11166                                 XType, N0, Shift);
11167       AddToWorkList(Shift.getNode());
11168       AddToWorkList(Add.getNode());
11169       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11170     }
11171   }
11172
11173   return SDValue();
11174 }
11175
11176 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11177 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11178                                    SDValue N1, ISD::CondCode Cond,
11179                                    SDLoc DL, bool foldBooleans) {
11180   TargetLowering::DAGCombinerInfo
11181     DagCombineInfo(DAG, Level, false, this);
11182   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11183 }
11184
11185 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11186 /// return a DAG expression to select that will generate the same value by
11187 /// multiplying by a magic number.  See:
11188 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11189 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11190   const APInt *Divisor;
11191   if (N->getValueType(0).isVector()) {
11192     // Handle splat vectors.
11193     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11194     if (ConstantSDNode *C = BV->getConstantSplatValue())
11195       Divisor = &C->getAPIntValue();
11196     else
11197       return SDValue();
11198   } else {
11199     Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11200   }
11201
11202   // Avoid division by zero.
11203   if (!*Divisor)
11204     return SDValue();
11205
11206   std::vector<SDNode*> Built;
11207   SDValue S = TLI.BuildSDIV(N, *Divisor, DAG, LegalOperations, &Built);
11208
11209   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11210        ii != ee; ++ii)
11211     AddToWorkList(*ii);
11212   return S;
11213 }
11214
11215 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11216 /// return a DAG expression to select that will generate the same value by
11217 /// multiplying by a magic number.  See:
11218 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11219 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11220   const APInt *Divisor;
11221   if (N->getValueType(0).isVector()) {
11222     // Handle splat vectors.
11223     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11224     if (ConstantSDNode *C = BV->getConstantSplatValue())
11225       Divisor = &C->getAPIntValue();
11226     else
11227       return SDValue();
11228   } else {
11229     Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11230   }
11231
11232   // Avoid division by zero.
11233   if (!*Divisor)
11234     return SDValue();
11235
11236   std::vector<SDNode*> Built;
11237   SDValue S = TLI.BuildUDIV(N, *Divisor, DAG, LegalOperations, &Built);
11238
11239   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11240        ii != ee; ++ii)
11241     AddToWorkList(*ii);
11242   return S;
11243 }
11244
11245 /// FindBaseOffset - Return true if base is a frame index, which is known not
11246 // to alias with anything but itself.  Provides base object and offset as
11247 // results.
11248 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11249                            const GlobalValue *&GV, const void *&CV) {
11250   // Assume it is a primitive operation.
11251   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11252
11253   // If it's an adding a simple constant then integrate the offset.
11254   if (Base.getOpcode() == ISD::ADD) {
11255     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11256       Base = Base.getOperand(0);
11257       Offset += C->getZExtValue();
11258     }
11259   }
11260
11261   // Return the underlying GlobalValue, and update the Offset.  Return false
11262   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11263   // by multiple nodes with different offsets.
11264   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11265     GV = G->getGlobal();
11266     Offset += G->getOffset();
11267     return false;
11268   }
11269
11270   // Return the underlying Constant value, and update the Offset.  Return false
11271   // for ConstantSDNodes since the same constant pool entry may be represented
11272   // by multiple nodes with different offsets.
11273   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11274     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11275                                          : (const void *)C->getConstVal();
11276     Offset += C->getOffset();
11277     return false;
11278   }
11279   // If it's any of the following then it can't alias with anything but itself.
11280   return isa<FrameIndexSDNode>(Base);
11281 }
11282
11283 /// isAlias - Return true if there is any possibility that the two addresses
11284 /// overlap.
11285 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11286   // If they are the same then they must be aliases.
11287   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11288
11289   // If they are both volatile then they cannot be reordered.
11290   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11291
11292   // Gather base node and offset information.
11293   SDValue Base1, Base2;
11294   int64_t Offset1, Offset2;
11295   const GlobalValue *GV1, *GV2;
11296   const void *CV1, *CV2;
11297   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11298                                       Base1, Offset1, GV1, CV1);
11299   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11300                                       Base2, Offset2, GV2, CV2);
11301
11302   // If they have a same base address then check to see if they overlap.
11303   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11304     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11305              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11306
11307   // It is possible for different frame indices to alias each other, mostly
11308   // when tail call optimization reuses return address slots for arguments.
11309   // To catch this case, look up the actual index of frame indices to compute
11310   // the real alias relationship.
11311   if (isFrameIndex1 && isFrameIndex2) {
11312     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11313     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11314     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11315     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11316              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11317   }
11318
11319   // Otherwise, if we know what the bases are, and they aren't identical, then
11320   // we know they cannot alias.
11321   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11322     return false;
11323
11324   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11325   // compared to the size and offset of the access, we may be able to prove they
11326   // do not alias.  This check is conservative for now to catch cases created by
11327   // splitting vector types.
11328   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11329       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11330       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11331        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11332       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11333     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11334     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11335
11336     // There is no overlap between these relatively aligned accesses of similar
11337     // size, return no alias.
11338     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11339         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11340       return false;
11341   }
11342
11343   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11344     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11345 #ifndef NDEBUG
11346   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11347       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11348     UseAA = false;
11349 #endif
11350   if (UseAA &&
11351       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11352     // Use alias analysis information.
11353     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11354                                  Op1->getSrcValueOffset());
11355     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11356         Op0->getSrcValueOffset() - MinOffset;
11357     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11358         Op1->getSrcValueOffset() - MinOffset;
11359     AliasAnalysis::AliasResult AAResult =
11360         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11361                                          Overlap1,
11362                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11363                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11364                                          Overlap2,
11365                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11366     if (AAResult == AliasAnalysis::NoAlias)
11367       return false;
11368   }
11369
11370   // Otherwise we have to assume they alias.
11371   return true;
11372 }
11373
11374 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11375 /// looking for aliasing nodes and adding them to the Aliases vector.
11376 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11377                                    SmallVectorImpl<SDValue> &Aliases) {
11378   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11379   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11380
11381   // Get alias information for node.
11382   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11383
11384   // Starting off.
11385   Chains.push_back(OriginalChain);
11386   unsigned Depth = 0;
11387
11388   // Look at each chain and determine if it is an alias.  If so, add it to the
11389   // aliases list.  If not, then continue up the chain looking for the next
11390   // candidate.
11391   while (!Chains.empty()) {
11392     SDValue Chain = Chains.back();
11393     Chains.pop_back();
11394
11395     // For TokenFactor nodes, look at each operand and only continue up the
11396     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11397     // find more and revert to original chain since the xform is unlikely to be
11398     // profitable.
11399     //
11400     // FIXME: The depth check could be made to return the last non-aliasing
11401     // chain we found before we hit a tokenfactor rather than the original
11402     // chain.
11403     if (Depth > 6 || Aliases.size() == 2) {
11404       Aliases.clear();
11405       Aliases.push_back(OriginalChain);
11406       return;
11407     }
11408
11409     // Don't bother if we've been before.
11410     if (!Visited.insert(Chain.getNode()))
11411       continue;
11412
11413     switch (Chain.getOpcode()) {
11414     case ISD::EntryToken:
11415       // Entry token is ideal chain operand, but handled in FindBetterChain.
11416       break;
11417
11418     case ISD::LOAD:
11419     case ISD::STORE: {
11420       // Get alias information for Chain.
11421       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11422           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11423
11424       // If chain is alias then stop here.
11425       if (!(IsLoad && IsOpLoad) &&
11426           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11427         Aliases.push_back(Chain);
11428       } else {
11429         // Look further up the chain.
11430         Chains.push_back(Chain.getOperand(0));
11431         ++Depth;
11432       }
11433       break;
11434     }
11435
11436     case ISD::TokenFactor:
11437       // We have to check each of the operands of the token factor for "small"
11438       // token factors, so we queue them up.  Adding the operands to the queue
11439       // (stack) in reverse order maintains the original order and increases the
11440       // likelihood that getNode will find a matching token factor (CSE.)
11441       if (Chain.getNumOperands() > 16) {
11442         Aliases.push_back(Chain);
11443         break;
11444       }
11445       for (unsigned n = Chain.getNumOperands(); n;)
11446         Chains.push_back(Chain.getOperand(--n));
11447       ++Depth;
11448       break;
11449
11450     default:
11451       // For all other instructions we will just have to take what we can get.
11452       Aliases.push_back(Chain);
11453       break;
11454     }
11455   }
11456
11457   // We need to be careful here to also search for aliases through the
11458   // value operand of a store, etc. Consider the following situation:
11459   //   Token1 = ...
11460   //   L1 = load Token1, %52
11461   //   S1 = store Token1, L1, %51
11462   //   L2 = load Token1, %52+8
11463   //   S2 = store Token1, L2, %51+8
11464   //   Token2 = Token(S1, S2)
11465   //   L3 = load Token2, %53
11466   //   S3 = store Token2, L3, %52
11467   //   L4 = load Token2, %53+8
11468   //   S4 = store Token2, L4, %52+8
11469   // If we search for aliases of S3 (which loads address %52), and we look
11470   // only through the chain, then we'll miss the trivial dependence on L1
11471   // (which also loads from %52). We then might change all loads and
11472   // stores to use Token1 as their chain operand, which could result in
11473   // copying %53 into %52 before copying %52 into %51 (which should
11474   // happen first).
11475   //
11476   // The problem is, however, that searching for such data dependencies
11477   // can become expensive, and the cost is not directly related to the
11478   // chain depth. Instead, we'll rule out such configurations here by
11479   // insisting that we've visited all chain users (except for users
11480   // of the original chain, which is not necessary). When doing this,
11481   // we need to look through nodes we don't care about (otherwise, things
11482   // like register copies will interfere with trivial cases).
11483
11484   SmallVector<const SDNode *, 16> Worklist;
11485   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11486        IE = Visited.end(); I != IE; ++I)
11487     if (*I != OriginalChain.getNode())
11488       Worklist.push_back(*I);
11489
11490   while (!Worklist.empty()) {
11491     const SDNode *M = Worklist.pop_back_val();
11492
11493     // We have already visited M, and want to make sure we've visited any uses
11494     // of M that we care about. For uses that we've not visisted, and don't
11495     // care about, queue them to the worklist.
11496
11497     for (SDNode::use_iterator UI = M->use_begin(),
11498          UIE = M->use_end(); UI != UIE; ++UI)
11499       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11500         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11501           // We've not visited this use, and we care about it (it could have an
11502           // ordering dependency with the original node).
11503           Aliases.clear();
11504           Aliases.push_back(OriginalChain);
11505           return;
11506         }
11507
11508         // We've not visited this use, but we don't care about it. Mark it as
11509         // visited and enqueue it to the worklist.
11510         Worklist.push_back(*UI);
11511       }
11512   }
11513 }
11514
11515 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11516 /// for a better chain (aliasing node.)
11517 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11518   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11519
11520   // Accumulate all the aliases to this node.
11521   GatherAllAliases(N, OldChain, Aliases);
11522
11523   // If no operands then chain to entry token.
11524   if (Aliases.size() == 0)
11525     return DAG.getEntryNode();
11526
11527   // If a single operand then chain to it.  We don't need to revisit it.
11528   if (Aliases.size() == 1)
11529     return Aliases[0];
11530
11531   // Construct a custom tailored token factor.
11532   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11533 }
11534
11535 // SelectionDAG::Combine - This is the entry point for the file.
11536 //
11537 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11538                            CodeGenOpt::Level OptLevel) {
11539   /// run - This is the main entry point to this class.
11540   ///
11541   DAGCombiner(*this, AA, OptLevel).Run(Level);
11542 }