Rip out X86-specific vector SDIV lowering, make the corresponding DAGCombiner transfo...
[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),
1406                            MVT::Other, &Ops[0], Ops.size());
1407     }
1408
1409     // Don't add users to work list.
1410     return CombineTo(N, Result, false);
1411   }
1412
1413   return Result;
1414 }
1415
1416 /// MERGE_VALUES can always be eliminated.
1417 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1418   WorkListRemover DeadNodes(*this);
1419   // Replacing results may cause a different MERGE_VALUES to suddenly
1420   // be CSE'd with N, and carry its uses with it. Iterate until no
1421   // uses remain, to ensure that the node can be safely deleted.
1422   // First add the users of this node to the work list so that they
1423   // can be tried again once they have new operands.
1424   AddUsersToWorkList(N);
1425   do {
1426     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1427       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1428   } while (!N->use_empty());
1429   removeFromWorkList(N);
1430   DAG.DeleteNode(N);
1431   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1432 }
1433
1434 static
1435 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1436                               SelectionDAG &DAG) {
1437   EVT VT = N0.getValueType();
1438   SDValue N00 = N0.getOperand(0);
1439   SDValue N01 = N0.getOperand(1);
1440   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1441
1442   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1443       isa<ConstantSDNode>(N00.getOperand(1))) {
1444     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1445     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1446                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1447                                  N00.getOperand(0), N01),
1448                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1449                                  N00.getOperand(1), N01));
1450     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1451   }
1452
1453   return SDValue();
1454 }
1455
1456 SDValue DAGCombiner::visitADD(SDNode *N) {
1457   SDValue N0 = N->getOperand(0);
1458   SDValue N1 = N->getOperand(1);
1459   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1460   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1461   EVT VT = N0.getValueType();
1462
1463   // fold vector ops
1464   if (VT.isVector()) {
1465     SDValue FoldedVOp = SimplifyVBinOp(N);
1466     if (FoldedVOp.getNode()) return FoldedVOp;
1467
1468     // fold (add x, 0) -> x, vector edition
1469     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1470       return N0;
1471     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1472       return N1;
1473   }
1474
1475   // fold (add x, undef) -> undef
1476   if (N0.getOpcode() == ISD::UNDEF)
1477     return N0;
1478   if (N1.getOpcode() == ISD::UNDEF)
1479     return N1;
1480   // fold (add c1, c2) -> c1+c2
1481   if (N0C && N1C)
1482     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1483   // canonicalize constant to RHS
1484   if (N0C && !N1C)
1485     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1486   // fold (add x, 0) -> x
1487   if (N1C && N1C->isNullValue())
1488     return N0;
1489   // fold (add Sym, c) -> Sym+c
1490   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1491     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1492         GA->getOpcode() == ISD::GlobalAddress)
1493       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1494                                   GA->getOffset() +
1495                                     (uint64_t)N1C->getSExtValue());
1496   // fold ((c1-A)+c2) -> (c1+c2)-A
1497   if (N1C && N0.getOpcode() == ISD::SUB)
1498     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1499       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1500                          DAG.getConstant(N1C->getAPIntValue()+
1501                                          N0C->getAPIntValue(), VT),
1502                          N0.getOperand(1));
1503   // reassociate add
1504   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1505   if (RADD.getNode())
1506     return RADD;
1507   // fold ((0-A) + B) -> B-A
1508   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1509       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1510     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1511   // fold (A + (0-B)) -> A-B
1512   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1513       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1514     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1515   // fold (A+(B-A)) -> B
1516   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1517     return N1.getOperand(0);
1518   // fold ((B-A)+A) -> B
1519   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1520     return N0.getOperand(0);
1521   // fold (A+(B-(A+C))) to (B-C)
1522   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1523       N0 == N1.getOperand(1).getOperand(0))
1524     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1525                        N1.getOperand(1).getOperand(1));
1526   // fold (A+(B-(C+A))) to (B-C)
1527   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1528       N0 == N1.getOperand(1).getOperand(1))
1529     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1530                        N1.getOperand(1).getOperand(0));
1531   // fold (A+((B-A)+or-C)) to (B+or-C)
1532   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1533       N1.getOperand(0).getOpcode() == ISD::SUB &&
1534       N0 == N1.getOperand(0).getOperand(1))
1535     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1536                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1537
1538   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1539   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1540     SDValue N00 = N0.getOperand(0);
1541     SDValue N01 = N0.getOperand(1);
1542     SDValue N10 = N1.getOperand(0);
1543     SDValue N11 = N1.getOperand(1);
1544
1545     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1546       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1547                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1548                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1549   }
1550
1551   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1552     return SDValue(N, 0);
1553
1554   // fold (a+b) -> (a|b) iff a and b share no bits.
1555   if (VT.isInteger() && !VT.isVector()) {
1556     APInt LHSZero, LHSOne;
1557     APInt RHSZero, RHSOne;
1558     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1559
1560     if (LHSZero.getBoolValue()) {
1561       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1562
1563       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1564       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1565       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1566         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1567           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1568       }
1569     }
1570   }
1571
1572   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1573   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1574     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1575     if (Result.getNode()) return Result;
1576   }
1577   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1578     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1579     if (Result.getNode()) return Result;
1580   }
1581
1582   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1583   if (N1.getOpcode() == ISD::SHL &&
1584       N1.getOperand(0).getOpcode() == ISD::SUB)
1585     if (ConstantSDNode *C =
1586           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1587       if (C->getAPIntValue() == 0)
1588         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1589                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1590                                        N1.getOperand(0).getOperand(1),
1591                                        N1.getOperand(1)));
1592   if (N0.getOpcode() == ISD::SHL &&
1593       N0.getOperand(0).getOpcode() == ISD::SUB)
1594     if (ConstantSDNode *C =
1595           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1596       if (C->getAPIntValue() == 0)
1597         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1598                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1599                                        N0.getOperand(0).getOperand(1),
1600                                        N0.getOperand(1)));
1601
1602   if (N1.getOpcode() == ISD::AND) {
1603     SDValue AndOp0 = N1.getOperand(0);
1604     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1605     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1606     unsigned DestBits = VT.getScalarType().getSizeInBits();
1607
1608     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1609     // and similar xforms where the inner op is either ~0 or 0.
1610     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1611       SDLoc DL(N);
1612       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1613     }
1614   }
1615
1616   // add (sext i1), X -> sub X, (zext i1)
1617   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1618       N0.getOperand(0).getValueType() == MVT::i1 &&
1619       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1620     SDLoc DL(N);
1621     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1622     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1623   }
1624
1625   return SDValue();
1626 }
1627
1628 SDValue DAGCombiner::visitADDC(SDNode *N) {
1629   SDValue N0 = N->getOperand(0);
1630   SDValue N1 = N->getOperand(1);
1631   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1632   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1633   EVT VT = N0.getValueType();
1634
1635   // If the flag result is dead, turn this into an ADD.
1636   if (!N->hasAnyUseOfValue(1))
1637     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1638                      DAG.getNode(ISD::CARRY_FALSE,
1639                                  SDLoc(N), MVT::Glue));
1640
1641   // canonicalize constant to RHS.
1642   if (N0C && !N1C)
1643     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1644
1645   // fold (addc x, 0) -> x + no carry out
1646   if (N1C && N1C->isNullValue())
1647     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1648                                         SDLoc(N), MVT::Glue));
1649
1650   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1651   APInt LHSZero, LHSOne;
1652   APInt RHSZero, RHSOne;
1653   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1654
1655   if (LHSZero.getBoolValue()) {
1656     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1657
1658     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1659     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1660     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1661       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1662                        DAG.getNode(ISD::CARRY_FALSE,
1663                                    SDLoc(N), MVT::Glue));
1664   }
1665
1666   return SDValue();
1667 }
1668
1669 SDValue DAGCombiner::visitADDE(SDNode *N) {
1670   SDValue N0 = N->getOperand(0);
1671   SDValue N1 = N->getOperand(1);
1672   SDValue CarryIn = N->getOperand(2);
1673   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1674   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1675
1676   // canonicalize constant to RHS
1677   if (N0C && !N1C)
1678     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1679                        N1, N0, CarryIn);
1680
1681   // fold (adde x, y, false) -> (addc x, y)
1682   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1683     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1684
1685   return SDValue();
1686 }
1687
1688 // Since it may not be valid to emit a fold to zero for vector initializers
1689 // check if we can before folding.
1690 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1691                              SelectionDAG &DAG,
1692                              bool LegalOperations, bool LegalTypes) {
1693   if (!VT.isVector())
1694     return DAG.getConstant(0, VT);
1695   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1696     return DAG.getConstant(0, VT);
1697   return SDValue();
1698 }
1699
1700 SDValue DAGCombiner::visitSUB(SDNode *N) {
1701   SDValue N0 = N->getOperand(0);
1702   SDValue N1 = N->getOperand(1);
1703   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1704   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1705   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1706     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1707   EVT VT = N0.getValueType();
1708
1709   // fold vector ops
1710   if (VT.isVector()) {
1711     SDValue FoldedVOp = SimplifyVBinOp(N);
1712     if (FoldedVOp.getNode()) return FoldedVOp;
1713
1714     // fold (sub x, 0) -> x, vector edition
1715     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1716       return N0;
1717   }
1718
1719   // fold (sub x, x) -> 0
1720   // FIXME: Refactor this and xor and other similar operations together.
1721   if (N0 == N1)
1722     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1723   // fold (sub c1, c2) -> c1-c2
1724   if (N0C && N1C)
1725     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1726   // fold (sub x, c) -> (add x, -c)
1727   if (N1C)
1728     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1729                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1730   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1731   if (N0C && N0C->isAllOnesValue())
1732     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1733   // fold A-(A-B) -> B
1734   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1735     return N1.getOperand(1);
1736   // fold (A+B)-A -> B
1737   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1738     return N0.getOperand(1);
1739   // fold (A+B)-B -> A
1740   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1741     return N0.getOperand(0);
1742   // fold C2-(A+C1) -> (C2-C1)-A
1743   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1744     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1745                                    VT);
1746     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1747                        N1.getOperand(0));
1748   }
1749   // fold ((A+(B+or-C))-B) -> A+or-C
1750   if (N0.getOpcode() == ISD::ADD &&
1751       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1752        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1753       N0.getOperand(1).getOperand(0) == N1)
1754     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1755                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1756   // fold ((A+(C+B))-B) -> A+C
1757   if (N0.getOpcode() == ISD::ADD &&
1758       N0.getOperand(1).getOpcode() == ISD::ADD &&
1759       N0.getOperand(1).getOperand(1) == N1)
1760     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1761                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1762   // fold ((A-(B-C))-C) -> A-B
1763   if (N0.getOpcode() == ISD::SUB &&
1764       N0.getOperand(1).getOpcode() == ISD::SUB &&
1765       N0.getOperand(1).getOperand(1) == N1)
1766     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1767                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1768
1769   // If either operand of a sub is undef, the result is undef
1770   if (N0.getOpcode() == ISD::UNDEF)
1771     return N0;
1772   if (N1.getOpcode() == ISD::UNDEF)
1773     return N1;
1774
1775   // If the relocation model supports it, consider symbol offsets.
1776   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1777     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1778       // fold (sub Sym, c) -> Sym-c
1779       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1780         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1781                                     GA->getOffset() -
1782                                       (uint64_t)N1C->getSExtValue());
1783       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1784       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1785         if (GA->getGlobal() == GB->getGlobal())
1786           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1787                                  VT);
1788     }
1789
1790   return SDValue();
1791 }
1792
1793 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1794   SDValue N0 = N->getOperand(0);
1795   SDValue N1 = N->getOperand(1);
1796   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1797   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1798   EVT VT = N0.getValueType();
1799
1800   // If the flag result is dead, turn this into an SUB.
1801   if (!N->hasAnyUseOfValue(1))
1802     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1803                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1804                                  MVT::Glue));
1805
1806   // fold (subc x, x) -> 0 + no borrow
1807   if (N0 == N1)
1808     return CombineTo(N, DAG.getConstant(0, VT),
1809                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1810                                  MVT::Glue));
1811
1812   // fold (subc x, 0) -> x + no borrow
1813   if (N1C && N1C->isNullValue())
1814     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1815                                         MVT::Glue));
1816
1817   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1818   if (N0C && N0C->isAllOnesValue())
1819     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1820                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1821                                  MVT::Glue));
1822
1823   return SDValue();
1824 }
1825
1826 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1827   SDValue N0 = N->getOperand(0);
1828   SDValue N1 = N->getOperand(1);
1829   SDValue CarryIn = N->getOperand(2);
1830
1831   // fold (sube x, y, false) -> (subc x, y)
1832   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1833     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1834
1835   return SDValue();
1836 }
1837
1838 SDValue DAGCombiner::visitMUL(SDNode *N) {
1839   SDValue N0 = N->getOperand(0);
1840   SDValue N1 = N->getOperand(1);
1841   EVT VT = N0.getValueType();
1842
1843   // fold (mul x, undef) -> 0
1844   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1845     return DAG.getConstant(0, VT);
1846
1847   bool N0IsConst = false;
1848   bool N1IsConst = false;
1849   APInt ConstValue0, ConstValue1;
1850   // fold vector ops
1851   if (VT.isVector()) {
1852     SDValue FoldedVOp = SimplifyVBinOp(N);
1853     if (FoldedVOp.getNode()) return FoldedVOp;
1854
1855     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1856     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1857   } else {
1858     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1859     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1860                             : APInt();
1861     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1862     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1863                             : APInt();
1864   }
1865
1866   // fold (mul c1, c2) -> c1*c2
1867   if (N0IsConst && N1IsConst)
1868     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1869
1870   // canonicalize constant to RHS
1871   if (N0IsConst && !N1IsConst)
1872     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1873   // fold (mul x, 0) -> 0
1874   if (N1IsConst && ConstValue1 == 0)
1875     return N1;
1876   // We require a splat of the entire scalar bit width for non-contiguous
1877   // bit patterns.
1878   bool IsFullSplat =
1879     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1880   // fold (mul x, 1) -> x
1881   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1882     return N0;
1883   // fold (mul x, -1) -> 0-x
1884   if (N1IsConst && ConstValue1.isAllOnesValue())
1885     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1886                        DAG.getConstant(0, VT), N0);
1887   // fold (mul x, (1 << c)) -> x << c
1888   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1889     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1890                        DAG.getConstant(ConstValue1.logBase2(),
1891                                        getShiftAmountTy(N0.getValueType())));
1892   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1893   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1894     unsigned Log2Val = (-ConstValue1).logBase2();
1895     // FIXME: If the input is something that is easily negated (e.g. a
1896     // single-use add), we should put the negate there.
1897     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1898                        DAG.getConstant(0, VT),
1899                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1900                             DAG.getConstant(Log2Val,
1901                                       getShiftAmountTy(N0.getValueType()))));
1902   }
1903
1904   APInt Val;
1905   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1906   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1907       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1908                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1909     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1910                              N1, N0.getOperand(1));
1911     AddToWorkList(C3.getNode());
1912     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913                        N0.getOperand(0), C3);
1914   }
1915
1916   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1917   // use.
1918   {
1919     SDValue Sh(nullptr,0), Y(nullptr,0);
1920     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1921     if (N0.getOpcode() == ISD::SHL &&
1922         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1924         N0.getNode()->hasOneUse()) {
1925       Sh = N0; Y = N1;
1926     } else if (N1.getOpcode() == ISD::SHL &&
1927                isa<ConstantSDNode>(N1.getOperand(1)) &&
1928                N1.getNode()->hasOneUse()) {
1929       Sh = N1; Y = N0;
1930     }
1931
1932     if (Sh.getNode()) {
1933       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1934                                 Sh.getOperand(0), Y);
1935       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1936                          Mul, Sh.getOperand(1));
1937     }
1938   }
1939
1940   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1941   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1942       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943                      isa<ConstantSDNode>(N0.getOperand(1))))
1944     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1945                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1946                                    N0.getOperand(0), N1),
1947                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1948                                    N0.getOperand(1), N1));
1949
1950   // reassociate mul
1951   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1952   if (RMUL.getNode())
1953     return RMUL;
1954
1955   return SDValue();
1956 }
1957
1958 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1959   SDValue N0 = N->getOperand(0);
1960   SDValue N1 = N->getOperand(1);
1961   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1962   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1963   EVT VT = N->getValueType(0);
1964
1965   // fold vector ops
1966   if (VT.isVector()) {
1967     SDValue FoldedVOp = SimplifyVBinOp(N);
1968     if (FoldedVOp.getNode()) return FoldedVOp;
1969   }
1970
1971   // fold (sdiv c1, c2) -> c1/c2
1972   if (N0C && N1C && !N1C->isNullValue())
1973     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1974   // fold (sdiv X, 1) -> X
1975   if (N1C && N1C->getAPIntValue() == 1LL)
1976     return N0;
1977   // fold (sdiv X, -1) -> 0-X
1978   if (N1C && N1C->isAllOnesValue())
1979     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1980                        DAG.getConstant(0, VT), N0);
1981   // If we know the sign bits of both operands are zero, strength reduce to a
1982   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1983   if (!VT.isVector()) {
1984     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1985       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1986                          N0, N1);
1987   }
1988
1989   const APInt *Divisor = nullptr;
1990   if (N1C) {
1991     Divisor = &N1C->getAPIntValue();
1992   } else if (N1.getValueType().isVector() &&
1993              N1->getOpcode() == ISD::BUILD_VECTOR) {
1994     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
1995     if (ConstantSDNode *C = BV->getConstantSplatValue())
1996       Divisor = &C->getAPIntValue();
1997   }
1998
1999   // fold (sdiv X, pow2) -> simple ops after legalize
2000   if (Divisor && !!*Divisor &&
2001       (Divisor->isPowerOf2() || (-*Divisor).isPowerOf2())) {
2002     // If dividing by powers of two is cheap, then don't perform the following
2003     // fold.
2004     if (TLI.isPow2DivCheap())
2005       return SDValue();
2006
2007     unsigned lg2 = Divisor->countTrailingZeros();
2008
2009     // Splat the sign bit into the register
2010     SDValue SGN =
2011         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2012                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2013                                     getShiftAmountTy(N0.getValueType())));
2014     AddToWorkList(SGN.getNode());
2015
2016     // Add (N0 < 0) ? abs2 - 1 : 0;
2017     SDValue SRL =
2018         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2019                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2020                                     getShiftAmountTy(SGN.getValueType())));
2021     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2022     AddToWorkList(SRL.getNode());
2023     AddToWorkList(ADD.getNode());    // Divide by pow2
2024     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2025                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2026
2027     // If we're dividing by a positive value, we're done.  Otherwise, we must
2028     // negate the result.
2029     if (Divisor->isNonNegative())
2030       return SRA;
2031
2032     AddToWorkList(SRA.getNode());
2033     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2034   }
2035
2036   // if integer divide is expensive and we satisfy the requirements, emit an
2037   // alternate sequence.
2038   if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2039     SDValue Op = BuildSDIV(N);
2040     if (Op.getNode()) return Op;
2041   }
2042
2043   // undef / X -> 0
2044   if (N0.getOpcode() == ISD::UNDEF)
2045     return DAG.getConstant(0, VT);
2046   // X / undef -> undef
2047   if (N1.getOpcode() == ISD::UNDEF)
2048     return N1;
2049
2050   return SDValue();
2051 }
2052
2053 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2054   SDValue N0 = N->getOperand(0);
2055   SDValue N1 = N->getOperand(1);
2056   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2057   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2058   EVT VT = N->getValueType(0);
2059
2060   // fold vector ops
2061   if (VT.isVector()) {
2062     SDValue FoldedVOp = SimplifyVBinOp(N);
2063     if (FoldedVOp.getNode()) return FoldedVOp;
2064   }
2065
2066   // fold (udiv c1, c2) -> c1/c2
2067   if (N0C && N1C && !N1C->isNullValue())
2068     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2069   // fold (udiv x, (1 << c)) -> x >>u c
2070   if (N1C && N1C->getAPIntValue().isPowerOf2())
2071     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2072                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2073                                        getShiftAmountTy(N0.getValueType())));
2074   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2075   if (N1.getOpcode() == ISD::SHL) {
2076     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2077       if (SHC->getAPIntValue().isPowerOf2()) {
2078         EVT ADDVT = N1.getOperand(1).getValueType();
2079         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2080                                   N1.getOperand(1),
2081                                   DAG.getConstant(SHC->getAPIntValue()
2082                                                                   .logBase2(),
2083                                                   ADDVT));
2084         AddToWorkList(Add.getNode());
2085         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2086       }
2087     }
2088   }
2089   // fold (udiv x, c) -> alternate
2090   if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2091     SDValue Op = BuildUDIV(N);
2092     if (Op.getNode()) return Op;
2093   }
2094
2095   // undef / X -> 0
2096   if (N0.getOpcode() == ISD::UNDEF)
2097     return DAG.getConstant(0, VT);
2098   // X / undef -> undef
2099   if (N1.getOpcode() == ISD::UNDEF)
2100     return N1;
2101
2102   return SDValue();
2103 }
2104
2105 SDValue DAGCombiner::visitSREM(SDNode *N) {
2106   SDValue N0 = N->getOperand(0);
2107   SDValue N1 = N->getOperand(1);
2108   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2109   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2110   EVT VT = N->getValueType(0);
2111
2112   // fold (srem c1, c2) -> c1%c2
2113   if (N0C && N1C && !N1C->isNullValue())
2114     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2115   // If we know the sign bits of both operands are zero, strength reduce to a
2116   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2117   if (!VT.isVector()) {
2118     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2119       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2120   }
2121
2122   // If X/C can be simplified by the division-by-constant logic, lower
2123   // X%C to the equivalent of X-X/C*C.
2124   if (N1C && !N1C->isNullValue()) {
2125     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2126     AddToWorkList(Div.getNode());
2127     SDValue OptimizedDiv = combine(Div.getNode());
2128     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2129       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2130                                 OptimizedDiv, N1);
2131       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2132       AddToWorkList(Mul.getNode());
2133       return Sub;
2134     }
2135   }
2136
2137   // undef % X -> 0
2138   if (N0.getOpcode() == ISD::UNDEF)
2139     return DAG.getConstant(0, VT);
2140   // X % undef -> undef
2141   if (N1.getOpcode() == ISD::UNDEF)
2142     return N1;
2143
2144   return SDValue();
2145 }
2146
2147 SDValue DAGCombiner::visitUREM(SDNode *N) {
2148   SDValue N0 = N->getOperand(0);
2149   SDValue N1 = N->getOperand(1);
2150   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2151   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2152   EVT VT = N->getValueType(0);
2153
2154   // fold (urem c1, c2) -> c1%c2
2155   if (N0C && N1C && !N1C->isNullValue())
2156     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2157   // fold (urem x, pow2) -> (and x, pow2-1)
2158   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2159     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2160                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2161   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2162   if (N1.getOpcode() == ISD::SHL) {
2163     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2164       if (SHC->getAPIntValue().isPowerOf2()) {
2165         SDValue Add =
2166           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2167                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2168                                  VT));
2169         AddToWorkList(Add.getNode());
2170         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2171       }
2172     }
2173   }
2174
2175   // If X/C can be simplified by the division-by-constant logic, lower
2176   // X%C to the equivalent of X-X/C*C.
2177   if (N1C && !N1C->isNullValue()) {
2178     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2179     AddToWorkList(Div.getNode());
2180     SDValue OptimizedDiv = combine(Div.getNode());
2181     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2182       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2183                                 OptimizedDiv, N1);
2184       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2185       AddToWorkList(Mul.getNode());
2186       return Sub;
2187     }
2188   }
2189
2190   // undef % X -> 0
2191   if (N0.getOpcode() == ISD::UNDEF)
2192     return DAG.getConstant(0, VT);
2193   // X % undef -> undef
2194   if (N1.getOpcode() == ISD::UNDEF)
2195     return N1;
2196
2197   return SDValue();
2198 }
2199
2200 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2201   SDValue N0 = N->getOperand(0);
2202   SDValue N1 = N->getOperand(1);
2203   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2204   EVT VT = N->getValueType(0);
2205   SDLoc DL(N);
2206
2207   // fold (mulhs x, 0) -> 0
2208   if (N1C && N1C->isNullValue())
2209     return N1;
2210   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2211   if (N1C && N1C->getAPIntValue() == 1)
2212     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2213                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2214                                        getShiftAmountTy(N0.getValueType())));
2215   // fold (mulhs x, undef) -> 0
2216   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2217     return DAG.getConstant(0, VT);
2218
2219   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2220   // plus a shift.
2221   if (VT.isSimple() && !VT.isVector()) {
2222     MVT Simple = VT.getSimpleVT();
2223     unsigned SimpleSize = Simple.getSizeInBits();
2224     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2225     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2226       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2227       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2228       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2229       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2230             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2231       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2232     }
2233   }
2234
2235   return SDValue();
2236 }
2237
2238 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2239   SDValue N0 = N->getOperand(0);
2240   SDValue N1 = N->getOperand(1);
2241   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2242   EVT VT = N->getValueType(0);
2243   SDLoc DL(N);
2244
2245   // fold (mulhu x, 0) -> 0
2246   if (N1C && N1C->isNullValue())
2247     return N1;
2248   // fold (mulhu x, 1) -> 0
2249   if (N1C && N1C->getAPIntValue() == 1)
2250     return DAG.getConstant(0, N0.getValueType());
2251   // fold (mulhu x, undef) -> 0
2252   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2253     return DAG.getConstant(0, VT);
2254
2255   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2256   // plus a shift.
2257   if (VT.isSimple() && !VT.isVector()) {
2258     MVT Simple = VT.getSimpleVT();
2259     unsigned SimpleSize = Simple.getSizeInBits();
2260     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2261     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2262       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2263       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2264       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2265       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2266             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2267       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2268     }
2269   }
2270
2271   return SDValue();
2272 }
2273
2274 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2275 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2276 /// that are being performed. Return true if a simplification was made.
2277 ///
2278 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2279                                                 unsigned HiOp) {
2280   // If the high half is not needed, just compute the low half.
2281   bool HiExists = N->hasAnyUseOfValue(1);
2282   if (!HiExists &&
2283       (!LegalOperations ||
2284        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2285     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2286                               N->op_begin(), N->getNumOperands());
2287     return CombineTo(N, Res, Res);
2288   }
2289
2290   // If the low half is not needed, just compute the high half.
2291   bool LoExists = N->hasAnyUseOfValue(0);
2292   if (!LoExists &&
2293       (!LegalOperations ||
2294        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2295     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2296                               N->op_begin(), N->getNumOperands());
2297     return CombineTo(N, Res, Res);
2298   }
2299
2300   // If both halves are used, return as it is.
2301   if (LoExists && HiExists)
2302     return SDValue();
2303
2304   // If the two computed results can be simplified separately, separate them.
2305   if (LoExists) {
2306     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2307                              N->op_begin(), N->getNumOperands());
2308     AddToWorkList(Lo.getNode());
2309     SDValue LoOpt = combine(Lo.getNode());
2310     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2311         (!LegalOperations ||
2312          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2313       return CombineTo(N, LoOpt, LoOpt);
2314   }
2315
2316   if (HiExists) {
2317     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2318                              N->op_begin(), N->getNumOperands());
2319     AddToWorkList(Hi.getNode());
2320     SDValue HiOpt = combine(Hi.getNode());
2321     if (HiOpt.getNode() && HiOpt != Hi &&
2322         (!LegalOperations ||
2323          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2324       return CombineTo(N, HiOpt, HiOpt);
2325   }
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2331   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2332   if (Res.getNode()) return Res;
2333
2334   EVT VT = N->getValueType(0);
2335   SDLoc DL(N);
2336
2337   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2338   // plus a shift.
2339   if (VT.isSimple() && !VT.isVector()) {
2340     MVT Simple = VT.getSimpleVT();
2341     unsigned SimpleSize = Simple.getSizeInBits();
2342     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2343     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2344       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2345       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2346       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2347       // Compute the high part as N1.
2348       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2349             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2350       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2351       // Compute the low part as N0.
2352       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2353       return CombineTo(N, Lo, Hi);
2354     }
2355   }
2356
2357   return SDValue();
2358 }
2359
2360 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2361   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2362   if (Res.getNode()) return Res;
2363
2364   EVT VT = N->getValueType(0);
2365   SDLoc DL(N);
2366
2367   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2368   // plus a shift.
2369   if (VT.isSimple() && !VT.isVector()) {
2370     MVT Simple = VT.getSimpleVT();
2371     unsigned SimpleSize = Simple.getSizeInBits();
2372     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2373     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2374       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2375       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2376       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2377       // Compute the high part as N1.
2378       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2379             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2380       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2381       // Compute the low part as N0.
2382       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2383       return CombineTo(N, Lo, Hi);
2384     }
2385   }
2386
2387   return SDValue();
2388 }
2389
2390 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2391   // (smulo x, 2) -> (saddo x, x)
2392   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2393     if (C2->getAPIntValue() == 2)
2394       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2395                          N->getOperand(0), N->getOperand(0));
2396
2397   return SDValue();
2398 }
2399
2400 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2401   // (umulo x, 2) -> (uaddo x, x)
2402   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403     if (C2->getAPIntValue() == 2)
2404       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2405                          N->getOperand(0), N->getOperand(0));
2406
2407   return SDValue();
2408 }
2409
2410 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2411   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2412   if (Res.getNode()) return Res;
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2418   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2419   if (Res.getNode()) return Res;
2420
2421   return SDValue();
2422 }
2423
2424 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2425 /// two operands of the same opcode, try to simplify it.
2426 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2427   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2428   EVT VT = N0.getValueType();
2429   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2430
2431   // Bail early if none of these transforms apply.
2432   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2433
2434   // For each of OP in AND/OR/XOR:
2435   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2436   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2437   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2438   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2439   //
2440   // do not sink logical op inside of a vector extend, since it may combine
2441   // into a vsetcc.
2442   EVT Op0VT = N0.getOperand(0).getValueType();
2443   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2444        N0.getOpcode() == ISD::SIGN_EXTEND ||
2445        // Avoid infinite looping with PromoteIntBinOp.
2446        (N0.getOpcode() == ISD::ANY_EXTEND &&
2447         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2448        (N0.getOpcode() == ISD::TRUNCATE &&
2449         (!TLI.isZExtFree(VT, Op0VT) ||
2450          !TLI.isTruncateFree(Op0VT, VT)) &&
2451         TLI.isTypeLegal(Op0VT))) &&
2452       !VT.isVector() &&
2453       Op0VT == N1.getOperand(0).getValueType() &&
2454       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2455     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2456                                  N0.getOperand(0).getValueType(),
2457                                  N0.getOperand(0), N1.getOperand(0));
2458     AddToWorkList(ORNode.getNode());
2459     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2460   }
2461
2462   // For each of OP in SHL/SRL/SRA/AND...
2463   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2464   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2465   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2466   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2467        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2468       N0.getOperand(1) == N1.getOperand(1)) {
2469     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2470                                  N0.getOperand(0).getValueType(),
2471                                  N0.getOperand(0), N1.getOperand(0));
2472     AddToWorkList(ORNode.getNode());
2473     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2474                        ORNode, N0.getOperand(1));
2475   }
2476
2477   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2478   // Only perform this optimization after type legalization and before
2479   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2480   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2481   // we don't want to undo this promotion.
2482   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2483   // on scalars.
2484   if ((N0.getOpcode() == ISD::BITCAST ||
2485        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2486       Level == AfterLegalizeTypes) {
2487     SDValue In0 = N0.getOperand(0);
2488     SDValue In1 = N1.getOperand(0);
2489     EVT In0Ty = In0.getValueType();
2490     EVT In1Ty = In1.getValueType();
2491     SDLoc DL(N);
2492     // If both incoming values are integers, and the original types are the
2493     // same.
2494     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2495       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2496       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2497       AddToWorkList(Op.getNode());
2498       return BC;
2499     }
2500   }
2501
2502   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2503   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2504   // If both shuffles use the same mask, and both shuffle within a single
2505   // vector, then it is worthwhile to move the swizzle after the operation.
2506   // The type-legalizer generates this pattern when loading illegal
2507   // vector types from memory. In many cases this allows additional shuffle
2508   // optimizations.
2509   // There are other cases where moving the shuffle after the xor/and/or
2510   // is profitable even if shuffles don't perform a swizzle.
2511   // If both shuffles use the same mask, and both shuffles have the same first
2512   // or second operand, then it might still be profitable to move the shuffle
2513   // after the xor/and/or operation.
2514   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2515     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2516     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2517
2518     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2519            "Inputs to shuffles are not the same type");
2520  
2521     // Check that both shuffles use the same mask. The masks are known to be of
2522     // the same length because the result vector type is the same.
2523     // Check also that shuffles have only one use to avoid introducing extra
2524     // instructions.
2525     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2526         SVN0->getMask().equals(SVN1->getMask())) {
2527       SDValue ShOp = N0->getOperand(1);
2528
2529       // Don't try to fold this node if it requires introducing a
2530       // build vector of all zeros that might be illegal at this stage.
2531       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2532         if (!LegalTypes)
2533           ShOp = DAG.getConstant(0, VT);
2534         else
2535           ShOp = SDValue();
2536       }
2537
2538       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2539       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2540       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2541       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2542         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2543                                       N0->getOperand(0), N1->getOperand(0));
2544         AddToWorkList(NewNode.getNode());
2545         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2546                                     &SVN0->getMask()[0]);
2547       }
2548
2549       // Don't try to fold this node if it requires introducing a
2550       // build vector of all zeros that might be illegal at this stage.
2551       ShOp = N0->getOperand(0);
2552       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2553         if (!LegalTypes)
2554           ShOp = DAG.getConstant(0, VT);
2555         else
2556           ShOp = SDValue();
2557       }
2558
2559       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2560       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2561       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2562       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2563         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2564                                       N0->getOperand(1), N1->getOperand(1));
2565         AddToWorkList(NewNode.getNode());
2566         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2567                                     &SVN0->getMask()[0]);
2568       }
2569     }
2570   }
2571
2572   return SDValue();
2573 }
2574
2575 SDValue DAGCombiner::visitAND(SDNode *N) {
2576   SDValue N0 = N->getOperand(0);
2577   SDValue N1 = N->getOperand(1);
2578   SDValue LL, LR, RL, RR, CC0, CC1;
2579   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2580   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2581   EVT VT = N1.getValueType();
2582   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2583
2584   // fold vector ops
2585   if (VT.isVector()) {
2586     SDValue FoldedVOp = SimplifyVBinOp(N);
2587     if (FoldedVOp.getNode()) return FoldedVOp;
2588
2589     // fold (and x, 0) -> 0, vector edition
2590     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2591       return N0;
2592     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2593       return N1;
2594
2595     // fold (and x, -1) -> x, vector edition
2596     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2597       return N1;
2598     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2599       return N0;
2600   }
2601
2602   // fold (and x, undef) -> 0
2603   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2604     return DAG.getConstant(0, VT);
2605   // fold (and c1, c2) -> c1&c2
2606   if (N0C && N1C)
2607     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2608   // canonicalize constant to RHS
2609   if (N0C && !N1C)
2610     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2611   // fold (and x, -1) -> x
2612   if (N1C && N1C->isAllOnesValue())
2613     return N0;
2614   // if (and x, c) is known to be zero, return 0
2615   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2616                                    APInt::getAllOnesValue(BitWidth)))
2617     return DAG.getConstant(0, VT);
2618   // reassociate and
2619   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2620   if (RAND.getNode())
2621     return RAND;
2622   // fold (and (or x, C), D) -> D if (C & D) == D
2623   if (N1C && N0.getOpcode() == ISD::OR)
2624     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2625       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2626         return N1;
2627   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2628   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2629     SDValue N0Op0 = N0.getOperand(0);
2630     APInt Mask = ~N1C->getAPIntValue();
2631     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2632     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2633       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2634                                  N0.getValueType(), N0Op0);
2635
2636       // Replace uses of the AND with uses of the Zero extend node.
2637       CombineTo(N, Zext);
2638
2639       // We actually want to replace all uses of the any_extend with the
2640       // zero_extend, to avoid duplicating things.  This will later cause this
2641       // AND to be folded.
2642       CombineTo(N0.getNode(), Zext);
2643       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2644     }
2645   }
2646   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2647   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2648   // already be zero by virtue of the width of the base type of the load.
2649   //
2650   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2651   // more cases.
2652   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2653        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2654       N0.getOpcode() == ISD::LOAD) {
2655     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2656                                          N0 : N0.getOperand(0) );
2657
2658     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2659     // This can be a pure constant or a vector splat, in which case we treat the
2660     // vector as a scalar and use the splat value.
2661     APInt Constant = APInt::getNullValue(1);
2662     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2663       Constant = C->getAPIntValue();
2664     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2665       APInt SplatValue, SplatUndef;
2666       unsigned SplatBitSize;
2667       bool HasAnyUndefs;
2668       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2669                                              SplatBitSize, HasAnyUndefs);
2670       if (IsSplat) {
2671         // Undef bits can contribute to a possible optimisation if set, so
2672         // set them.
2673         SplatValue |= SplatUndef;
2674
2675         // The splat value may be something like "0x00FFFFFF", which means 0 for
2676         // the first vector value and FF for the rest, repeating. We need a mask
2677         // that will apply equally to all members of the vector, so AND all the
2678         // lanes of the constant together.
2679         EVT VT = Vector->getValueType(0);
2680         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2681
2682         // If the splat value has been compressed to a bitlength lower
2683         // than the size of the vector lane, we need to re-expand it to
2684         // the lane size.
2685         if (BitWidth > SplatBitSize)
2686           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2687                SplatBitSize < BitWidth;
2688                SplatBitSize = SplatBitSize * 2)
2689             SplatValue |= SplatValue.shl(SplatBitSize);
2690
2691         Constant = APInt::getAllOnesValue(BitWidth);
2692         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2693           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2694       }
2695     }
2696
2697     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2698     // actually legal and isn't going to get expanded, else this is a false
2699     // optimisation.
2700     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2701                                                     Load->getMemoryVT());
2702
2703     // Resize the constant to the same size as the original memory access before
2704     // extension. If it is still the AllOnesValue then this AND is completely
2705     // unneeded.
2706     Constant =
2707       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2708
2709     bool B;
2710     switch (Load->getExtensionType()) {
2711     default: B = false; break;
2712     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2713     case ISD::ZEXTLOAD:
2714     case ISD::NON_EXTLOAD: B = true; break;
2715     }
2716
2717     if (B && Constant.isAllOnesValue()) {
2718       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2719       // preserve semantics once we get rid of the AND.
2720       SDValue NewLoad(Load, 0);
2721       if (Load->getExtensionType() == ISD::EXTLOAD) {
2722         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2723                               Load->getValueType(0), SDLoc(Load),
2724                               Load->getChain(), Load->getBasePtr(),
2725                               Load->getOffset(), Load->getMemoryVT(),
2726                               Load->getMemOperand());
2727         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2728         if (Load->getNumValues() == 3) {
2729           // PRE/POST_INC loads have 3 values.
2730           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2731                            NewLoad.getValue(2) };
2732           CombineTo(Load, To, 3, true);
2733         } else {
2734           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2735         }
2736       }
2737
2738       // Fold the AND away, taking care not to fold to the old load node if we
2739       // replaced it.
2740       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2741
2742       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2743     }
2744   }
2745   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2747     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2748     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2749
2750     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2751         LL.getValueType().isInteger()) {
2752       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2753       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2754         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2755                                      LR.getValueType(), LL, RL);
2756         AddToWorkList(ORNode.getNode());
2757         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2758       }
2759       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2760       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2761         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2762                                       LR.getValueType(), LL, RL);
2763         AddToWorkList(ANDNode.getNode());
2764         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2765       }
2766       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2767       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2768         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2769                                      LR.getValueType(), LL, RL);
2770         AddToWorkList(ORNode.getNode());
2771         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2772       }
2773     }
2774     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2775     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2776         Op0 == Op1 && LL.getValueType().isInteger() &&
2777       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2778                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2779                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2780                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2781       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2782                                     LL, DAG.getConstant(1, LL.getValueType()));
2783       AddToWorkList(ADDNode.getNode());
2784       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2785                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2786     }
2787     // canonicalize equivalent to ll == rl
2788     if (LL == RR && LR == RL) {
2789       Op1 = ISD::getSetCCSwappedOperands(Op1);
2790       std::swap(RL, RR);
2791     }
2792     if (LL == RL && LR == RR) {
2793       bool isInteger = LL.getValueType().isInteger();
2794       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795       if (Result != ISD::SETCC_INVALID &&
2796           (!LegalOperations ||
2797            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798             TLI.isOperationLegal(ISD::SETCC,
2799                             getSetCCResultType(N0.getSimpleValueType())))))
2800         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2801                             LL, LR, Result);
2802     }
2803   }
2804
2805   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2806   if (N0.getOpcode() == N1.getOpcode()) {
2807     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2808     if (Tmp.getNode()) return Tmp;
2809   }
2810
2811   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2812   // fold (and (sra)) -> (and (srl)) when possible.
2813   if (!VT.isVector() &&
2814       SimplifyDemandedBits(SDValue(N, 0)))
2815     return SDValue(N, 0);
2816
2817   // fold (zext_inreg (extload x)) -> (zextload x)
2818   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2819     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2820     EVT MemVT = LN0->getMemoryVT();
2821     // If we zero all the possible extended bits, then we can turn this into
2822     // a zextload if we are running before legalize or the operation is legal.
2823     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2824     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2825                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2826         ((!LegalOperations && !LN0->isVolatile()) ||
2827          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2828       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2829                                        LN0->getChain(), LN0->getBasePtr(),
2830                                        MemVT, LN0->getMemOperand());
2831       AddToWorkList(N);
2832       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2833       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2834     }
2835   }
2836   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2837   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2838       N0.hasOneUse()) {
2839     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2840     EVT MemVT = LN0->getMemoryVT();
2841     // If we zero all the possible extended bits, then we can turn this into
2842     // a zextload if we are running before legalize or the operation is legal.
2843     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2844     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2845                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2846         ((!LegalOperations && !LN0->isVolatile()) ||
2847          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2848       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2849                                        LN0->getChain(), LN0->getBasePtr(),
2850                                        MemVT, LN0->getMemOperand());
2851       AddToWorkList(N);
2852       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2853       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2854     }
2855   }
2856
2857   // fold (and (load x), 255) -> (zextload x, i8)
2858   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2859   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2860   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2861               (N0.getOpcode() == ISD::ANY_EXTEND &&
2862                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2863     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2864     LoadSDNode *LN0 = HasAnyExt
2865       ? cast<LoadSDNode>(N0.getOperand(0))
2866       : cast<LoadSDNode>(N0);
2867     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2868         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2869       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2870       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2871         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2872         EVT LoadedVT = LN0->getMemoryVT();
2873
2874         if (ExtVT == LoadedVT &&
2875             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2876           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2877
2878           SDValue NewLoad =
2879             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2880                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2881                            LN0->getMemOperand());
2882           AddToWorkList(N);
2883           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2884           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2885         }
2886
2887         // Do not change the width of a volatile load.
2888         // Do not generate loads of non-round integer types since these can
2889         // be expensive (and would be wrong if the type is not byte sized).
2890         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2891             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2892           EVT PtrType = LN0->getOperand(1).getValueType();
2893
2894           unsigned Alignment = LN0->getAlignment();
2895           SDValue NewPtr = LN0->getBasePtr();
2896
2897           // For big endian targets, we need to add an offset to the pointer
2898           // to load the correct bytes.  For little endian systems, we merely
2899           // need to read fewer bytes from the same pointer.
2900           if (TLI.isBigEndian()) {
2901             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2902             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2903             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2904             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2905                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2906             Alignment = MinAlign(Alignment, PtrOff);
2907           }
2908
2909           AddToWorkList(NewPtr.getNode());
2910
2911           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2912           SDValue Load =
2913             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2914                            LN0->getChain(), NewPtr,
2915                            LN0->getPointerInfo(),
2916                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2917                            Alignment, LN0->getTBAAInfo());
2918           AddToWorkList(N);
2919           CombineTo(LN0, Load, Load.getValue(1));
2920           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2921         }
2922       }
2923     }
2924   }
2925
2926   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2927       VT.getSizeInBits() <= 64) {
2928     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2929       APInt ADDC = ADDI->getAPIntValue();
2930       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2931         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2932         // immediate for an add, but it is legal if its top c2 bits are set,
2933         // transform the ADD so the immediate doesn't need to be materialized
2934         // in a register.
2935         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2936           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2937                                              SRLI->getZExtValue());
2938           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2939             ADDC |= Mask;
2940             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941               SDValue NewAdd =
2942                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2943                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2944               CombineTo(N0.getNode(), NewAdd);
2945               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2946             }
2947           }
2948         }
2949       }
2950     }
2951   }
2952
2953   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2954   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2955     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2956                                        N0.getOperand(1), false);
2957     if (BSwap.getNode())
2958       return BSwap;
2959   }
2960
2961   return SDValue();
2962 }
2963
2964 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2965 ///
2966 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2967                                         bool DemandHighBits) {
2968   if (!LegalOperations)
2969     return SDValue();
2970
2971   EVT VT = N->getValueType(0);
2972   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2973     return SDValue();
2974   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2975     return SDValue();
2976
2977   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2978   bool LookPassAnd0 = false;
2979   bool LookPassAnd1 = false;
2980   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2981       std::swap(N0, N1);
2982   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2983       std::swap(N0, N1);
2984   if (N0.getOpcode() == ISD::AND) {
2985     if (!N0.getNode()->hasOneUse())
2986       return SDValue();
2987     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2988     if (!N01C || N01C->getZExtValue() != 0xFF00)
2989       return SDValue();
2990     N0 = N0.getOperand(0);
2991     LookPassAnd0 = true;
2992   }
2993
2994   if (N1.getOpcode() == ISD::AND) {
2995     if (!N1.getNode()->hasOneUse())
2996       return SDValue();
2997     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2998     if (!N11C || N11C->getZExtValue() != 0xFF)
2999       return SDValue();
3000     N1 = N1.getOperand(0);
3001     LookPassAnd1 = true;
3002   }
3003
3004   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3005     std::swap(N0, N1);
3006   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3007     return SDValue();
3008   if (!N0.getNode()->hasOneUse() ||
3009       !N1.getNode()->hasOneUse())
3010     return SDValue();
3011
3012   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3013   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3014   if (!N01C || !N11C)
3015     return SDValue();
3016   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3017     return SDValue();
3018
3019   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3020   SDValue N00 = N0->getOperand(0);
3021   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3022     if (!N00.getNode()->hasOneUse())
3023       return SDValue();
3024     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3025     if (!N001C || N001C->getZExtValue() != 0xFF)
3026       return SDValue();
3027     N00 = N00.getOperand(0);
3028     LookPassAnd0 = true;
3029   }
3030
3031   SDValue N10 = N1->getOperand(0);
3032   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3033     if (!N10.getNode()->hasOneUse())
3034       return SDValue();
3035     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3036     if (!N101C || N101C->getZExtValue() != 0xFF00)
3037       return SDValue();
3038     N10 = N10.getOperand(0);
3039     LookPassAnd1 = true;
3040   }
3041
3042   if (N00 != N10)
3043     return SDValue();
3044
3045   // Make sure everything beyond the low halfword gets set to zero since the SRL
3046   // 16 will clear the top bits.
3047   unsigned OpSizeInBits = VT.getSizeInBits();
3048   if (DemandHighBits && OpSizeInBits > 16) {
3049     // If the left-shift isn't masked out then the only way this is a bswap is
3050     // if all bits beyond the low 8 are 0. In that case the entire pattern
3051     // reduces to a left shift anyway: leave it for other parts of the combiner.
3052     if (!LookPassAnd0)
3053       return SDValue();
3054
3055     // However, if the right shift isn't masked out then it might be because
3056     // it's not needed. See if we can spot that too.
3057     if (!LookPassAnd1 &&
3058         !DAG.MaskedValueIsZero(
3059             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3060       return SDValue();
3061   }
3062
3063   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3064   if (OpSizeInBits > 16)
3065     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3066                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3067   return Res;
3068 }
3069
3070 /// isBSwapHWordElement - Return true if the specified node is an element
3071 /// that makes up a 32-bit packed halfword byteswap. i.e.
3072 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3073 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3074   if (!N.getNode()->hasOneUse())
3075     return false;
3076
3077   unsigned Opc = N.getOpcode();
3078   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3079     return false;
3080
3081   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3082   if (!N1C)
3083     return false;
3084
3085   unsigned Num;
3086   switch (N1C->getZExtValue()) {
3087   default:
3088     return false;
3089   case 0xFF:       Num = 0; break;
3090   case 0xFF00:     Num = 1; break;
3091   case 0xFF0000:   Num = 2; break;
3092   case 0xFF000000: Num = 3; break;
3093   }
3094
3095   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3096   SDValue N0 = N.getOperand(0);
3097   if (Opc == ISD::AND) {
3098     if (Num == 0 || Num == 2) {
3099       // (x >> 8) & 0xff
3100       // (x >> 8) & 0xff0000
3101       if (N0.getOpcode() != ISD::SRL)
3102         return false;
3103       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3104       if (!C || C->getZExtValue() != 8)
3105         return false;
3106     } else {
3107       // (x << 8) & 0xff00
3108       // (x << 8) & 0xff000000
3109       if (N0.getOpcode() != ISD::SHL)
3110         return false;
3111       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3112       if (!C || C->getZExtValue() != 8)
3113         return false;
3114     }
3115   } else if (Opc == ISD::SHL) {
3116     // (x & 0xff) << 8
3117     // (x & 0xff0000) << 8
3118     if (Num != 0 && Num != 2)
3119       return false;
3120     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3121     if (!C || C->getZExtValue() != 8)
3122       return false;
3123   } else { // Opc == ISD::SRL
3124     // (x & 0xff00) >> 8
3125     // (x & 0xff000000) >> 8
3126     if (Num != 1 && Num != 3)
3127       return false;
3128     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3129     if (!C || C->getZExtValue() != 8)
3130       return false;
3131   }
3132
3133   if (Parts[Num])
3134     return false;
3135
3136   Parts[Num] = N0.getOperand(0).getNode();
3137   return true;
3138 }
3139
3140 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3141 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3142 /// => (rotl (bswap x), 16)
3143 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3144   if (!LegalOperations)
3145     return SDValue();
3146
3147   EVT VT = N->getValueType(0);
3148   if (VT != MVT::i32)
3149     return SDValue();
3150   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3151     return SDValue();
3152
3153   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3154   // Look for either
3155   // (or (or (and), (and)), (or (and), (and)))
3156   // (or (or (or (and), (and)), (and)), (and))
3157   if (N0.getOpcode() != ISD::OR)
3158     return SDValue();
3159   SDValue N00 = N0.getOperand(0);
3160   SDValue N01 = N0.getOperand(1);
3161
3162   if (N1.getOpcode() == ISD::OR &&
3163       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3164     // (or (or (and), (and)), (or (and), (and)))
3165     SDValue N000 = N00.getOperand(0);
3166     if (!isBSwapHWordElement(N000, Parts))
3167       return SDValue();
3168
3169     SDValue N001 = N00.getOperand(1);
3170     if (!isBSwapHWordElement(N001, Parts))
3171       return SDValue();
3172     SDValue N010 = N01.getOperand(0);
3173     if (!isBSwapHWordElement(N010, Parts))
3174       return SDValue();
3175     SDValue N011 = N01.getOperand(1);
3176     if (!isBSwapHWordElement(N011, Parts))
3177       return SDValue();
3178   } else {
3179     // (or (or (or (and), (and)), (and)), (and))
3180     if (!isBSwapHWordElement(N1, Parts))
3181       return SDValue();
3182     if (!isBSwapHWordElement(N01, Parts))
3183       return SDValue();
3184     if (N00.getOpcode() != ISD::OR)
3185       return SDValue();
3186     SDValue N000 = N00.getOperand(0);
3187     if (!isBSwapHWordElement(N000, Parts))
3188       return SDValue();
3189     SDValue N001 = N00.getOperand(1);
3190     if (!isBSwapHWordElement(N001, Parts))
3191       return SDValue();
3192   }
3193
3194   // Make sure the parts are all coming from the same node.
3195   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3196     return SDValue();
3197
3198   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3199                               SDValue(Parts[0],0));
3200
3201   // Result of the bswap should be rotated by 16. If it's not legal, then
3202   // do  (x << 16) | (x >> 16).
3203   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3204   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3205     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3206   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3207     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3208   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3209                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3210                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3211 }
3212
3213 SDValue DAGCombiner::visitOR(SDNode *N) {
3214   SDValue N0 = N->getOperand(0);
3215   SDValue N1 = N->getOperand(1);
3216   SDValue LL, LR, RL, RR, CC0, CC1;
3217   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3218   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3219   EVT VT = N1.getValueType();
3220
3221   // fold vector ops
3222   if (VT.isVector()) {
3223     SDValue FoldedVOp = SimplifyVBinOp(N);
3224     if (FoldedVOp.getNode()) return FoldedVOp;
3225
3226     // fold (or x, 0) -> x, vector edition
3227     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3228       return N1;
3229     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3230       return N0;
3231
3232     // fold (or x, -1) -> -1, vector edition
3233     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3234       return N0;
3235     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3236       return N1;
3237
3238     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3239     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3240     // Do this only if the resulting shuffle is legal.
3241     if (isa<ShuffleVectorSDNode>(N0) &&
3242         isa<ShuffleVectorSDNode>(N1) &&
3243         N0->getOperand(1) == N1->getOperand(1) &&
3244         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3245       bool CanFold = true;
3246       unsigned NumElts = VT.getVectorNumElements();
3247       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3248       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3249       // We construct two shuffle masks:
3250       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3251       // and N1 as the second operand.
3252       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3253       // and N0 as the second operand.
3254       // We do this because OR is commutable and therefore there might be
3255       // two ways to fold this node into a shuffle.
3256       SmallVector<int,4> Mask1;
3257       SmallVector<int,4> Mask2;
3258       
3259       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3260         int M0 = SV0->getMaskElt(i);
3261         int M1 = SV1->getMaskElt(i);
3262    
3263         // Both shuffle indexes are undef. Propagate Undef.
3264         if (M0 < 0 && M1 < 0) {
3265           Mask1.push_back(M0);
3266           Mask2.push_back(M0);
3267           continue;
3268         }
3269
3270         if (M0 < 0 || M1 < 0 ||
3271             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3272             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3273           CanFold = false;
3274           break;
3275         }
3276         
3277         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3278         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3279       }
3280
3281       if (CanFold) {
3282         // Fold this sequence only if the resulting shuffle is 'legal'.
3283         if (TLI.isShuffleMaskLegal(Mask1, VT))
3284           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3285                                       N1->getOperand(0), &Mask1[0]);
3286         if (TLI.isShuffleMaskLegal(Mask2, VT))
3287           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3288                                       N0->getOperand(0), &Mask2[0]);
3289       }
3290     }
3291   }
3292
3293   // fold (or x, undef) -> -1
3294   if (!LegalOperations &&
3295       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3296     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3297     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3298   }
3299   // fold (or c1, c2) -> c1|c2
3300   if (N0C && N1C)
3301     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3302   // canonicalize constant to RHS
3303   if (N0C && !N1C)
3304     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3305   // fold (or x, 0) -> x
3306   if (N1C && N1C->isNullValue())
3307     return N0;
3308   // fold (or x, -1) -> -1
3309   if (N1C && N1C->isAllOnesValue())
3310     return N1;
3311   // fold (or x, c) -> c iff (x & ~c) == 0
3312   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3313     return N1;
3314
3315   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3316   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3317   if (BSwap.getNode())
3318     return BSwap;
3319   BSwap = MatchBSwapHWordLow(N, N0, N1);
3320   if (BSwap.getNode())
3321     return BSwap;
3322
3323   // reassociate or
3324   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3325   if (ROR.getNode())
3326     return ROR;
3327   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3328   // iff (c1 & c2) == 0.
3329   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3330              isa<ConstantSDNode>(N0.getOperand(1))) {
3331     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3332     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3333       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3334       if (!COR.getNode())
3335         return SDValue();
3336       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3337                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3338                                      N0.getOperand(0), N1), COR);
3339     }
3340   }
3341   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3342   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3343     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3344     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3345
3346     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3347         LL.getValueType().isInteger()) {
3348       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3349       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3350       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3351           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3352         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3353                                      LR.getValueType(), LL, RL);
3354         AddToWorkList(ORNode.getNode());
3355         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3356       }
3357       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3358       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3359       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3360           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3361         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3362                                       LR.getValueType(), LL, RL);
3363         AddToWorkList(ANDNode.getNode());
3364         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3365       }
3366     }
3367     // canonicalize equivalent to ll == rl
3368     if (LL == RR && LR == RL) {
3369       Op1 = ISD::getSetCCSwappedOperands(Op1);
3370       std::swap(RL, RR);
3371     }
3372     if (LL == RL && LR == RR) {
3373       bool isInteger = LL.getValueType().isInteger();
3374       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3375       if (Result != ISD::SETCC_INVALID &&
3376           (!LegalOperations ||
3377            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3378             TLI.isOperationLegal(ISD::SETCC,
3379               getSetCCResultType(N0.getValueType())))))
3380         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3381                             LL, LR, Result);
3382     }
3383   }
3384
3385   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3386   if (N0.getOpcode() == N1.getOpcode()) {
3387     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3388     if (Tmp.getNode()) return Tmp;
3389   }
3390
3391   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3392   if (N0.getOpcode() == ISD::AND &&
3393       N1.getOpcode() == ISD::AND &&
3394       N0.getOperand(1).getOpcode() == ISD::Constant &&
3395       N1.getOperand(1).getOpcode() == ISD::Constant &&
3396       // Don't increase # computations.
3397       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3398     // We can only do this xform if we know that bits from X that are set in C2
3399     // but not in C1 are already zero.  Likewise for Y.
3400     const APInt &LHSMask =
3401       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3402     const APInt &RHSMask =
3403       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3404
3405     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3406         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3407       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3408                               N0.getOperand(0), N1.getOperand(0));
3409       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3410                          DAG.getConstant(LHSMask | RHSMask, VT));
3411     }
3412   }
3413
3414   // See if this is some rotate idiom.
3415   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3416     return SDValue(Rot, 0);
3417
3418   // Simplify the operands using demanded-bits information.
3419   if (!VT.isVector() &&
3420       SimplifyDemandedBits(SDValue(N, 0)))
3421     return SDValue(N, 0);
3422
3423   return SDValue();
3424 }
3425
3426 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3427 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3428   if (Op.getOpcode() == ISD::AND) {
3429     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3430       Mask = Op.getOperand(1);
3431       Op = Op.getOperand(0);
3432     } else {
3433       return false;
3434     }
3435   }
3436
3437   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3438     Shift = Op;
3439     return true;
3440   }
3441
3442   return false;
3443 }
3444
3445 // Return true if we can prove that, whenever Neg and Pos are both in the
3446 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3447 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3448 //
3449 //     (or (shift1 X, Neg), (shift2 X, Pos))
3450 //
3451 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3452 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3453 // to consider shift amounts with defined behavior.
3454 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3455   // If OpSize is a power of 2 then:
3456   //
3457   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3458   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3459   //
3460   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3461   // for the stronger condition:
3462   //
3463   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3464   //
3465   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3466   // we can just replace Neg with Neg' for the rest of the function.
3467   //
3468   // In other cases we check for the even stronger condition:
3469   //
3470   //     Neg == OpSize - Pos                                    [B]
3471   //
3472   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3473   // behavior if Pos == 0 (and consequently Neg == OpSize).
3474   //
3475   // We could actually use [A] whenever OpSize is a power of 2, but the
3476   // only extra cases that it would match are those uninteresting ones
3477   // where Neg and Pos are never in range at the same time.  E.g. for
3478   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3479   // as well as (sub 32, Pos), but:
3480   //
3481   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3482   //
3483   // always invokes undefined behavior for 32-bit X.
3484   //
3485   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3486   unsigned MaskLoBits = 0;
3487   if (Neg.getOpcode() == ISD::AND &&
3488       isPowerOf2_64(OpSize) &&
3489       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3490       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3491     Neg = Neg.getOperand(0);
3492     MaskLoBits = Log2_64(OpSize);
3493   }
3494
3495   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3496   if (Neg.getOpcode() != ISD::SUB)
3497     return 0;
3498   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3499   if (!NegC)
3500     return 0;
3501   SDValue NegOp1 = Neg.getOperand(1);
3502
3503   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3504   // Pos'.  The truncation is redundant for the purpose of the equality.
3505   if (MaskLoBits &&
3506       Pos.getOpcode() == ISD::AND &&
3507       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3508       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3509     Pos = Pos.getOperand(0);
3510
3511   // The condition we need is now:
3512   //
3513   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3514   //
3515   // If NegOp1 == Pos then we need:
3516   //
3517   //              OpSize & Mask == NegC & Mask
3518   //
3519   // (because "x & Mask" is a truncation and distributes through subtraction).
3520   APInt Width;
3521   if (Pos == NegOp1)
3522     Width = NegC->getAPIntValue();
3523   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3524   // Then the condition we want to prove becomes:
3525   //
3526   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3527   //
3528   // which, again because "x & Mask" is a truncation, becomes:
3529   //
3530   //                NegC & Mask == (OpSize - PosC) & Mask
3531   //              OpSize & Mask == (NegC + PosC) & Mask
3532   else if (Pos.getOpcode() == ISD::ADD &&
3533            Pos.getOperand(0) == NegOp1 &&
3534            Pos.getOperand(1).getOpcode() == ISD::Constant)
3535     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3536              NegC->getAPIntValue());
3537   else
3538     return false;
3539
3540   // Now we just need to check that OpSize & Mask == Width & Mask.
3541   if (MaskLoBits)
3542     // Opsize & Mask is 0 since Mask is Opsize - 1.
3543     return Width.getLoBits(MaskLoBits) == 0;
3544   return Width == OpSize;
3545 }
3546
3547 // A subroutine of MatchRotate used once we have found an OR of two opposite
3548 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3549 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3550 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3551 // Neg with outer conversions stripped away.
3552 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3553                                        SDValue Neg, SDValue InnerPos,
3554                                        SDValue InnerNeg, unsigned PosOpcode,
3555                                        unsigned NegOpcode, SDLoc DL) {
3556   // fold (or (shl x, (*ext y)),
3557   //          (srl x, (*ext (sub 32, y)))) ->
3558   //   (rotl x, y) or (rotr x, (sub 32, y))
3559   //
3560   // fold (or (shl x, (*ext (sub 32, y))),
3561   //          (srl x, (*ext y))) ->
3562   //   (rotr x, y) or (rotl x, (sub 32, y))
3563   EVT VT = Shifted.getValueType();
3564   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3565     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3566     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3567                        HasPos ? Pos : Neg).getNode();
3568   }
3569
3570   return nullptr;
3571 }
3572
3573 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3574 // idioms for rotate, and if the target supports rotation instructions, generate
3575 // a rot[lr].
3576 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3577   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3578   EVT VT = LHS.getValueType();
3579   if (!TLI.isTypeLegal(VT)) return nullptr;
3580
3581   // The target must have at least one rotate flavor.
3582   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3583   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3584   if (!HasROTL && !HasROTR) return nullptr;
3585
3586   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3587   SDValue LHSShift;   // The shift.
3588   SDValue LHSMask;    // AND value if any.
3589   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3590     return nullptr; // Not part of a rotate.
3591
3592   SDValue RHSShift;   // The shift.
3593   SDValue RHSMask;    // AND value if any.
3594   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3595     return nullptr; // Not part of a rotate.
3596
3597   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3598     return nullptr;   // Not shifting the same value.
3599
3600   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3601     return nullptr;   // Shifts must disagree.
3602
3603   // Canonicalize shl to left side in a shl/srl pair.
3604   if (RHSShift.getOpcode() == ISD::SHL) {
3605     std::swap(LHS, RHS);
3606     std::swap(LHSShift, RHSShift);
3607     std::swap(LHSMask , RHSMask );
3608   }
3609
3610   unsigned OpSizeInBits = VT.getSizeInBits();
3611   SDValue LHSShiftArg = LHSShift.getOperand(0);
3612   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3613   SDValue RHSShiftArg = RHSShift.getOperand(0);
3614   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3615
3616   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3617   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3618   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3619       RHSShiftAmt.getOpcode() == ISD::Constant) {
3620     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3621     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3622     if ((LShVal + RShVal) != OpSizeInBits)
3623       return nullptr;
3624
3625     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3626                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3627
3628     // If there is an AND of either shifted operand, apply it to the result.
3629     if (LHSMask.getNode() || RHSMask.getNode()) {
3630       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3631
3632       if (LHSMask.getNode()) {
3633         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3634         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3635       }
3636       if (RHSMask.getNode()) {
3637         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3638         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3639       }
3640
3641       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3642     }
3643
3644     return Rot.getNode();
3645   }
3646
3647   // If there is a mask here, and we have a variable shift, we can't be sure
3648   // that we're masking out the right stuff.
3649   if (LHSMask.getNode() || RHSMask.getNode())
3650     return nullptr;
3651
3652   // If the shift amount is sign/zext/any-extended just peel it off.
3653   SDValue LExtOp0 = LHSShiftAmt;
3654   SDValue RExtOp0 = RHSShiftAmt;
3655   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3656        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3657        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3658        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3659       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3660        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3661        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3662        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3663     LExtOp0 = LHSShiftAmt.getOperand(0);
3664     RExtOp0 = RHSShiftAmt.getOperand(0);
3665   }
3666
3667   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3668                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3669   if (TryL)
3670     return TryL;
3671
3672   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3673                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3674   if (TryR)
3675     return TryR;
3676
3677   return nullptr;
3678 }
3679
3680 SDValue DAGCombiner::visitXOR(SDNode *N) {
3681   SDValue N0 = N->getOperand(0);
3682   SDValue N1 = N->getOperand(1);
3683   SDValue LHS, RHS, CC;
3684   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3685   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3686   EVT VT = N0.getValueType();
3687
3688   // fold vector ops
3689   if (VT.isVector()) {
3690     SDValue FoldedVOp = SimplifyVBinOp(N);
3691     if (FoldedVOp.getNode()) return FoldedVOp;
3692
3693     // fold (xor x, 0) -> x, vector edition
3694     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3695       return N1;
3696     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3697       return N0;
3698   }
3699
3700   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3701   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3702     return DAG.getConstant(0, VT);
3703   // fold (xor x, undef) -> undef
3704   if (N0.getOpcode() == ISD::UNDEF)
3705     return N0;
3706   if (N1.getOpcode() == ISD::UNDEF)
3707     return N1;
3708   // fold (xor c1, c2) -> c1^c2
3709   if (N0C && N1C)
3710     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3711   // canonicalize constant to RHS
3712   if (N0C && !N1C)
3713     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3714   // fold (xor x, 0) -> x
3715   if (N1C && N1C->isNullValue())
3716     return N0;
3717   // reassociate xor
3718   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3719   if (RXOR.getNode())
3720     return RXOR;
3721
3722   // fold !(x cc y) -> (x !cc y)
3723   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3724     bool isInt = LHS.getValueType().isInteger();
3725     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3726                                                isInt);
3727
3728     if (!LegalOperations ||
3729         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3730       switch (N0.getOpcode()) {
3731       default:
3732         llvm_unreachable("Unhandled SetCC Equivalent!");
3733       case ISD::SETCC:
3734         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3735       case ISD::SELECT_CC:
3736         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3737                                N0.getOperand(3), NotCC);
3738       }
3739     }
3740   }
3741
3742   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3743   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3744       N0.getNode()->hasOneUse() &&
3745       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3746     SDValue V = N0.getOperand(0);
3747     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3748                     DAG.getConstant(1, V.getValueType()));
3749     AddToWorkList(V.getNode());
3750     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3751   }
3752
3753   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3754   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3755       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3756     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3757     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3758       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3759       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3760       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3761       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3762       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3763     }
3764   }
3765   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3766   if (N1C && N1C->isAllOnesValue() &&
3767       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3768     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3769     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3770       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3771       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3772       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3773       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3774       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3775     }
3776   }
3777   // fold (xor (and x, y), y) -> (and (not x), y)
3778   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3779       N0->getOperand(1) == N1) {
3780     SDValue X = N0->getOperand(0);
3781     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3782     AddToWorkList(NotX.getNode());
3783     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3784   }
3785   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3786   if (N1C && N0.getOpcode() == ISD::XOR) {
3787     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3788     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3789     if (N00C)
3790       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3791                          DAG.getConstant(N1C->getAPIntValue() ^
3792                                          N00C->getAPIntValue(), VT));
3793     if (N01C)
3794       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3795                          DAG.getConstant(N1C->getAPIntValue() ^
3796                                          N01C->getAPIntValue(), VT));
3797   }
3798   // fold (xor x, x) -> 0
3799   if (N0 == N1)
3800     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3801
3802   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3803   if (N0.getOpcode() == N1.getOpcode()) {
3804     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3805     if (Tmp.getNode()) return Tmp;
3806   }
3807
3808   // Simplify the expression using non-local knowledge.
3809   if (!VT.isVector() &&
3810       SimplifyDemandedBits(SDValue(N, 0)))
3811     return SDValue(N, 0);
3812
3813   return SDValue();
3814 }
3815
3816 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3817 /// the shift amount is a constant.
3818 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3819   // We can't and shouldn't fold opaque constants.
3820   if (Amt->isOpaque())
3821     return SDValue();
3822
3823   SDNode *LHS = N->getOperand(0).getNode();
3824   if (!LHS->hasOneUse()) return SDValue();
3825
3826   // We want to pull some binops through shifts, so that we have (and (shift))
3827   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3828   // thing happens with address calculations, so it's important to canonicalize
3829   // it.
3830   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3831
3832   switch (LHS->getOpcode()) {
3833   default: return SDValue();
3834   case ISD::OR:
3835   case ISD::XOR:
3836     HighBitSet = false; // We can only transform sra if the high bit is clear.
3837     break;
3838   case ISD::AND:
3839     HighBitSet = true;  // We can only transform sra if the high bit is set.
3840     break;
3841   case ISD::ADD:
3842     if (N->getOpcode() != ISD::SHL)
3843       return SDValue(); // only shl(add) not sr[al](add).
3844     HighBitSet = false; // We can only transform sra if the high bit is clear.
3845     break;
3846   }
3847
3848   // We require the RHS of the binop to be a constant and not opaque as well.
3849   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3850   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3851
3852   // FIXME: disable this unless the input to the binop is a shift by a constant.
3853   // If it is not a shift, it pessimizes some common cases like:
3854   //
3855   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3856   //    int bar(int *X, int i) { return X[i & 255]; }
3857   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3858   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3859        BinOpLHSVal->getOpcode() != ISD::SRA &&
3860        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3861       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3862     return SDValue();
3863
3864   EVT VT = N->getValueType(0);
3865
3866   // If this is a signed shift right, and the high bit is modified by the
3867   // logical operation, do not perform the transformation. The highBitSet
3868   // boolean indicates the value of the high bit of the constant which would
3869   // cause it to be modified for this operation.
3870   if (N->getOpcode() == ISD::SRA) {
3871     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3872     if (BinOpRHSSignSet != HighBitSet)
3873       return SDValue();
3874   }
3875
3876   // Fold the constants, shifting the binop RHS by the shift amount.
3877   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3878                                N->getValueType(0),
3879                                LHS->getOperand(1), N->getOperand(1));
3880   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3881
3882   // Create the new shift.
3883   SDValue NewShift = DAG.getNode(N->getOpcode(),
3884                                  SDLoc(LHS->getOperand(0)),
3885                                  VT, LHS->getOperand(0), N->getOperand(1));
3886
3887   // Create the new binop.
3888   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3889 }
3890
3891 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3892   assert(N->getOpcode() == ISD::TRUNCATE);
3893   assert(N->getOperand(0).getOpcode() == ISD::AND);
3894
3895   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3896   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3897     SDValue N01 = N->getOperand(0).getOperand(1);
3898
3899     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3900       EVT TruncVT = N->getValueType(0);
3901       SDValue N00 = N->getOperand(0).getOperand(0);
3902       APInt TruncC = N01C->getAPIntValue();
3903       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3904
3905       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3906                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3907                          DAG.getConstant(TruncC, TruncVT));
3908     }
3909   }
3910
3911   return SDValue();
3912 }
3913
3914 SDValue DAGCombiner::visitRotate(SDNode *N) {
3915   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3916   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3917       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3918     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3919     if (NewOp1.getNode())
3920       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3921                          N->getOperand(0), NewOp1);
3922   }
3923   return SDValue();
3924 }
3925
3926 SDValue DAGCombiner::visitSHL(SDNode *N) {
3927   SDValue N0 = N->getOperand(0);
3928   SDValue N1 = N->getOperand(1);
3929   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3930   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3931   EVT VT = N0.getValueType();
3932   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3933
3934   // fold vector ops
3935   if (VT.isVector()) {
3936     SDValue FoldedVOp = SimplifyVBinOp(N);
3937     if (FoldedVOp.getNode()) return FoldedVOp;
3938
3939     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3940     // If setcc produces all-one true value then:
3941     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3942     if (N1CV && N1CV->isConstant()) {
3943       if (N0.getOpcode() == ISD::AND &&
3944           TLI.getBooleanContents(true) ==
3945           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3946         SDValue N00 = N0->getOperand(0);
3947         SDValue N01 = N0->getOperand(1);
3948         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3949
3950         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3951           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3952           if (C.getNode())
3953             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3954         }
3955       } else {
3956         N1C = isConstOrConstSplat(N1);
3957       }
3958     }
3959   }
3960
3961   // fold (shl c1, c2) -> c1<<c2
3962   if (N0C && N1C)
3963     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3964   // fold (shl 0, x) -> 0
3965   if (N0C && N0C->isNullValue())
3966     return N0;
3967   // fold (shl x, c >= size(x)) -> undef
3968   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3969     return DAG.getUNDEF(VT);
3970   // fold (shl x, 0) -> x
3971   if (N1C && N1C->isNullValue())
3972     return N0;
3973   // fold (shl undef, x) -> 0
3974   if (N0.getOpcode() == ISD::UNDEF)
3975     return DAG.getConstant(0, VT);
3976   // if (shl x, c) is known to be zero, return 0
3977   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3978                             APInt::getAllOnesValue(OpSizeInBits)))
3979     return DAG.getConstant(0, VT);
3980   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3981   if (N1.getOpcode() == ISD::TRUNCATE &&
3982       N1.getOperand(0).getOpcode() == ISD::AND) {
3983     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3984     if (NewOp1.getNode())
3985       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3986   }
3987
3988   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3989     return SDValue(N, 0);
3990
3991   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3992   if (N1C && N0.getOpcode() == ISD::SHL) {
3993     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3994       uint64_t c1 = N0C1->getZExtValue();
3995       uint64_t c2 = N1C->getZExtValue();
3996       if (c1 + c2 >= OpSizeInBits)
3997         return DAG.getConstant(0, VT);
3998       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3999                          DAG.getConstant(c1 + c2, N1.getValueType()));
4000     }
4001   }
4002
4003   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4004   // For this to be valid, the second form must not preserve any of the bits
4005   // that are shifted out by the inner shift in the first form.  This means
4006   // the outer shift size must be >= the number of bits added by the ext.
4007   // As a corollary, we don't care what kind of ext it is.
4008   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4009               N0.getOpcode() == ISD::ANY_EXTEND ||
4010               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4011       N0.getOperand(0).getOpcode() == ISD::SHL) {
4012     SDValue N0Op0 = N0.getOperand(0);
4013     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4014       uint64_t c1 = N0Op0C1->getZExtValue();
4015       uint64_t c2 = N1C->getZExtValue();
4016       EVT InnerShiftVT = N0Op0.getValueType();
4017       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4018       if (c2 >= OpSizeInBits - InnerShiftSize) {
4019         if (c1 + c2 >= OpSizeInBits)
4020           return DAG.getConstant(0, VT);
4021         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4022                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4023                                        N0Op0->getOperand(0)),
4024                            DAG.getConstant(c1 + c2, N1.getValueType()));
4025       }
4026     }
4027   }
4028
4029   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4030   // Only fold this if the inner zext has no other uses to avoid increasing
4031   // the total number of instructions.
4032   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4033       N0.getOperand(0).getOpcode() == ISD::SRL) {
4034     SDValue N0Op0 = N0.getOperand(0);
4035     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4036       uint64_t c1 = N0Op0C1->getZExtValue();
4037       if (c1 < VT.getScalarSizeInBits()) {
4038         uint64_t c2 = N1C->getZExtValue();
4039         if (c1 == c2) {
4040           SDValue NewOp0 = N0.getOperand(0);
4041           EVT CountVT = NewOp0.getOperand(1).getValueType();
4042           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4043                                        NewOp0, DAG.getConstant(c2, CountVT));
4044           AddToWorkList(NewSHL.getNode());
4045           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4046         }
4047       }
4048     }
4049   }
4050
4051   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4052   //                               (and (srl x, (sub c1, c2), MASK)
4053   // Only fold this if the inner shift has no other uses -- if it does, folding
4054   // this will increase the total number of instructions.
4055   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4056     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4057       uint64_t c1 = N0C1->getZExtValue();
4058       if (c1 < OpSizeInBits) {
4059         uint64_t c2 = N1C->getZExtValue();
4060         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4061         SDValue Shift;
4062         if (c2 > c1) {
4063           Mask = Mask.shl(c2 - c1);
4064           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4065                               DAG.getConstant(c2 - c1, N1.getValueType()));
4066         } else {
4067           Mask = Mask.lshr(c1 - c2);
4068           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4069                               DAG.getConstant(c1 - c2, N1.getValueType()));
4070         }
4071         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4072                            DAG.getConstant(Mask, VT));
4073       }
4074     }
4075   }
4076   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4077   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4078     unsigned BitSize = VT.getScalarSizeInBits();
4079     SDValue HiBitsMask =
4080       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4081                                             BitSize - N1C->getZExtValue()), VT);
4082     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4083                        HiBitsMask);
4084   }
4085
4086   if (N1C) {
4087     SDValue NewSHL = visitShiftByConstant(N, N1C);
4088     if (NewSHL.getNode())
4089       return NewSHL;
4090   }
4091
4092   return SDValue();
4093 }
4094
4095 SDValue DAGCombiner::visitSRA(SDNode *N) {
4096   SDValue N0 = N->getOperand(0);
4097   SDValue N1 = N->getOperand(1);
4098   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4099   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4100   EVT VT = N0.getValueType();
4101   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4102
4103   // fold vector ops
4104   if (VT.isVector()) {
4105     SDValue FoldedVOp = SimplifyVBinOp(N);
4106     if (FoldedVOp.getNode()) return FoldedVOp;
4107
4108     N1C = isConstOrConstSplat(N1);
4109   }
4110
4111   // fold (sra c1, c2) -> (sra c1, c2)
4112   if (N0C && N1C)
4113     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4114   // fold (sra 0, x) -> 0
4115   if (N0C && N0C->isNullValue())
4116     return N0;
4117   // fold (sra -1, x) -> -1
4118   if (N0C && N0C->isAllOnesValue())
4119     return N0;
4120   // fold (sra x, (setge c, size(x))) -> undef
4121   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4122     return DAG.getUNDEF(VT);
4123   // fold (sra x, 0) -> x
4124   if (N1C && N1C->isNullValue())
4125     return N0;
4126   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4127   // sext_inreg.
4128   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4129     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4130     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4131     if (VT.isVector())
4132       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4133                                ExtVT, VT.getVectorNumElements());
4134     if ((!LegalOperations ||
4135          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4136       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4137                          N0.getOperand(0), DAG.getValueType(ExtVT));
4138   }
4139
4140   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4141   if (N1C && N0.getOpcode() == ISD::SRA) {
4142     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4143       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4144       if (Sum >= OpSizeInBits)
4145         Sum = OpSizeInBits - 1;
4146       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4147                          DAG.getConstant(Sum, N1.getValueType()));
4148     }
4149   }
4150
4151   // fold (sra (shl X, m), (sub result_size, n))
4152   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4153   // result_size - n != m.
4154   // If truncate is free for the target sext(shl) is likely to result in better
4155   // code.
4156   if (N0.getOpcode() == ISD::SHL && N1C) {
4157     // Get the two constanst of the shifts, CN0 = m, CN = n.
4158     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4159     if (N01C) {
4160       LLVMContext &Ctx = *DAG.getContext();
4161       // Determine what the truncate's result bitsize and type would be.
4162       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4163
4164       if (VT.isVector())
4165         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4166
4167       // Determine the residual right-shift amount.
4168       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4169
4170       // If the shift is not a no-op (in which case this should be just a sign
4171       // extend already), the truncated to type is legal, sign_extend is legal
4172       // on that type, and the truncate to that type is both legal and free,
4173       // perform the transform.
4174       if ((ShiftAmt > 0) &&
4175           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4176           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4177           TLI.isTruncateFree(VT, TruncVT)) {
4178
4179           SDValue Amt = DAG.getConstant(ShiftAmt,
4180               getShiftAmountTy(N0.getOperand(0).getValueType()));
4181           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4182                                       N0.getOperand(0), Amt);
4183           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4184                                       Shift);
4185           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4186                              N->getValueType(0), Trunc);
4187       }
4188     }
4189   }
4190
4191   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4192   if (N1.getOpcode() == ISD::TRUNCATE &&
4193       N1.getOperand(0).getOpcode() == ISD::AND) {
4194     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4195     if (NewOp1.getNode())
4196       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4197   }
4198
4199   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4200   //      if c1 is equal to the number of bits the trunc removes
4201   if (N0.getOpcode() == ISD::TRUNCATE &&
4202       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4203        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4204       N0.getOperand(0).hasOneUse() &&
4205       N0.getOperand(0).getOperand(1).hasOneUse() &&
4206       N1C) {
4207     SDValue N0Op0 = N0.getOperand(0);
4208     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4209       unsigned LargeShiftVal = LargeShift->getZExtValue();
4210       EVT LargeVT = N0Op0.getValueType();
4211
4212       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4213         SDValue Amt =
4214           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4215                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4216         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4217                                   N0Op0.getOperand(0), Amt);
4218         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4219       }
4220     }
4221   }
4222
4223   // Simplify, based on bits shifted out of the LHS.
4224   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4225     return SDValue(N, 0);
4226
4227
4228   // If the sign bit is known to be zero, switch this to a SRL.
4229   if (DAG.SignBitIsZero(N0))
4230     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4231
4232   if (N1C) {
4233     SDValue NewSRA = visitShiftByConstant(N, N1C);
4234     if (NewSRA.getNode())
4235       return NewSRA;
4236   }
4237
4238   return SDValue();
4239 }
4240
4241 SDValue DAGCombiner::visitSRL(SDNode *N) {
4242   SDValue N0 = N->getOperand(0);
4243   SDValue N1 = N->getOperand(1);
4244   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4245   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4246   EVT VT = N0.getValueType();
4247   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4248
4249   // fold vector ops
4250   if (VT.isVector()) {
4251     SDValue FoldedVOp = SimplifyVBinOp(N);
4252     if (FoldedVOp.getNode()) return FoldedVOp;
4253
4254     N1C = isConstOrConstSplat(N1);
4255   }
4256
4257   // fold (srl c1, c2) -> c1 >>u c2
4258   if (N0C && N1C)
4259     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4260   // fold (srl 0, x) -> 0
4261   if (N0C && N0C->isNullValue())
4262     return N0;
4263   // fold (srl x, c >= size(x)) -> undef
4264   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4265     return DAG.getUNDEF(VT);
4266   // fold (srl x, 0) -> x
4267   if (N1C && N1C->isNullValue())
4268     return N0;
4269   // if (srl x, c) is known to be zero, return 0
4270   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4271                                    APInt::getAllOnesValue(OpSizeInBits)))
4272     return DAG.getConstant(0, VT);
4273
4274   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4275   if (N1C && N0.getOpcode() == ISD::SRL) {
4276     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4277       uint64_t c1 = N01C->getZExtValue();
4278       uint64_t c2 = N1C->getZExtValue();
4279       if (c1 + c2 >= OpSizeInBits)
4280         return DAG.getConstant(0, VT);
4281       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4282                          DAG.getConstant(c1 + c2, N1.getValueType()));
4283     }
4284   }
4285
4286   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4287   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4288       N0.getOperand(0).getOpcode() == ISD::SRL &&
4289       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4290     uint64_t c1 =
4291       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4292     uint64_t c2 = N1C->getZExtValue();
4293     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4294     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4295     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4296     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4297     if (c1 + OpSizeInBits == InnerShiftSize) {
4298       if (c1 + c2 >= InnerShiftSize)
4299         return DAG.getConstant(0, VT);
4300       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4301                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4302                                      N0.getOperand(0)->getOperand(0),
4303                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4304     }
4305   }
4306
4307   // fold (srl (shl x, c), c) -> (and x, cst2)
4308   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4309     unsigned BitSize = N0.getScalarValueSizeInBits();
4310     if (BitSize <= 64) {
4311       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4312       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4313                          DAG.getConstant(~0ULL >> ShAmt, VT));
4314     }
4315   }
4316
4317   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4318   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4319     // Shifting in all undef bits?
4320     EVT SmallVT = N0.getOperand(0).getValueType();
4321     unsigned BitSize = SmallVT.getScalarSizeInBits();
4322     if (N1C->getZExtValue() >= BitSize)
4323       return DAG.getUNDEF(VT);
4324
4325     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4326       uint64_t ShiftAmt = N1C->getZExtValue();
4327       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4328                                        N0.getOperand(0),
4329                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4330       AddToWorkList(SmallShift.getNode());
4331       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4332       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4333                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4334                          DAG.getConstant(Mask, VT));
4335     }
4336   }
4337
4338   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4339   // bit, which is unmodified by sra.
4340   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4341     if (N0.getOpcode() == ISD::SRA)
4342       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4343   }
4344
4345   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4346   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4347       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4348     APInt KnownZero, KnownOne;
4349     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4350
4351     // If any of the input bits are KnownOne, then the input couldn't be all
4352     // zeros, thus the result of the srl will always be zero.
4353     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4354
4355     // If all of the bits input the to ctlz node are known to be zero, then
4356     // the result of the ctlz is "32" and the result of the shift is one.
4357     APInt UnknownBits = ~KnownZero;
4358     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4359
4360     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4361     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4362       // Okay, we know that only that the single bit specified by UnknownBits
4363       // could be set on input to the CTLZ node. If this bit is set, the SRL
4364       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4365       // to an SRL/XOR pair, which is likely to simplify more.
4366       unsigned ShAmt = UnknownBits.countTrailingZeros();
4367       SDValue Op = N0.getOperand(0);
4368
4369       if (ShAmt) {
4370         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4371                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4372         AddToWorkList(Op.getNode());
4373       }
4374
4375       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4376                          Op, DAG.getConstant(1, VT));
4377     }
4378   }
4379
4380   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4381   if (N1.getOpcode() == ISD::TRUNCATE &&
4382       N1.getOperand(0).getOpcode() == ISD::AND) {
4383     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4384     if (NewOp1.getNode())
4385       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4386   }
4387
4388   // fold operands of srl based on knowledge that the low bits are not
4389   // demanded.
4390   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4391     return SDValue(N, 0);
4392
4393   if (N1C) {
4394     SDValue NewSRL = visitShiftByConstant(N, N1C);
4395     if (NewSRL.getNode())
4396       return NewSRL;
4397   }
4398
4399   // Attempt to convert a srl of a load into a narrower zero-extending load.
4400   SDValue NarrowLoad = ReduceLoadWidth(N);
4401   if (NarrowLoad.getNode())
4402     return NarrowLoad;
4403
4404   // Here is a common situation. We want to optimize:
4405   //
4406   //   %a = ...
4407   //   %b = and i32 %a, 2
4408   //   %c = srl i32 %b, 1
4409   //   brcond i32 %c ...
4410   //
4411   // into
4412   //
4413   //   %a = ...
4414   //   %b = and %a, 2
4415   //   %c = setcc eq %b, 0
4416   //   brcond %c ...
4417   //
4418   // However when after the source operand of SRL is optimized into AND, the SRL
4419   // itself may not be optimized further. Look for it and add the BRCOND into
4420   // the worklist.
4421   if (N->hasOneUse()) {
4422     SDNode *Use = *N->use_begin();
4423     if (Use->getOpcode() == ISD::BRCOND)
4424       AddToWorkList(Use);
4425     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4426       // Also look pass the truncate.
4427       Use = *Use->use_begin();
4428       if (Use->getOpcode() == ISD::BRCOND)
4429         AddToWorkList(Use);
4430     }
4431   }
4432
4433   return SDValue();
4434 }
4435
4436 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4437   SDValue N0 = N->getOperand(0);
4438   EVT VT = N->getValueType(0);
4439
4440   // fold (ctlz c1) -> c2
4441   if (isa<ConstantSDNode>(N0))
4442     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4443   return SDValue();
4444 }
4445
4446 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4447   SDValue N0 = N->getOperand(0);
4448   EVT VT = N->getValueType(0);
4449
4450   // fold (ctlz_zero_undef c1) -> c2
4451   if (isa<ConstantSDNode>(N0))
4452     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4453   return SDValue();
4454 }
4455
4456 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4457   SDValue N0 = N->getOperand(0);
4458   EVT VT = N->getValueType(0);
4459
4460   // fold (cttz c1) -> c2
4461   if (isa<ConstantSDNode>(N0))
4462     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4463   return SDValue();
4464 }
4465
4466 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4467   SDValue N0 = N->getOperand(0);
4468   EVT VT = N->getValueType(0);
4469
4470   // fold (cttz_zero_undef c1) -> c2
4471   if (isa<ConstantSDNode>(N0))
4472     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4473   return SDValue();
4474 }
4475
4476 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4477   SDValue N0 = N->getOperand(0);
4478   EVT VT = N->getValueType(0);
4479
4480   // fold (ctpop c1) -> c2
4481   if (isa<ConstantSDNode>(N0))
4482     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4483   return SDValue();
4484 }
4485
4486 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4487   SDValue N0 = N->getOperand(0);
4488   SDValue N1 = N->getOperand(1);
4489   SDValue N2 = N->getOperand(2);
4490   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4491   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4492   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4493   EVT VT = N->getValueType(0);
4494   EVT VT0 = N0.getValueType();
4495
4496   // fold (select C, X, X) -> X
4497   if (N1 == N2)
4498     return N1;
4499   // fold (select true, X, Y) -> X
4500   if (N0C && !N0C->isNullValue())
4501     return N1;
4502   // fold (select false, X, Y) -> Y
4503   if (N0C && N0C->isNullValue())
4504     return N2;
4505   // fold (select C, 1, X) -> (or C, X)
4506   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4507     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4508   // fold (select C, 0, 1) -> (xor C, 1)
4509   if (VT.isInteger() &&
4510       (VT0 == MVT::i1 ||
4511        (VT0.isInteger() &&
4512         TLI.getBooleanContents(false) ==
4513         TargetLowering::ZeroOrOneBooleanContent)) &&
4514       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4515     SDValue XORNode;
4516     if (VT == VT0)
4517       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4518                          N0, DAG.getConstant(1, VT0));
4519     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4520                           N0, DAG.getConstant(1, VT0));
4521     AddToWorkList(XORNode.getNode());
4522     if (VT.bitsGT(VT0))
4523       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4524     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4525   }
4526   // fold (select C, 0, X) -> (and (not C), X)
4527   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4528     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4529     AddToWorkList(NOTNode.getNode());
4530     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4531   }
4532   // fold (select C, X, 1) -> (or (not C), X)
4533   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4534     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4535     AddToWorkList(NOTNode.getNode());
4536     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4537   }
4538   // fold (select C, X, 0) -> (and C, X)
4539   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4540     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4541   // fold (select X, X, Y) -> (or X, Y)
4542   // fold (select X, 1, Y) -> (or X, Y)
4543   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4544     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4545   // fold (select X, Y, X) -> (and X, Y)
4546   // fold (select X, Y, 0) -> (and X, Y)
4547   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4548     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4549
4550   // If we can fold this based on the true/false value, do so.
4551   if (SimplifySelectOps(N, N1, N2))
4552     return SDValue(N, 0);  // Don't revisit N.
4553
4554   // fold selects based on a setcc into other things, such as min/max/abs
4555   if (N0.getOpcode() == ISD::SETCC) {
4556     // FIXME:
4557     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4558     // having to say they don't support SELECT_CC on every type the DAG knows
4559     // about, since there is no way to mark an opcode illegal at all value types
4560     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4561         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4562       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4563                          N0.getOperand(0), N0.getOperand(1),
4564                          N1, N2, N0.getOperand(2));
4565     return SimplifySelect(SDLoc(N), N0, N1, N2);
4566   }
4567
4568   return SDValue();
4569 }
4570
4571 static
4572 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4573   SDLoc DL(N);
4574   EVT LoVT, HiVT;
4575   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4576
4577   // Split the inputs.
4578   SDValue Lo, Hi, LL, LH, RL, RH;
4579   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4580   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4581
4582   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4583   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4584
4585   return std::make_pair(Lo, Hi);
4586 }
4587
4588 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4589   SDValue N0 = N->getOperand(0);
4590   SDValue N1 = N->getOperand(1);
4591   SDValue N2 = N->getOperand(2);
4592   SDLoc DL(N);
4593
4594   // Canonicalize integer abs.
4595   // vselect (setg[te] X,  0),  X, -X ->
4596   // vselect (setgt    X, -1),  X, -X ->
4597   // vselect (setl[te] X,  0), -X,  X ->
4598   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4599   if (N0.getOpcode() == ISD::SETCC) {
4600     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4601     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4602     bool isAbs = false;
4603     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4604
4605     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4606          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4607         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4608       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4609     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4610              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4611       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4612
4613     if (isAbs) {
4614       EVT VT = LHS.getValueType();
4615       SDValue Shift = DAG.getNode(
4616           ISD::SRA, DL, VT, LHS,
4617           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4618       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4619       AddToWorkList(Shift.getNode());
4620       AddToWorkList(Add.getNode());
4621       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4622     }
4623   }
4624
4625   // If the VSELECT result requires splitting and the mask is provided by a
4626   // SETCC, then split both nodes and its operands before legalization. This
4627   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4628   // and enables future optimizations (e.g. min/max pattern matching on X86).
4629   if (N0.getOpcode() == ISD::SETCC) {
4630     EVT VT = N->getValueType(0);
4631
4632     // Check if any splitting is required.
4633     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4634         TargetLowering::TypeSplitVector)
4635       return SDValue();
4636
4637     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4638     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4639     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4640     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4641
4642     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4643     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4644
4645     // Add the new VSELECT nodes to the work list in case they need to be split
4646     // again.
4647     AddToWorkList(Lo.getNode());
4648     AddToWorkList(Hi.getNode());
4649
4650     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4651   }
4652
4653   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4654   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4655     return N1;
4656   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4657   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4658     return N2;
4659
4660   return SDValue();
4661 }
4662
4663 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4664   SDValue N0 = N->getOperand(0);
4665   SDValue N1 = N->getOperand(1);
4666   SDValue N2 = N->getOperand(2);
4667   SDValue N3 = N->getOperand(3);
4668   SDValue N4 = N->getOperand(4);
4669   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4670
4671   // fold select_cc lhs, rhs, x, x, cc -> x
4672   if (N2 == N3)
4673     return N2;
4674
4675   // Determine if the condition we're dealing with is constant
4676   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4677                               N0, N1, CC, SDLoc(N), false);
4678   if (SCC.getNode()) {
4679     AddToWorkList(SCC.getNode());
4680
4681     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4682       if (!SCCC->isNullValue())
4683         return N2;    // cond always true -> true val
4684       else
4685         return N3;    // cond always false -> false val
4686     }
4687
4688     // Fold to a simpler select_cc
4689     if (SCC.getOpcode() == ISD::SETCC)
4690       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4691                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4692                          SCC.getOperand(2));
4693   }
4694
4695   // If we can fold this based on the true/false value, do so.
4696   if (SimplifySelectOps(N, N2, N3))
4697     return SDValue(N, 0);  // Don't revisit N.
4698
4699   // fold select_cc into other things, such as min/max/abs
4700   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4701 }
4702
4703 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4704   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4705                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4706                        SDLoc(N));
4707 }
4708
4709 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4710 // dag node into a ConstantSDNode or a build_vector of constants.
4711 // This function is called by the DAGCombiner when visiting sext/zext/aext
4712 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4713 // Vector extends are not folded if operations are legal; this is to
4714 // avoid introducing illegal build_vector dag nodes.
4715 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4716                                          SelectionDAG &DAG, bool LegalTypes,
4717                                          bool LegalOperations) {
4718   unsigned Opcode = N->getOpcode();
4719   SDValue N0 = N->getOperand(0);
4720   EVT VT = N->getValueType(0);
4721
4722   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4723          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4724
4725   // fold (sext c1) -> c1
4726   // fold (zext c1) -> c1
4727   // fold (aext c1) -> c1
4728   if (isa<ConstantSDNode>(N0))
4729     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4730
4731   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4732   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4733   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4734   EVT SVT = VT.getScalarType();
4735   if (!(VT.isVector() &&
4736       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4737       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4738     return nullptr;
4739   
4740   // We can fold this node into a build_vector.
4741   unsigned VTBits = SVT.getSizeInBits();
4742   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4743   unsigned ShAmt = VTBits - EVTBits;
4744   SmallVector<SDValue, 8> Elts;
4745   unsigned NumElts = N0->getNumOperands();
4746   SDLoc DL(N);
4747
4748   for (unsigned i=0; i != NumElts; ++i) {
4749     SDValue Op = N0->getOperand(i);
4750     if (Op->getOpcode() == ISD::UNDEF) {
4751       Elts.push_back(DAG.getUNDEF(SVT));
4752       continue;
4753     }
4754
4755     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4756     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4757     if (Opcode == ISD::SIGN_EXTEND)
4758       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4759                                      SVT));
4760     else
4761       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4762                                      SVT));
4763   }
4764
4765   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4766 }
4767
4768 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4769 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4770 // transformation. Returns true if extension are possible and the above
4771 // mentioned transformation is profitable.
4772 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4773                                     unsigned ExtOpc,
4774                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4775                                     const TargetLowering &TLI) {
4776   bool HasCopyToRegUses = false;
4777   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4778   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4779                             UE = N0.getNode()->use_end();
4780        UI != UE; ++UI) {
4781     SDNode *User = *UI;
4782     if (User == N)
4783       continue;
4784     if (UI.getUse().getResNo() != N0.getResNo())
4785       continue;
4786     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4787     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4788       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4789       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4790         // Sign bits will be lost after a zext.
4791         return false;
4792       bool Add = false;
4793       for (unsigned i = 0; i != 2; ++i) {
4794         SDValue UseOp = User->getOperand(i);
4795         if (UseOp == N0)
4796           continue;
4797         if (!isa<ConstantSDNode>(UseOp))
4798           return false;
4799         Add = true;
4800       }
4801       if (Add)
4802         ExtendNodes.push_back(User);
4803       continue;
4804     }
4805     // If truncates aren't free and there are users we can't
4806     // extend, it isn't worthwhile.
4807     if (!isTruncFree)
4808       return false;
4809     // Remember if this value is live-out.
4810     if (User->getOpcode() == ISD::CopyToReg)
4811       HasCopyToRegUses = true;
4812   }
4813
4814   if (HasCopyToRegUses) {
4815     bool BothLiveOut = false;
4816     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4817          UI != UE; ++UI) {
4818       SDUse &Use = UI.getUse();
4819       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4820         BothLiveOut = true;
4821         break;
4822       }
4823     }
4824     if (BothLiveOut)
4825       // Both unextended and extended values are live out. There had better be
4826       // a good reason for the transformation.
4827       return ExtendNodes.size();
4828   }
4829   return true;
4830 }
4831
4832 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4833                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4834                                   ISD::NodeType ExtType) {
4835   // Extend SetCC uses if necessary.
4836   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4837     SDNode *SetCC = SetCCs[i];
4838     SmallVector<SDValue, 4> Ops;
4839
4840     for (unsigned j = 0; j != 2; ++j) {
4841       SDValue SOp = SetCC->getOperand(j);
4842       if (SOp == Trunc)
4843         Ops.push_back(ExtLoad);
4844       else
4845         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4846     }
4847
4848     Ops.push_back(SetCC->getOperand(2));
4849     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4850                                  &Ops[0], Ops.size()));
4851   }
4852 }
4853
4854 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4855   SDValue N0 = N->getOperand(0);
4856   EVT VT = N->getValueType(0);
4857
4858   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4859                                               LegalOperations))
4860     return SDValue(Res, 0);
4861
4862   // fold (sext (sext x)) -> (sext x)
4863   // fold (sext (aext x)) -> (sext x)
4864   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4865     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4866                        N0.getOperand(0));
4867
4868   if (N0.getOpcode() == ISD::TRUNCATE) {
4869     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4870     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4871     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4872     if (NarrowLoad.getNode()) {
4873       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4874       if (NarrowLoad.getNode() != N0.getNode()) {
4875         CombineTo(N0.getNode(), NarrowLoad);
4876         // CombineTo deleted the truncate, if needed, but not what's under it.
4877         AddToWorkList(oye);
4878       }
4879       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4880     }
4881
4882     // See if the value being truncated is already sign extended.  If so, just
4883     // eliminate the trunc/sext pair.
4884     SDValue Op = N0.getOperand(0);
4885     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4886     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4887     unsigned DestBits = VT.getScalarType().getSizeInBits();
4888     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4889
4890     if (OpBits == DestBits) {
4891       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4892       // bits, it is already ready.
4893       if (NumSignBits > DestBits-MidBits)
4894         return Op;
4895     } else if (OpBits < DestBits) {
4896       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4897       // bits, just sext from i32.
4898       if (NumSignBits > OpBits-MidBits)
4899         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4900     } else {
4901       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4902       // bits, just truncate to i32.
4903       if (NumSignBits > OpBits-MidBits)
4904         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4905     }
4906
4907     // fold (sext (truncate x)) -> (sextinreg x).
4908     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4909                                                  N0.getValueType())) {
4910       if (OpBits < DestBits)
4911         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4912       else if (OpBits > DestBits)
4913         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4914       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4915                          DAG.getValueType(N0.getValueType()));
4916     }
4917   }
4918
4919   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4920   // None of the supported targets knows how to perform load and sign extend
4921   // on vectors in one instruction.  We only perform this transformation on
4922   // scalars.
4923   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4924       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4925       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4926        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4927     bool DoXform = true;
4928     SmallVector<SDNode*, 4> SetCCs;
4929     if (!N0.hasOneUse())
4930       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4931     if (DoXform) {
4932       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4933       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4934                                        LN0->getChain(),
4935                                        LN0->getBasePtr(), N0.getValueType(),
4936                                        LN0->getMemOperand());
4937       CombineTo(N, ExtLoad);
4938       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4939                                   N0.getValueType(), ExtLoad);
4940       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4941       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4942                       ISD::SIGN_EXTEND);
4943       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4944     }
4945   }
4946
4947   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4948   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4949   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4950       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4951     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4952     EVT MemVT = LN0->getMemoryVT();
4953     if ((!LegalOperations && !LN0->isVolatile()) ||
4954         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4955       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4956                                        LN0->getChain(),
4957                                        LN0->getBasePtr(), MemVT,
4958                                        LN0->getMemOperand());
4959       CombineTo(N, ExtLoad);
4960       CombineTo(N0.getNode(),
4961                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4962                             N0.getValueType(), ExtLoad),
4963                 ExtLoad.getValue(1));
4964       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4965     }
4966   }
4967
4968   // fold (sext (and/or/xor (load x), cst)) ->
4969   //      (and/or/xor (sextload x), (sext cst))
4970   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4971        N0.getOpcode() == ISD::XOR) &&
4972       isa<LoadSDNode>(N0.getOperand(0)) &&
4973       N0.getOperand(1).getOpcode() == ISD::Constant &&
4974       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4975       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4976     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4977     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4978       bool DoXform = true;
4979       SmallVector<SDNode*, 4> SetCCs;
4980       if (!N0.hasOneUse())
4981         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4982                                           SetCCs, TLI);
4983       if (DoXform) {
4984         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4985                                          LN0->getChain(), LN0->getBasePtr(),
4986                                          LN0->getMemoryVT(),
4987                                          LN0->getMemOperand());
4988         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4989         Mask = Mask.sext(VT.getSizeInBits());
4990         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4991                                   ExtLoad, DAG.getConstant(Mask, VT));
4992         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4993                                     SDLoc(N0.getOperand(0)),
4994                                     N0.getOperand(0).getValueType(), ExtLoad);
4995         CombineTo(N, And);
4996         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4997         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4998                         ISD::SIGN_EXTEND);
4999         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5000       }
5001     }
5002   }
5003
5004   if (N0.getOpcode() == ISD::SETCC) {
5005     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5006     // Only do this before legalize for now.
5007     if (VT.isVector() && !LegalOperations &&
5008         TLI.getBooleanContents(true) ==
5009           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5010       EVT N0VT = N0.getOperand(0).getValueType();
5011       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5012       // of the same size as the compared operands. Only optimize sext(setcc())
5013       // if this is the case.
5014       EVT SVT = getSetCCResultType(N0VT);
5015
5016       // We know that the # elements of the results is the same as the
5017       // # elements of the compare (and the # elements of the compare result
5018       // for that matter).  Check to see that they are the same size.  If so,
5019       // we know that the element size of the sext'd result matches the
5020       // element size of the compare operands.
5021       if (VT.getSizeInBits() == SVT.getSizeInBits())
5022         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5023                              N0.getOperand(1),
5024                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5025
5026       // If the desired elements are smaller or larger than the source
5027       // elements we can use a matching integer vector type and then
5028       // truncate/sign extend
5029       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5030       if (SVT == MatchingVectorType) {
5031         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5032                                N0.getOperand(0), N0.getOperand(1),
5033                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5034         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5035       }
5036     }
5037
5038     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5039     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5040     SDValue NegOne =
5041       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5042     SDValue SCC =
5043       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5044                        NegOne, DAG.getConstant(0, VT),
5045                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5046     if (SCC.getNode()) return SCC;
5047
5048     if (!VT.isVector()) {
5049       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5050       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5051         SDLoc DL(N);
5052         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5053         SDValue SetCC = DAG.getSetCC(DL,
5054                                      SetCCVT,
5055                                      N0.getOperand(0), N0.getOperand(1), CC);
5056         EVT SelectVT = getSetCCResultType(VT);
5057         return DAG.getSelect(DL, VT,
5058                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5059                              NegOne, DAG.getConstant(0, VT));
5060
5061       }
5062     }
5063   }
5064
5065   // fold (sext x) -> (zext x) if the sign bit is known zero.
5066   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5067       DAG.SignBitIsZero(N0))
5068     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5069
5070   return SDValue();
5071 }
5072
5073 // isTruncateOf - If N is a truncate of some other value, return true, record
5074 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5075 // This function computes KnownZero to avoid a duplicated call to
5076 // ComputeMaskedBits in the caller.
5077 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5078                          APInt &KnownZero) {
5079   APInt KnownOne;
5080   if (N->getOpcode() == ISD::TRUNCATE) {
5081     Op = N->getOperand(0);
5082     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5083     return true;
5084   }
5085
5086   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5087       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5088     return false;
5089
5090   SDValue Op0 = N->getOperand(0);
5091   SDValue Op1 = N->getOperand(1);
5092   assert(Op0.getValueType() == Op1.getValueType());
5093
5094   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5095   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5096   if (COp0 && COp0->isNullValue())
5097     Op = Op1;
5098   else if (COp1 && COp1->isNullValue())
5099     Op = Op0;
5100   else
5101     return false;
5102
5103   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5104
5105   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5106     return false;
5107
5108   return true;
5109 }
5110
5111 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5112   SDValue N0 = N->getOperand(0);
5113   EVT VT = N->getValueType(0);
5114
5115   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5116                                               LegalOperations))
5117     return SDValue(Res, 0);
5118
5119   // fold (zext (zext x)) -> (zext x)
5120   // fold (zext (aext x)) -> (zext x)
5121   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5122     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5123                        N0.getOperand(0));
5124
5125   // fold (zext (truncate x)) -> (zext x) or
5126   //      (zext (truncate x)) -> (truncate x)
5127   // This is valid when the truncated bits of x are already zero.
5128   // FIXME: We should extend this to work for vectors too.
5129   SDValue Op;
5130   APInt KnownZero;
5131   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5132     APInt TruncatedBits =
5133       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5134       APInt(Op.getValueSizeInBits(), 0) :
5135       APInt::getBitsSet(Op.getValueSizeInBits(),
5136                         N0.getValueSizeInBits(),
5137                         std::min(Op.getValueSizeInBits(),
5138                                  VT.getSizeInBits()));
5139     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5140       if (VT.bitsGT(Op.getValueType()))
5141         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5142       if (VT.bitsLT(Op.getValueType()))
5143         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5144
5145       return Op;
5146     }
5147   }
5148
5149   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5150   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5151   if (N0.getOpcode() == ISD::TRUNCATE) {
5152     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5153     if (NarrowLoad.getNode()) {
5154       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5155       if (NarrowLoad.getNode() != N0.getNode()) {
5156         CombineTo(N0.getNode(), NarrowLoad);
5157         // CombineTo deleted the truncate, if needed, but not what's under it.
5158         AddToWorkList(oye);
5159       }
5160       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5161     }
5162   }
5163
5164   // fold (zext (truncate x)) -> (and x, mask)
5165   if (N0.getOpcode() == ISD::TRUNCATE &&
5166       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5167
5168     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5169     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5170     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5171     if (NarrowLoad.getNode()) {
5172       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5173       if (NarrowLoad.getNode() != N0.getNode()) {
5174         CombineTo(N0.getNode(), NarrowLoad);
5175         // CombineTo deleted the truncate, if needed, but not what's under it.
5176         AddToWorkList(oye);
5177       }
5178       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5179     }
5180
5181     SDValue Op = N0.getOperand(0);
5182     if (Op.getValueType().bitsLT(VT)) {
5183       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5184       AddToWorkList(Op.getNode());
5185     } else if (Op.getValueType().bitsGT(VT)) {
5186       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5187       AddToWorkList(Op.getNode());
5188     }
5189     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5190                                   N0.getValueType().getScalarType());
5191   }
5192
5193   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5194   // if either of the casts is not free.
5195   if (N0.getOpcode() == ISD::AND &&
5196       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5197       N0.getOperand(1).getOpcode() == ISD::Constant &&
5198       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5199                            N0.getValueType()) ||
5200        !TLI.isZExtFree(N0.getValueType(), VT))) {
5201     SDValue X = N0.getOperand(0).getOperand(0);
5202     if (X.getValueType().bitsLT(VT)) {
5203       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5204     } else if (X.getValueType().bitsGT(VT)) {
5205       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5206     }
5207     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5208     Mask = Mask.zext(VT.getSizeInBits());
5209     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5210                        X, DAG.getConstant(Mask, VT));
5211   }
5212
5213   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5214   // None of the supported targets knows how to perform load and vector_zext
5215   // on vectors in one instruction.  We only perform this transformation on
5216   // scalars.
5217   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5218       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5219       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5220        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5221     bool DoXform = true;
5222     SmallVector<SDNode*, 4> SetCCs;
5223     if (!N0.hasOneUse())
5224       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5225     if (DoXform) {
5226       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5227       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5228                                        LN0->getChain(),
5229                                        LN0->getBasePtr(), N0.getValueType(),
5230                                        LN0->getMemOperand());
5231       CombineTo(N, ExtLoad);
5232       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5233                                   N0.getValueType(), ExtLoad);
5234       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5235
5236       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5237                       ISD::ZERO_EXTEND);
5238       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5239     }
5240   }
5241
5242   // fold (zext (and/or/xor (load x), cst)) ->
5243   //      (and/or/xor (zextload x), (zext cst))
5244   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5245        N0.getOpcode() == ISD::XOR) &&
5246       isa<LoadSDNode>(N0.getOperand(0)) &&
5247       N0.getOperand(1).getOpcode() == ISD::Constant &&
5248       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5249       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5250     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5251     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5252       bool DoXform = true;
5253       SmallVector<SDNode*, 4> SetCCs;
5254       if (!N0.hasOneUse())
5255         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5256                                           SetCCs, TLI);
5257       if (DoXform) {
5258         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5259                                          LN0->getChain(), LN0->getBasePtr(),
5260                                          LN0->getMemoryVT(),
5261                                          LN0->getMemOperand());
5262         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5263         Mask = Mask.zext(VT.getSizeInBits());
5264         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5265                                   ExtLoad, DAG.getConstant(Mask, VT));
5266         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5267                                     SDLoc(N0.getOperand(0)),
5268                                     N0.getOperand(0).getValueType(), ExtLoad);
5269         CombineTo(N, And);
5270         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5271         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5272                         ISD::ZERO_EXTEND);
5273         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5274       }
5275     }
5276   }
5277
5278   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5279   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5280   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5281       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5282     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5283     EVT MemVT = LN0->getMemoryVT();
5284     if ((!LegalOperations && !LN0->isVolatile()) ||
5285         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5286       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5287                                        LN0->getChain(),
5288                                        LN0->getBasePtr(), MemVT,
5289                                        LN0->getMemOperand());
5290       CombineTo(N, ExtLoad);
5291       CombineTo(N0.getNode(),
5292                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5293                             ExtLoad),
5294                 ExtLoad.getValue(1));
5295       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5296     }
5297   }
5298
5299   if (N0.getOpcode() == ISD::SETCC) {
5300     if (!LegalOperations && VT.isVector() &&
5301         N0.getValueType().getVectorElementType() == MVT::i1) {
5302       EVT N0VT = N0.getOperand(0).getValueType();
5303       if (getSetCCResultType(N0VT) == N0.getValueType())
5304         return SDValue();
5305
5306       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5307       // Only do this before legalize for now.
5308       EVT EltVT = VT.getVectorElementType();
5309       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5310                                     DAG.getConstant(1, EltVT));
5311       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5312         // We know that the # elements of the results is the same as the
5313         // # elements of the compare (and the # elements of the compare result
5314         // for that matter).  Check to see that they are the same size.  If so,
5315         // we know that the element size of the sext'd result matches the
5316         // element size of the compare operands.
5317         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5318                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5319                                          N0.getOperand(1),
5320                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5321                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5322                                        &OneOps[0], OneOps.size()));
5323
5324       // If the desired elements are smaller or larger than the source
5325       // elements we can use a matching integer vector type and then
5326       // truncate/sign extend
5327       EVT MatchingElementType =
5328         EVT::getIntegerVT(*DAG.getContext(),
5329                           N0VT.getScalarType().getSizeInBits());
5330       EVT MatchingVectorType =
5331         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5332                          N0VT.getVectorNumElements());
5333       SDValue VsetCC =
5334         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5335                       N0.getOperand(1),
5336                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5337       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5338                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5339                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5340                                      &OneOps[0], OneOps.size()));
5341     }
5342
5343     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5344     SDValue SCC =
5345       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5346                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5347                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5348     if (SCC.getNode()) return SCC;
5349   }
5350
5351   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5352   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5353       isa<ConstantSDNode>(N0.getOperand(1)) &&
5354       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5355       N0.hasOneUse()) {
5356     SDValue ShAmt = N0.getOperand(1);
5357     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5358     if (N0.getOpcode() == ISD::SHL) {
5359       SDValue InnerZExt = N0.getOperand(0);
5360       // If the original shl may be shifting out bits, do not perform this
5361       // transformation.
5362       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5363         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5364       if (ShAmtVal > KnownZeroBits)
5365         return SDValue();
5366     }
5367
5368     SDLoc DL(N);
5369
5370     // Ensure that the shift amount is wide enough for the shifted value.
5371     if (VT.getSizeInBits() >= 256)
5372       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5373
5374     return DAG.getNode(N0.getOpcode(), DL, VT,
5375                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5376                        ShAmt);
5377   }
5378
5379   return SDValue();
5380 }
5381
5382 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5383   SDValue N0 = N->getOperand(0);
5384   EVT VT = N->getValueType(0);
5385
5386   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5387                                               LegalOperations))
5388     return SDValue(Res, 0);
5389
5390   // fold (aext (aext x)) -> (aext x)
5391   // fold (aext (zext x)) -> (zext x)
5392   // fold (aext (sext x)) -> (sext x)
5393   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5394       N0.getOpcode() == ISD::ZERO_EXTEND ||
5395       N0.getOpcode() == ISD::SIGN_EXTEND)
5396     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5397
5398   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5399   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5400   if (N0.getOpcode() == ISD::TRUNCATE) {
5401     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5402     if (NarrowLoad.getNode()) {
5403       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5404       if (NarrowLoad.getNode() != N0.getNode()) {
5405         CombineTo(N0.getNode(), NarrowLoad);
5406         // CombineTo deleted the truncate, if needed, but not what's under it.
5407         AddToWorkList(oye);
5408       }
5409       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5410     }
5411   }
5412
5413   // fold (aext (truncate x))
5414   if (N0.getOpcode() == ISD::TRUNCATE) {
5415     SDValue TruncOp = N0.getOperand(0);
5416     if (TruncOp.getValueType() == VT)
5417       return TruncOp; // x iff x size == zext size.
5418     if (TruncOp.getValueType().bitsGT(VT))
5419       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5420     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5421   }
5422
5423   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5424   // if the trunc is not free.
5425   if (N0.getOpcode() == ISD::AND &&
5426       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5427       N0.getOperand(1).getOpcode() == ISD::Constant &&
5428       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5429                           N0.getValueType())) {
5430     SDValue X = N0.getOperand(0).getOperand(0);
5431     if (X.getValueType().bitsLT(VT)) {
5432       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5433     } else if (X.getValueType().bitsGT(VT)) {
5434       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5435     }
5436     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5437     Mask = Mask.zext(VT.getSizeInBits());
5438     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5439                        X, DAG.getConstant(Mask, VT));
5440   }
5441
5442   // fold (aext (load x)) -> (aext (truncate (extload x)))
5443   // None of the supported targets knows how to perform load and any_ext
5444   // on vectors in one instruction.  We only perform this transformation on
5445   // scalars.
5446   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5447       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5448       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5449        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5450     bool DoXform = true;
5451     SmallVector<SDNode*, 4> SetCCs;
5452     if (!N0.hasOneUse())
5453       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5454     if (DoXform) {
5455       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5456       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5457                                        LN0->getChain(),
5458                                        LN0->getBasePtr(), N0.getValueType(),
5459                                        LN0->getMemOperand());
5460       CombineTo(N, ExtLoad);
5461       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5462                                   N0.getValueType(), ExtLoad);
5463       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5464       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5465                       ISD::ANY_EXTEND);
5466       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5467     }
5468   }
5469
5470   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5471   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5472   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5473   if (N0.getOpcode() == ISD::LOAD &&
5474       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5475       N0.hasOneUse()) {
5476     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5477     ISD::LoadExtType ExtType = LN0->getExtensionType();
5478     EVT MemVT = LN0->getMemoryVT();
5479     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5480       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5481                                        VT, LN0->getChain(), LN0->getBasePtr(),
5482                                        MemVT, LN0->getMemOperand());
5483       CombineTo(N, ExtLoad);
5484       CombineTo(N0.getNode(),
5485                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5486                             N0.getValueType(), ExtLoad),
5487                 ExtLoad.getValue(1));
5488       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5489     }
5490   }
5491
5492   if (N0.getOpcode() == ISD::SETCC) {
5493     // For vectors:
5494     // aext(setcc) -> vsetcc
5495     // aext(setcc) -> truncate(vsetcc)
5496     // aext(setcc) -> aext(vsetcc)
5497     // Only do this before legalize for now.
5498     if (VT.isVector() && !LegalOperations) {
5499       EVT N0VT = N0.getOperand(0).getValueType();
5500         // We know that the # elements of the results is the same as the
5501         // # elements of the compare (and the # elements of the compare result
5502         // for that matter).  Check to see that they are the same size.  If so,
5503         // we know that the element size of the sext'd result matches the
5504         // element size of the compare operands.
5505       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5506         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5507                              N0.getOperand(1),
5508                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5509       // If the desired elements are smaller or larger than the source
5510       // elements we can use a matching integer vector type and then
5511       // truncate/any extend
5512       else {
5513         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5514         SDValue VsetCC =
5515           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5516                         N0.getOperand(1),
5517                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5518         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5519       }
5520     }
5521
5522     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5523     SDValue SCC =
5524       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5525                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5526                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5527     if (SCC.getNode())
5528       return SCC;
5529   }
5530
5531   return SDValue();
5532 }
5533
5534 /// GetDemandedBits - See if the specified operand can be simplified with the
5535 /// knowledge that only the bits specified by Mask are used.  If so, return the
5536 /// simpler operand, otherwise return a null SDValue.
5537 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5538   switch (V.getOpcode()) {
5539   default: break;
5540   case ISD::Constant: {
5541     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5542     assert(CV && "Const value should be ConstSDNode.");
5543     const APInt &CVal = CV->getAPIntValue();
5544     APInt NewVal = CVal & Mask;
5545     if (NewVal != CVal)
5546       return DAG.getConstant(NewVal, V.getValueType());
5547     break;
5548   }
5549   case ISD::OR:
5550   case ISD::XOR:
5551     // If the LHS or RHS don't contribute bits to the or, drop them.
5552     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5553       return V.getOperand(1);
5554     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5555       return V.getOperand(0);
5556     break;
5557   case ISD::SRL:
5558     // Only look at single-use SRLs.
5559     if (!V.getNode()->hasOneUse())
5560       break;
5561     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5562       // See if we can recursively simplify the LHS.
5563       unsigned Amt = RHSC->getZExtValue();
5564
5565       // Watch out for shift count overflow though.
5566       if (Amt >= Mask.getBitWidth()) break;
5567       APInt NewMask = Mask << Amt;
5568       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5569       if (SimplifyLHS.getNode())
5570         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5571                            SimplifyLHS, V.getOperand(1));
5572     }
5573   }
5574   return SDValue();
5575 }
5576
5577 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5578 /// bits and then truncated to a narrower type and where N is a multiple
5579 /// of number of bits of the narrower type, transform it to a narrower load
5580 /// from address + N / num of bits of new type. If the result is to be
5581 /// extended, also fold the extension to form a extending load.
5582 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5583   unsigned Opc = N->getOpcode();
5584
5585   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5586   SDValue N0 = N->getOperand(0);
5587   EVT VT = N->getValueType(0);
5588   EVT ExtVT = VT;
5589
5590   // This transformation isn't valid for vector loads.
5591   if (VT.isVector())
5592     return SDValue();
5593
5594   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5595   // extended to VT.
5596   if (Opc == ISD::SIGN_EXTEND_INREG) {
5597     ExtType = ISD::SEXTLOAD;
5598     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5599   } else if (Opc == ISD::SRL) {
5600     // Another special-case: SRL is basically zero-extending a narrower value.
5601     ExtType = ISD::ZEXTLOAD;
5602     N0 = SDValue(N, 0);
5603     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5604     if (!N01) return SDValue();
5605     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5606                               VT.getSizeInBits() - N01->getZExtValue());
5607   }
5608   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5609     return SDValue();
5610
5611   unsigned EVTBits = ExtVT.getSizeInBits();
5612
5613   // Do not generate loads of non-round integer types since these can
5614   // be expensive (and would be wrong if the type is not byte sized).
5615   if (!ExtVT.isRound())
5616     return SDValue();
5617
5618   unsigned ShAmt = 0;
5619   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5620     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5621       ShAmt = N01->getZExtValue();
5622       // Is the shift amount a multiple of size of VT?
5623       if ((ShAmt & (EVTBits-1)) == 0) {
5624         N0 = N0.getOperand(0);
5625         // Is the load width a multiple of size of VT?
5626         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5627           return SDValue();
5628       }
5629
5630       // At this point, we must have a load or else we can't do the transform.
5631       if (!isa<LoadSDNode>(N0)) return SDValue();
5632
5633       // Because a SRL must be assumed to *need* to zero-extend the high bits
5634       // (as opposed to anyext the high bits), we can't combine the zextload
5635       // lowering of SRL and an sextload.
5636       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5637         return SDValue();
5638
5639       // If the shift amount is larger than the input type then we're not
5640       // accessing any of the loaded bytes.  If the load was a zextload/extload
5641       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5642       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5643         return SDValue();
5644     }
5645   }
5646
5647   // If the load is shifted left (and the result isn't shifted back right),
5648   // we can fold the truncate through the shift.
5649   unsigned ShLeftAmt = 0;
5650   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5651       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5652     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5653       ShLeftAmt = N01->getZExtValue();
5654       N0 = N0.getOperand(0);
5655     }
5656   }
5657
5658   // If we haven't found a load, we can't narrow it.  Don't transform one with
5659   // multiple uses, this would require adding a new load.
5660   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5661     return SDValue();
5662
5663   // Don't change the width of a volatile load.
5664   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5665   if (LN0->isVolatile())
5666     return SDValue();
5667
5668   // Verify that we are actually reducing a load width here.
5669   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5670     return SDValue();
5671
5672   // For the transform to be legal, the load must produce only two values
5673   // (the value loaded and the chain).  Don't transform a pre-increment
5674   // load, for example, which produces an extra value.  Otherwise the
5675   // transformation is not equivalent, and the downstream logic to replace
5676   // uses gets things wrong.
5677   if (LN0->getNumValues() > 2)
5678     return SDValue();
5679
5680   // If the load that we're shrinking is an extload and we're not just
5681   // discarding the extension we can't simply shrink the load. Bail.
5682   // TODO: It would be possible to merge the extensions in some cases.
5683   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5684       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5685     return SDValue();
5686
5687   EVT PtrType = N0.getOperand(1).getValueType();
5688
5689   if (PtrType == MVT::Untyped || PtrType.isExtended())
5690     // It's not possible to generate a constant of extended or untyped type.
5691     return SDValue();
5692
5693   // For big endian targets, we need to adjust the offset to the pointer to
5694   // load the correct bytes.
5695   if (TLI.isBigEndian()) {
5696     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5697     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5698     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5699   }
5700
5701   uint64_t PtrOff = ShAmt / 8;
5702   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5703   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5704                                PtrType, LN0->getBasePtr(),
5705                                DAG.getConstant(PtrOff, PtrType));
5706   AddToWorkList(NewPtr.getNode());
5707
5708   SDValue Load;
5709   if (ExtType == ISD::NON_EXTLOAD)
5710     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5711                         LN0->getPointerInfo().getWithOffset(PtrOff),
5712                         LN0->isVolatile(), LN0->isNonTemporal(),
5713                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5714   else
5715     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5716                           LN0->getPointerInfo().getWithOffset(PtrOff),
5717                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5718                           NewAlign, LN0->getTBAAInfo());
5719
5720   // Replace the old load's chain with the new load's chain.
5721   WorkListRemover DeadNodes(*this);
5722   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5723
5724   // Shift the result left, if we've swallowed a left shift.
5725   SDValue Result = Load;
5726   if (ShLeftAmt != 0) {
5727     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5728     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5729       ShImmTy = VT;
5730     // If the shift amount is as large as the result size (but, presumably,
5731     // no larger than the source) then the useful bits of the result are
5732     // zero; we can't simply return the shortened shift, because the result
5733     // of that operation is undefined.
5734     if (ShLeftAmt >= VT.getSizeInBits())
5735       Result = DAG.getConstant(0, VT);
5736     else
5737       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5738                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5739   }
5740
5741   // Return the new loaded value.
5742   return Result;
5743 }
5744
5745 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5746   SDValue N0 = N->getOperand(0);
5747   SDValue N1 = N->getOperand(1);
5748   EVT VT = N->getValueType(0);
5749   EVT EVT = cast<VTSDNode>(N1)->getVT();
5750   unsigned VTBits = VT.getScalarType().getSizeInBits();
5751   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5752
5753   // fold (sext_in_reg c1) -> c1
5754   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5755     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5756
5757   // If the input is already sign extended, just drop the extension.
5758   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5759     return N0;
5760
5761   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5762   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5763       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5764     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5765                        N0.getOperand(0), N1);
5766
5767   // fold (sext_in_reg (sext x)) -> (sext x)
5768   // fold (sext_in_reg (aext x)) -> (sext x)
5769   // if x is small enough.
5770   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5771     SDValue N00 = N0.getOperand(0);
5772     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5773         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5774       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5775   }
5776
5777   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5778   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5779     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5780
5781   // fold operands of sext_in_reg based on knowledge that the top bits are not
5782   // demanded.
5783   if (SimplifyDemandedBits(SDValue(N, 0)))
5784     return SDValue(N, 0);
5785
5786   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5787   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5788   SDValue NarrowLoad = ReduceLoadWidth(N);
5789   if (NarrowLoad.getNode())
5790     return NarrowLoad;
5791
5792   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5793   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5794   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5795   if (N0.getOpcode() == ISD::SRL) {
5796     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5797       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5798         // We can turn this into an SRA iff the input to the SRL is already sign
5799         // extended enough.
5800         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5801         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5802           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5803                              N0.getOperand(0), N0.getOperand(1));
5804       }
5805   }
5806
5807   // fold (sext_inreg (extload x)) -> (sextload x)
5808   if (ISD::isEXTLoad(N0.getNode()) &&
5809       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5810       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5811       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5812        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5813     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5814     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5815                                      LN0->getChain(),
5816                                      LN0->getBasePtr(), EVT,
5817                                      LN0->getMemOperand());
5818     CombineTo(N, ExtLoad);
5819     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5820     AddToWorkList(ExtLoad.getNode());
5821     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5822   }
5823   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5824   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5825       N0.hasOneUse() &&
5826       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5827       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5828        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5829     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5830     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5831                                      LN0->getChain(),
5832                                      LN0->getBasePtr(), EVT,
5833                                      LN0->getMemOperand());
5834     CombineTo(N, ExtLoad);
5835     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5836     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5837   }
5838
5839   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5840   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5841     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5842                                        N0.getOperand(1), false);
5843     if (BSwap.getNode())
5844       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5845                          BSwap, N1);
5846   }
5847
5848   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5849   // into a build_vector.
5850   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5851     SmallVector<SDValue, 8> Elts;
5852     unsigned NumElts = N0->getNumOperands();
5853     unsigned ShAmt = VTBits - EVTBits;
5854
5855     for (unsigned i = 0; i != NumElts; ++i) {
5856       SDValue Op = N0->getOperand(i);
5857       if (Op->getOpcode() == ISD::UNDEF) {
5858         Elts.push_back(Op);
5859         continue;
5860       }
5861
5862       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5863       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5864       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5865                                      Op.getValueType()));
5866     }
5867
5868     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5869   }
5870
5871   return SDValue();
5872 }
5873
5874 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5875   SDValue N0 = N->getOperand(0);
5876   EVT VT = N->getValueType(0);
5877   bool isLE = TLI.isLittleEndian();
5878
5879   // noop truncate
5880   if (N0.getValueType() == N->getValueType(0))
5881     return N0;
5882   // fold (truncate c1) -> c1
5883   if (isa<ConstantSDNode>(N0))
5884     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5885   // fold (truncate (truncate x)) -> (truncate x)
5886   if (N0.getOpcode() == ISD::TRUNCATE)
5887     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5888   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5889   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5890       N0.getOpcode() == ISD::SIGN_EXTEND ||
5891       N0.getOpcode() == ISD::ANY_EXTEND) {
5892     if (N0.getOperand(0).getValueType().bitsLT(VT))
5893       // if the source is smaller than the dest, we still need an extend
5894       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5895                          N0.getOperand(0));
5896     if (N0.getOperand(0).getValueType().bitsGT(VT))
5897       // if the source is larger than the dest, than we just need the truncate
5898       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5899     // if the source and dest are the same type, we can drop both the extend
5900     // and the truncate.
5901     return N0.getOperand(0);
5902   }
5903
5904   // Fold extract-and-trunc into a narrow extract. For example:
5905   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5906   //   i32 y = TRUNCATE(i64 x)
5907   //        -- becomes --
5908   //   v16i8 b = BITCAST (v2i64 val)
5909   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5910   //
5911   // Note: We only run this optimization after type legalization (which often
5912   // creates this pattern) and before operation legalization after which
5913   // we need to be more careful about the vector instructions that we generate.
5914   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5915       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5916
5917     EVT VecTy = N0.getOperand(0).getValueType();
5918     EVT ExTy = N0.getValueType();
5919     EVT TrTy = N->getValueType(0);
5920
5921     unsigned NumElem = VecTy.getVectorNumElements();
5922     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5923
5924     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5925     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5926
5927     SDValue EltNo = N0->getOperand(1);
5928     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5929       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5930       EVT IndexTy = TLI.getVectorIdxTy();
5931       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5932
5933       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5934                               NVT, N0.getOperand(0));
5935
5936       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5937                          SDLoc(N), TrTy, V,
5938                          DAG.getConstant(Index, IndexTy));
5939     }
5940   }
5941
5942   // Fold a series of buildvector, bitcast, and truncate if possible.
5943   // For example fold
5944   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5945   //   (2xi32 (buildvector x, y)).
5946   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5947       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5948       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5949       N0.getOperand(0).hasOneUse()) {
5950
5951     SDValue BuildVect = N0.getOperand(0);
5952     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5953     EVT TruncVecEltTy = VT.getVectorElementType();
5954
5955     // Check that the element types match.
5956     if (BuildVectEltTy == TruncVecEltTy) {
5957       // Now we only need to compute the offset of the truncated elements.
5958       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5959       unsigned TruncVecNumElts = VT.getVectorNumElements();
5960       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5961
5962       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5963              "Invalid number of elements");
5964
5965       SmallVector<SDValue, 8> Opnds;
5966       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5967         Opnds.push_back(BuildVect.getOperand(i));
5968
5969       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5970                          Opnds.size());
5971     }
5972   }
5973
5974   // See if we can simplify the input to this truncate through knowledge that
5975   // only the low bits are being used.
5976   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5977   // Currently we only perform this optimization on scalars because vectors
5978   // may have different active low bits.
5979   if (!VT.isVector()) {
5980     SDValue Shorter =
5981       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5982                                                VT.getSizeInBits()));
5983     if (Shorter.getNode())
5984       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5985   }
5986   // fold (truncate (load x)) -> (smaller load x)
5987   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5988   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5989     SDValue Reduced = ReduceLoadWidth(N);
5990     if (Reduced.getNode())
5991       return Reduced;
5992     // Handle the case where the load remains an extending load even
5993     // after truncation.
5994     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5995       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5996       if (!LN0->isVolatile() &&
5997           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5998         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5999                                          VT, LN0->getChain(), LN0->getBasePtr(),
6000                                          LN0->getMemoryVT(),
6001                                          LN0->getMemOperand());
6002         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6003         return NewLoad;
6004       }
6005     }
6006   }
6007   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6008   // where ... are all 'undef'.
6009   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6010     SmallVector<EVT, 8> VTs;
6011     SDValue V;
6012     unsigned Idx = 0;
6013     unsigned NumDefs = 0;
6014
6015     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6016       SDValue X = N0.getOperand(i);
6017       if (X.getOpcode() != ISD::UNDEF) {
6018         V = X;
6019         Idx = i;
6020         NumDefs++;
6021       }
6022       // Stop if more than one members are non-undef.
6023       if (NumDefs > 1)
6024         break;
6025       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6026                                      VT.getVectorElementType(),
6027                                      X.getValueType().getVectorNumElements()));
6028     }
6029
6030     if (NumDefs == 0)
6031       return DAG.getUNDEF(VT);
6032
6033     if (NumDefs == 1) {
6034       assert(V.getNode() && "The single defined operand is empty!");
6035       SmallVector<SDValue, 8> Opnds;
6036       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6037         if (i != Idx) {
6038           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6039           continue;
6040         }
6041         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6042         AddToWorkList(NV.getNode());
6043         Opnds.push_back(NV);
6044       }
6045       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6046                          &Opnds[0], Opnds.size());
6047     }
6048   }
6049
6050   // Simplify the operands using demanded-bits information.
6051   if (!VT.isVector() &&
6052       SimplifyDemandedBits(SDValue(N, 0)))
6053     return SDValue(N, 0);
6054
6055   return SDValue();
6056 }
6057
6058 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6059   SDValue Elt = N->getOperand(i);
6060   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6061     return Elt.getNode();
6062   return Elt.getOperand(Elt.getResNo()).getNode();
6063 }
6064
6065 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6066 /// if load locations are consecutive.
6067 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6068   assert(N->getOpcode() == ISD::BUILD_PAIR);
6069
6070   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6071   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6072   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6073       LD1->getAddressSpace() != LD2->getAddressSpace())
6074     return SDValue();
6075   EVT LD1VT = LD1->getValueType(0);
6076
6077   if (ISD::isNON_EXTLoad(LD2) &&
6078       LD2->hasOneUse() &&
6079       // If both are volatile this would reduce the number of volatile loads.
6080       // If one is volatile it might be ok, but play conservative and bail out.
6081       !LD1->isVolatile() &&
6082       !LD2->isVolatile() &&
6083       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6084     unsigned Align = LD1->getAlignment();
6085     unsigned NewAlign = TLI.getDataLayout()->
6086       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6087
6088     if (NewAlign <= Align &&
6089         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6090       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6091                          LD1->getBasePtr(), LD1->getPointerInfo(),
6092                          false, false, false, Align);
6093   }
6094
6095   return SDValue();
6096 }
6097
6098 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6099   SDValue N0 = N->getOperand(0);
6100   EVT VT = N->getValueType(0);
6101
6102   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6103   // Only do this before legalize, since afterward the target may be depending
6104   // on the bitconvert.
6105   // First check to see if this is all constant.
6106   if (!LegalTypes &&
6107       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6108       VT.isVector()) {
6109     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6110
6111     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6112     assert(!DestEltVT.isVector() &&
6113            "Element type of vector ValueType must not be vector!");
6114     if (isSimple)
6115       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6116   }
6117
6118   // If the input is a constant, let getNode fold it.
6119   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6120     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6121     if (Res.getNode() != N) {
6122       if (!LegalOperations ||
6123           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6124         return Res;
6125
6126       // Folding it resulted in an illegal node, and it's too late to
6127       // do that. Clean up the old node and forego the transformation.
6128       // Ideally this won't happen very often, because instcombine
6129       // and the earlier dagcombine runs (where illegal nodes are
6130       // permitted) should have folded most of them already.
6131       DAG.DeleteNode(Res.getNode());
6132     }
6133   }
6134
6135   // (conv (conv x, t1), t2) -> (conv x, t2)
6136   if (N0.getOpcode() == ISD::BITCAST)
6137     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6138                        N0.getOperand(0));
6139
6140   // fold (conv (load x)) -> (load (conv*)x)
6141   // If the resultant load doesn't need a higher alignment than the original!
6142   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6143       // Do not change the width of a volatile load.
6144       !cast<LoadSDNode>(N0)->isVolatile() &&
6145       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6146       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6147     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6148     unsigned Align = TLI.getDataLayout()->
6149       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6150     unsigned OrigAlign = LN0->getAlignment();
6151
6152     if (Align <= OrigAlign) {
6153       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6154                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6155                                  LN0->isVolatile(), LN0->isNonTemporal(),
6156                                  LN0->isInvariant(), OrigAlign,
6157                                  LN0->getTBAAInfo());
6158       AddToWorkList(N);
6159       CombineTo(N0.getNode(),
6160                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6161                             N0.getValueType(), Load),
6162                 Load.getValue(1));
6163       return Load;
6164     }
6165   }
6166
6167   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6168   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6169   // This often reduces constant pool loads.
6170   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6171        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6172       N0.getNode()->hasOneUse() && VT.isInteger() &&
6173       !VT.isVector() && !N0.getValueType().isVector()) {
6174     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6175                                   N0.getOperand(0));
6176     AddToWorkList(NewConv.getNode());
6177
6178     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6179     if (N0.getOpcode() == ISD::FNEG)
6180       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6181                          NewConv, DAG.getConstant(SignBit, VT));
6182     assert(N0.getOpcode() == ISD::FABS);
6183     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6184                        NewConv, DAG.getConstant(~SignBit, VT));
6185   }
6186
6187   // fold (bitconvert (fcopysign cst, x)) ->
6188   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6189   // Note that we don't handle (copysign x, cst) because this can always be
6190   // folded to an fneg or fabs.
6191   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6192       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6193       VT.isInteger() && !VT.isVector()) {
6194     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6195     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6196     if (isTypeLegal(IntXVT)) {
6197       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6198                               IntXVT, N0.getOperand(1));
6199       AddToWorkList(X.getNode());
6200
6201       // If X has a different width than the result/lhs, sext it or truncate it.
6202       unsigned VTWidth = VT.getSizeInBits();
6203       if (OrigXWidth < VTWidth) {
6204         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6205         AddToWorkList(X.getNode());
6206       } else if (OrigXWidth > VTWidth) {
6207         // To get the sign bit in the right place, we have to shift it right
6208         // before truncating.
6209         X = DAG.getNode(ISD::SRL, SDLoc(X),
6210                         X.getValueType(), X,
6211                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6212         AddToWorkList(X.getNode());
6213         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6214         AddToWorkList(X.getNode());
6215       }
6216
6217       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6218       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6219                       X, DAG.getConstant(SignBit, VT));
6220       AddToWorkList(X.getNode());
6221
6222       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6223                                 VT, N0.getOperand(0));
6224       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6225                         Cst, DAG.getConstant(~SignBit, VT));
6226       AddToWorkList(Cst.getNode());
6227
6228       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6229     }
6230   }
6231
6232   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6233   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6234     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6235     if (CombineLD.getNode())
6236       return CombineLD;
6237   }
6238
6239   return SDValue();
6240 }
6241
6242 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6243   EVT VT = N->getValueType(0);
6244   return CombineConsecutiveLoads(N, VT);
6245 }
6246
6247 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6248 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6249 /// destination element value type.
6250 SDValue DAGCombiner::
6251 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6252   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6253
6254   // If this is already the right type, we're done.
6255   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6256
6257   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6258   unsigned DstBitSize = DstEltVT.getSizeInBits();
6259
6260   // If this is a conversion of N elements of one type to N elements of another
6261   // type, convert each element.  This handles FP<->INT cases.
6262   if (SrcBitSize == DstBitSize) {
6263     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6264                               BV->getValueType(0).getVectorNumElements());
6265
6266     // Due to the FP element handling below calling this routine recursively,
6267     // we can end up with a scalar-to-vector node here.
6268     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6269       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6270                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6271                                      DstEltVT, BV->getOperand(0)));
6272
6273     SmallVector<SDValue, 8> Ops;
6274     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6275       SDValue Op = BV->getOperand(i);
6276       // If the vector element type is not legal, the BUILD_VECTOR operands
6277       // are promoted and implicitly truncated.  Make that explicit here.
6278       if (Op.getValueType() != SrcEltVT)
6279         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6280       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6281                                 DstEltVT, Op));
6282       AddToWorkList(Ops.back().getNode());
6283     }
6284     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6285                        &Ops[0], Ops.size());
6286   }
6287
6288   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6289   // handle annoying details of growing/shrinking FP values, we convert them to
6290   // int first.
6291   if (SrcEltVT.isFloatingPoint()) {
6292     // Convert the input float vector to a int vector where the elements are the
6293     // same sizes.
6294     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6295     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6296     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6297     SrcEltVT = IntVT;
6298   }
6299
6300   // Now we know the input is an integer vector.  If the output is a FP type,
6301   // convert to integer first, then to FP of the right size.
6302   if (DstEltVT.isFloatingPoint()) {
6303     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6304     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6305     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6306
6307     // Next, convert to FP elements of the same size.
6308     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6309   }
6310
6311   // Okay, we know the src/dst types are both integers of differing types.
6312   // Handling growing first.
6313   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6314   if (SrcBitSize < DstBitSize) {
6315     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6316
6317     SmallVector<SDValue, 8> Ops;
6318     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6319          i += NumInputsPerOutput) {
6320       bool isLE = TLI.isLittleEndian();
6321       APInt NewBits = APInt(DstBitSize, 0);
6322       bool EltIsUndef = true;
6323       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6324         // Shift the previously computed bits over.
6325         NewBits <<= SrcBitSize;
6326         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6327         if (Op.getOpcode() == ISD::UNDEF) continue;
6328         EltIsUndef = false;
6329
6330         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6331                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6332       }
6333
6334       if (EltIsUndef)
6335         Ops.push_back(DAG.getUNDEF(DstEltVT));
6336       else
6337         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6338     }
6339
6340     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6341     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6342                        &Ops[0], Ops.size());
6343   }
6344
6345   // Finally, this must be the case where we are shrinking elements: each input
6346   // turns into multiple outputs.
6347   bool isS2V = ISD::isScalarToVector(BV);
6348   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6349   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6350                             NumOutputsPerInput*BV->getNumOperands());
6351   SmallVector<SDValue, 8> Ops;
6352
6353   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6354     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6355       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6356         Ops.push_back(DAG.getUNDEF(DstEltVT));
6357       continue;
6358     }
6359
6360     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6361                   getAPIntValue().zextOrTrunc(SrcBitSize);
6362
6363     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6364       APInt ThisVal = OpVal.trunc(DstBitSize);
6365       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6366       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6367         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6368         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6369                            Ops[0]);
6370       OpVal = OpVal.lshr(DstBitSize);
6371     }
6372
6373     // For big endian targets, swap the order of the pieces of each element.
6374     if (TLI.isBigEndian())
6375       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6376   }
6377
6378   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6379                      &Ops[0], Ops.size());
6380 }
6381
6382 SDValue DAGCombiner::visitFADD(SDNode *N) {
6383   SDValue N0 = N->getOperand(0);
6384   SDValue N1 = N->getOperand(1);
6385   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6386   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6387   EVT VT = N->getValueType(0);
6388
6389   // fold vector ops
6390   if (VT.isVector()) {
6391     SDValue FoldedVOp = SimplifyVBinOp(N);
6392     if (FoldedVOp.getNode()) return FoldedVOp;
6393   }
6394
6395   // fold (fadd c1, c2) -> c1 + c2
6396   if (N0CFP && N1CFP)
6397     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6398   // canonicalize constant to RHS
6399   if (N0CFP && !N1CFP)
6400     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6401   // fold (fadd A, 0) -> A
6402   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6403       N1CFP->getValueAPF().isZero())
6404     return N0;
6405   // fold (fadd A, (fneg B)) -> (fsub A, B)
6406   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6407     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6408     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6409                        GetNegatedExpression(N1, DAG, LegalOperations));
6410   // fold (fadd (fneg A), B) -> (fsub B, A)
6411   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6412     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6413     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6414                        GetNegatedExpression(N0, DAG, LegalOperations));
6415
6416   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6417   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6418       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6419       isa<ConstantFPSDNode>(N0.getOperand(1)))
6420     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6421                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6422                                    N0.getOperand(1), N1));
6423
6424   // No FP constant should be created after legalization as Instruction
6425   // Selection pass has hard time in dealing with FP constant.
6426   //
6427   // We don't need test this condition for transformation like following, as
6428   // the DAG being transformed implies it is legal to take FP constant as
6429   // operand.
6430   //
6431   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6432   //
6433   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6434
6435   // If allow, fold (fadd (fneg x), x) -> 0.0
6436   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6437       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6438     return DAG.getConstantFP(0.0, VT);
6439
6440     // If allow, fold (fadd x, (fneg x)) -> 0.0
6441   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6442       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6443     return DAG.getConstantFP(0.0, VT);
6444
6445   // In unsafe math mode, we can fold chains of FADD's of the same value
6446   // into multiplications.  This transform is not safe in general because
6447   // we are reducing the number of rounding steps.
6448   if (DAG.getTarget().Options.UnsafeFPMath &&
6449       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6450       !N0CFP && !N1CFP) {
6451     if (N0.getOpcode() == ISD::FMUL) {
6452       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6453       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6454
6455       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6456       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6457         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6458                                      SDValue(CFP00, 0),
6459                                      DAG.getConstantFP(1.0, VT));
6460         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6461                            N1, NewCFP);
6462       }
6463
6464       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6465       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6466         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6467                                      SDValue(CFP01, 0),
6468                                      DAG.getConstantFP(1.0, VT));
6469         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6470                            N1, NewCFP);
6471       }
6472
6473       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6474       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6475           N1.getOperand(0) == N1.getOperand(1) &&
6476           N0.getOperand(1) == N1.getOperand(0)) {
6477         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6478                                      SDValue(CFP00, 0),
6479                                      DAG.getConstantFP(2.0, VT));
6480         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6481                            N0.getOperand(1), NewCFP);
6482       }
6483
6484       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6485       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6486           N1.getOperand(0) == N1.getOperand(1) &&
6487           N0.getOperand(0) == N1.getOperand(0)) {
6488         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6489                                      SDValue(CFP01, 0),
6490                                      DAG.getConstantFP(2.0, VT));
6491         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6492                            N0.getOperand(0), NewCFP);
6493       }
6494     }
6495
6496     if (N1.getOpcode() == ISD::FMUL) {
6497       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6498       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6499
6500       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6501       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6502         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6503                                      SDValue(CFP10, 0),
6504                                      DAG.getConstantFP(1.0, VT));
6505         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6506                            N0, NewCFP);
6507       }
6508
6509       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6510       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6511         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6512                                      SDValue(CFP11, 0),
6513                                      DAG.getConstantFP(1.0, VT));
6514         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6515                            N0, NewCFP);
6516       }
6517
6518
6519       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6520       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6521           N0.getOperand(0) == N0.getOperand(1) &&
6522           N1.getOperand(1) == N0.getOperand(0)) {
6523         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6524                                      SDValue(CFP10, 0),
6525                                      DAG.getConstantFP(2.0, VT));
6526         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6527                            N1.getOperand(1), NewCFP);
6528       }
6529
6530       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6531       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6532           N0.getOperand(0) == N0.getOperand(1) &&
6533           N1.getOperand(0) == N0.getOperand(0)) {
6534         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6535                                      SDValue(CFP11, 0),
6536                                      DAG.getConstantFP(2.0, VT));
6537         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538                            N1.getOperand(0), NewCFP);
6539       }
6540     }
6541
6542     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6543       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6544       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6545       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6546           (N0.getOperand(0) == N1))
6547         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6548                            N1, DAG.getConstantFP(3.0, VT));
6549     }
6550
6551     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6552       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6553       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6554       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6555           N1.getOperand(0) == N0)
6556         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557                            N0, DAG.getConstantFP(3.0, VT));
6558     }
6559
6560     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6561     if (AllowNewFpConst &&
6562         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6563         N0.getOperand(0) == N0.getOperand(1) &&
6564         N1.getOperand(0) == N1.getOperand(1) &&
6565         N0.getOperand(0) == N1.getOperand(0))
6566       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6567                          N0.getOperand(0),
6568                          DAG.getConstantFP(4.0, VT));
6569   }
6570
6571   // FADD -> FMA combines:
6572   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6573        DAG.getTarget().Options.UnsafeFPMath) &&
6574       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6575       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6576
6577     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6578     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6579       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6580                          N0.getOperand(0), N0.getOperand(1), N1);
6581
6582     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6583     // Note: Commutes FADD operands.
6584     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6585       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6586                          N1.getOperand(0), N1.getOperand(1), N0);
6587   }
6588
6589   return SDValue();
6590 }
6591
6592 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6593   SDValue N0 = N->getOperand(0);
6594   SDValue N1 = N->getOperand(1);
6595   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6596   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6597   EVT VT = N->getValueType(0);
6598   SDLoc dl(N);
6599
6600   // fold vector ops
6601   if (VT.isVector()) {
6602     SDValue FoldedVOp = SimplifyVBinOp(N);
6603     if (FoldedVOp.getNode()) return FoldedVOp;
6604   }
6605
6606   // fold (fsub c1, c2) -> c1-c2
6607   if (N0CFP && N1CFP)
6608     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6609   // fold (fsub A, 0) -> A
6610   if (DAG.getTarget().Options.UnsafeFPMath &&
6611       N1CFP && N1CFP->getValueAPF().isZero())
6612     return N0;
6613   // fold (fsub 0, B) -> -B
6614   if (DAG.getTarget().Options.UnsafeFPMath &&
6615       N0CFP && N0CFP->getValueAPF().isZero()) {
6616     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6617       return GetNegatedExpression(N1, DAG, LegalOperations);
6618     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6619       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6620   }
6621   // fold (fsub A, (fneg B)) -> (fadd A, B)
6622   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6623     return DAG.getNode(ISD::FADD, dl, VT, N0,
6624                        GetNegatedExpression(N1, DAG, LegalOperations));
6625
6626   // If 'unsafe math' is enabled, fold
6627   //    (fsub x, x) -> 0.0 &
6628   //    (fsub x, (fadd x, y)) -> (fneg y) &
6629   //    (fsub x, (fadd y, x)) -> (fneg y)
6630   if (DAG.getTarget().Options.UnsafeFPMath) {
6631     if (N0 == N1)
6632       return DAG.getConstantFP(0.0f, VT);
6633
6634     if (N1.getOpcode() == ISD::FADD) {
6635       SDValue N10 = N1->getOperand(0);
6636       SDValue N11 = N1->getOperand(1);
6637
6638       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6639                                           &DAG.getTarget().Options))
6640         return GetNegatedExpression(N11, DAG, LegalOperations);
6641
6642       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6643                                           &DAG.getTarget().Options))
6644         return GetNegatedExpression(N10, DAG, LegalOperations);
6645     }
6646   }
6647
6648   // FSUB -> FMA combines:
6649   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6650        DAG.getTarget().Options.UnsafeFPMath) &&
6651       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6652       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6653
6654     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6655     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6656       return DAG.getNode(ISD::FMA, dl, VT,
6657                          N0.getOperand(0), N0.getOperand(1),
6658                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6659
6660     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6661     // Note: Commutes FSUB operands.
6662     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6663       return DAG.getNode(ISD::FMA, dl, VT,
6664                          DAG.getNode(ISD::FNEG, dl, VT,
6665                          N1.getOperand(0)),
6666                          N1.getOperand(1), N0);
6667
6668     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6669     if (N0.getOpcode() == ISD::FNEG &&
6670         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6671         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6672       SDValue N00 = N0.getOperand(0).getOperand(0);
6673       SDValue N01 = N0.getOperand(0).getOperand(1);
6674       return DAG.getNode(ISD::FMA, dl, VT,
6675                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6676                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6677     }
6678   }
6679
6680   return SDValue();
6681 }
6682
6683 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6684   SDValue N0 = N->getOperand(0);
6685   SDValue N1 = N->getOperand(1);
6686   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6687   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6688   EVT VT = N->getValueType(0);
6689   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6690
6691   // fold vector ops
6692   if (VT.isVector()) {
6693     SDValue FoldedVOp = SimplifyVBinOp(N);
6694     if (FoldedVOp.getNode()) return FoldedVOp;
6695   }
6696
6697   // fold (fmul c1, c2) -> c1*c2
6698   if (N0CFP && N1CFP)
6699     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6700   // canonicalize constant to RHS
6701   if (N0CFP && !N1CFP)
6702     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6703   // fold (fmul A, 0) -> 0
6704   if (DAG.getTarget().Options.UnsafeFPMath &&
6705       N1CFP && N1CFP->getValueAPF().isZero())
6706     return N1;
6707   // fold (fmul A, 0) -> 0, vector edition.
6708   if (DAG.getTarget().Options.UnsafeFPMath &&
6709       ISD::isBuildVectorAllZeros(N1.getNode()))
6710     return N1;
6711   // fold (fmul A, 1.0) -> A
6712   if (N1CFP && N1CFP->isExactlyValue(1.0))
6713     return N0;
6714   // fold (fmul X, 2.0) -> (fadd X, X)
6715   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6716     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6717   // fold (fmul X, -1.0) -> (fneg X)
6718   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6719     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6720       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6721
6722   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6723   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6724                                        &DAG.getTarget().Options)) {
6725     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6726                                          &DAG.getTarget().Options)) {
6727       // Both can be negated for free, check to see if at least one is cheaper
6728       // negated.
6729       if (LHSNeg == 2 || RHSNeg == 2)
6730         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6731                            GetNegatedExpression(N0, DAG, LegalOperations),
6732                            GetNegatedExpression(N1, DAG, LegalOperations));
6733     }
6734   }
6735
6736   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6737   if (DAG.getTarget().Options.UnsafeFPMath &&
6738       N1CFP && N0.getOpcode() == ISD::FMUL &&
6739       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6740     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6741                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6742                                    N0.getOperand(1), N1));
6743
6744   return SDValue();
6745 }
6746
6747 SDValue DAGCombiner::visitFMA(SDNode *N) {
6748   SDValue N0 = N->getOperand(0);
6749   SDValue N1 = N->getOperand(1);
6750   SDValue N2 = N->getOperand(2);
6751   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6752   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6753   EVT VT = N->getValueType(0);
6754   SDLoc dl(N);
6755
6756   if (DAG.getTarget().Options.UnsafeFPMath) {
6757     if (N0CFP && N0CFP->isZero())
6758       return N2;
6759     if (N1CFP && N1CFP->isZero())
6760       return N2;
6761   }
6762   if (N0CFP && N0CFP->isExactlyValue(1.0))
6763     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6764   if (N1CFP && N1CFP->isExactlyValue(1.0))
6765     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6766
6767   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6768   if (N0CFP && !N1CFP)
6769     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6770
6771   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6772   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6773       N2.getOpcode() == ISD::FMUL &&
6774       N0 == N2.getOperand(0) &&
6775       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6776     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6777                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6778   }
6779
6780
6781   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6782   if (DAG.getTarget().Options.UnsafeFPMath &&
6783       N0.getOpcode() == ISD::FMUL && N1CFP &&
6784       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6785     return DAG.getNode(ISD::FMA, dl, VT,
6786                        N0.getOperand(0),
6787                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6788                        N2);
6789   }
6790
6791   // (fma x, 1, y) -> (fadd x, y)
6792   // (fma x, -1, y) -> (fadd (fneg x), y)
6793   if (N1CFP) {
6794     if (N1CFP->isExactlyValue(1.0))
6795       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6796
6797     if (N1CFP->isExactlyValue(-1.0) &&
6798         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6799       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6800       AddToWorkList(RHSNeg.getNode());
6801       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6802     }
6803   }
6804
6805   // (fma x, c, x) -> (fmul x, (c+1))
6806   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6807     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6808                        DAG.getNode(ISD::FADD, dl, VT,
6809                                    N1, DAG.getConstantFP(1.0, VT)));
6810
6811   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6812   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6813       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6814     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6815                        DAG.getNode(ISD::FADD, dl, VT,
6816                                    N1, DAG.getConstantFP(-1.0, VT)));
6817
6818
6819   return SDValue();
6820 }
6821
6822 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6823   SDValue N0 = N->getOperand(0);
6824   SDValue N1 = N->getOperand(1);
6825   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6826   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6827   EVT VT = N->getValueType(0);
6828   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6829
6830   // fold vector ops
6831   if (VT.isVector()) {
6832     SDValue FoldedVOp = SimplifyVBinOp(N);
6833     if (FoldedVOp.getNode()) return FoldedVOp;
6834   }
6835
6836   // fold (fdiv c1, c2) -> c1/c2
6837   if (N0CFP && N1CFP)
6838     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6839
6840   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6841   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6842     // Compute the reciprocal 1.0 / c2.
6843     APFloat N1APF = N1CFP->getValueAPF();
6844     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6845     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6846     // Only do the transform if the reciprocal is a legal fp immediate that
6847     // isn't too nasty (eg NaN, denormal, ...).
6848     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6849         (!LegalOperations ||
6850          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6851          // backend)... we should handle this gracefully after Legalize.
6852          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6853          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6854          TLI.isFPImmLegal(Recip, VT)))
6855       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6856                          DAG.getConstantFP(Recip, VT));
6857   }
6858
6859   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6860   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6861                                        &DAG.getTarget().Options)) {
6862     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6863                                          &DAG.getTarget().Options)) {
6864       // Both can be negated for free, check to see if at least one is cheaper
6865       // negated.
6866       if (LHSNeg == 2 || RHSNeg == 2)
6867         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6868                            GetNegatedExpression(N0, DAG, LegalOperations),
6869                            GetNegatedExpression(N1, DAG, LegalOperations));
6870     }
6871   }
6872
6873   return SDValue();
6874 }
6875
6876 SDValue DAGCombiner::visitFREM(SDNode *N) {
6877   SDValue N0 = N->getOperand(0);
6878   SDValue N1 = N->getOperand(1);
6879   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6880   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6881   EVT VT = N->getValueType(0);
6882
6883   // fold (frem c1, c2) -> fmod(c1,c2)
6884   if (N0CFP && N1CFP)
6885     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6886
6887   return SDValue();
6888 }
6889
6890 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6891   SDValue N0 = N->getOperand(0);
6892   SDValue N1 = N->getOperand(1);
6893   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6894   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6895   EVT VT = N->getValueType(0);
6896
6897   if (N0CFP && N1CFP)  // Constant fold
6898     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6899
6900   if (N1CFP) {
6901     const APFloat& V = N1CFP->getValueAPF();
6902     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6903     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6904     if (!V.isNegative()) {
6905       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6906         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6907     } else {
6908       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6909         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6910                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6911     }
6912   }
6913
6914   // copysign(fabs(x), y) -> copysign(x, y)
6915   // copysign(fneg(x), y) -> copysign(x, y)
6916   // copysign(copysign(x,z), y) -> copysign(x, y)
6917   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6918       N0.getOpcode() == ISD::FCOPYSIGN)
6919     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6920                        N0.getOperand(0), N1);
6921
6922   // copysign(x, abs(y)) -> abs(x)
6923   if (N1.getOpcode() == ISD::FABS)
6924     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6925
6926   // copysign(x, copysign(y,z)) -> copysign(x, z)
6927   if (N1.getOpcode() == ISD::FCOPYSIGN)
6928     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6929                        N0, N1.getOperand(1));
6930
6931   // copysign(x, fp_extend(y)) -> copysign(x, y)
6932   // copysign(x, fp_round(y)) -> copysign(x, y)
6933   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6934     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6935                        N0, N1.getOperand(0));
6936
6937   return SDValue();
6938 }
6939
6940 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6941   SDValue N0 = N->getOperand(0);
6942   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6943   EVT VT = N->getValueType(0);
6944   EVT OpVT = N0.getValueType();
6945
6946   // fold (sint_to_fp c1) -> c1fp
6947   if (N0C &&
6948       // ...but only if the target supports immediate floating-point values
6949       (!LegalOperations ||
6950        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6951     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6952
6953   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6954   // but UINT_TO_FP is legal on this target, try to convert.
6955   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6956       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6957     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6958     if (DAG.SignBitIsZero(N0))
6959       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6960   }
6961
6962   // The next optimizations are desirable only if SELECT_CC can be lowered.
6963   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6964   // having to say they don't support SELECT_CC on every type the DAG knows
6965   // about, since there is no way to mark an opcode illegal at all value types
6966   // (See also visitSELECT)
6967   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6968     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6969     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6970         !VT.isVector() &&
6971         (!LegalOperations ||
6972          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6973       SDValue Ops[] =
6974         { N0.getOperand(0), N0.getOperand(1),
6975           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6976           N0.getOperand(2) };
6977       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6978     }
6979
6980     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6981     //      (select_cc x, y, 1.0, 0.0,, cc)
6982     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6983         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6984         (!LegalOperations ||
6985          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6986       SDValue Ops[] =
6987         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6988           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6989           N0.getOperand(0).getOperand(2) };
6990       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6991     }
6992   }
6993
6994   return SDValue();
6995 }
6996
6997 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6998   SDValue N0 = N->getOperand(0);
6999   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7000   EVT VT = N->getValueType(0);
7001   EVT OpVT = N0.getValueType();
7002
7003   // fold (uint_to_fp c1) -> c1fp
7004   if (N0C &&
7005       // ...but only if the target supports immediate floating-point values
7006       (!LegalOperations ||
7007        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7008     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7009
7010   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7011   // but SINT_TO_FP is legal on this target, try to convert.
7012   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7013       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7014     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7015     if (DAG.SignBitIsZero(N0))
7016       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7017   }
7018
7019   // The next optimizations are desirable only if SELECT_CC can be lowered.
7020   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7021   // having to say they don't support SELECT_CC on every type the DAG knows
7022   // about, since there is no way to mark an opcode illegal at all value types
7023   // (See also visitSELECT)
7024   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7025     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7026
7027     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7028         (!LegalOperations ||
7029          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7030       SDValue Ops[] =
7031         { N0.getOperand(0), N0.getOperand(1),
7032           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7033           N0.getOperand(2) };
7034       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7035     }
7036   }
7037
7038   return SDValue();
7039 }
7040
7041 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7042   SDValue N0 = N->getOperand(0);
7043   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7044   EVT VT = N->getValueType(0);
7045
7046   // fold (fp_to_sint c1fp) -> c1
7047   if (N0CFP)
7048     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7049
7050   return SDValue();
7051 }
7052
7053 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7054   SDValue N0 = N->getOperand(0);
7055   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7056   EVT VT = N->getValueType(0);
7057
7058   // fold (fp_to_uint c1fp) -> c1
7059   if (N0CFP)
7060     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7061
7062   return SDValue();
7063 }
7064
7065 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7066   SDValue N0 = N->getOperand(0);
7067   SDValue N1 = N->getOperand(1);
7068   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7069   EVT VT = N->getValueType(0);
7070
7071   // fold (fp_round c1fp) -> c1fp
7072   if (N0CFP)
7073     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7074
7075   // fold (fp_round (fp_extend x)) -> x
7076   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7077     return N0.getOperand(0);
7078
7079   // fold (fp_round (fp_round x)) -> (fp_round x)
7080   if (N0.getOpcode() == ISD::FP_ROUND) {
7081     // This is a value preserving truncation if both round's are.
7082     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7083                    N0.getNode()->getConstantOperandVal(1) == 1;
7084     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7085                        DAG.getIntPtrConstant(IsTrunc));
7086   }
7087
7088   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7089   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7090     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7091                               N0.getOperand(0), N1);
7092     AddToWorkList(Tmp.getNode());
7093     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7094                        Tmp, N0.getOperand(1));
7095   }
7096
7097   return SDValue();
7098 }
7099
7100 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7101   SDValue N0 = N->getOperand(0);
7102   EVT VT = N->getValueType(0);
7103   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7104   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7105
7106   // fold (fp_round_inreg c1fp) -> c1fp
7107   if (N0CFP && isTypeLegal(EVT)) {
7108     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7109     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7110   }
7111
7112   return SDValue();
7113 }
7114
7115 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7116   SDValue N0 = N->getOperand(0);
7117   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7118   EVT VT = N->getValueType(0);
7119
7120   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7121   if (N->hasOneUse() &&
7122       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7123     return SDValue();
7124
7125   // fold (fp_extend c1fp) -> c1fp
7126   if (N0CFP)
7127     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7128
7129   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7130   // value of X.
7131   if (N0.getOpcode() == ISD::FP_ROUND
7132       && N0.getNode()->getConstantOperandVal(1) == 1) {
7133     SDValue In = N0.getOperand(0);
7134     if (In.getValueType() == VT) return In;
7135     if (VT.bitsLT(In.getValueType()))
7136       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7137                          In, N0.getOperand(1));
7138     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7139   }
7140
7141   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7142   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7143       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7144        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7145     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7146     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7147                                      LN0->getChain(),
7148                                      LN0->getBasePtr(), N0.getValueType(),
7149                                      LN0->getMemOperand());
7150     CombineTo(N, ExtLoad);
7151     CombineTo(N0.getNode(),
7152               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7153                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7154               ExtLoad.getValue(1));
7155     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7156   }
7157
7158   return SDValue();
7159 }
7160
7161 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7162   SDValue N0 = N->getOperand(0);
7163   EVT VT = N->getValueType(0);
7164
7165   if (VT.isVector()) {
7166     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7167     if (FoldedVOp.getNode()) return FoldedVOp;
7168   }
7169
7170   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7171                          &DAG.getTarget().Options))
7172     return GetNegatedExpression(N0, DAG, LegalOperations);
7173
7174   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7175   // constant pool values.
7176   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7177       !VT.isVector() &&
7178       N0.getNode()->hasOneUse() &&
7179       N0.getOperand(0).getValueType().isInteger()) {
7180     SDValue Int = N0.getOperand(0);
7181     EVT IntVT = Int.getValueType();
7182     if (IntVT.isInteger() && !IntVT.isVector()) {
7183       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7184               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7185       AddToWorkList(Int.getNode());
7186       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7187                          VT, Int);
7188     }
7189   }
7190
7191   // (fneg (fmul c, x)) -> (fmul -c, x)
7192   if (N0.getOpcode() == ISD::FMUL) {
7193     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7194     if (CFP1)
7195       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7196                          N0.getOperand(0),
7197                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7198                                      N0.getOperand(1)));
7199   }
7200
7201   return SDValue();
7202 }
7203
7204 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7205   SDValue N0 = N->getOperand(0);
7206   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7207   EVT VT = N->getValueType(0);
7208
7209   // fold (fceil c1) -> fceil(c1)
7210   if (N0CFP)
7211     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7212
7213   return SDValue();
7214 }
7215
7216 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7217   SDValue N0 = N->getOperand(0);
7218   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7219   EVT VT = N->getValueType(0);
7220
7221   // fold (ftrunc c1) -> ftrunc(c1)
7222   if (N0CFP)
7223     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7224
7225   return SDValue();
7226 }
7227
7228 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7229   SDValue N0 = N->getOperand(0);
7230   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7231   EVT VT = N->getValueType(0);
7232
7233   // fold (ffloor c1) -> ffloor(c1)
7234   if (N0CFP)
7235     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7236
7237   return SDValue();
7238 }
7239
7240 SDValue DAGCombiner::visitFABS(SDNode *N) {
7241   SDValue N0 = N->getOperand(0);
7242   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7243   EVT VT = N->getValueType(0);
7244
7245   if (VT.isVector()) {
7246     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7247     if (FoldedVOp.getNode()) return FoldedVOp;
7248   }
7249
7250   // fold (fabs c1) -> fabs(c1)
7251   if (N0CFP)
7252     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7253   // fold (fabs (fabs x)) -> (fabs x)
7254   if (N0.getOpcode() == ISD::FABS)
7255     return N->getOperand(0);
7256   // fold (fabs (fneg x)) -> (fabs x)
7257   // fold (fabs (fcopysign x, y)) -> (fabs x)
7258   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7259     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7260
7261   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7262   // constant pool values.
7263   if (!TLI.isFAbsFree(VT) &&
7264       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7265       N0.getOperand(0).getValueType().isInteger() &&
7266       !N0.getOperand(0).getValueType().isVector()) {
7267     SDValue Int = N0.getOperand(0);
7268     EVT IntVT = Int.getValueType();
7269     if (IntVT.isInteger() && !IntVT.isVector()) {
7270       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7271              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7272       AddToWorkList(Int.getNode());
7273       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7274                          N->getValueType(0), Int);
7275     }
7276   }
7277
7278   return SDValue();
7279 }
7280
7281 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7282   SDValue Chain = N->getOperand(0);
7283   SDValue N1 = N->getOperand(1);
7284   SDValue N2 = N->getOperand(2);
7285
7286   // If N is a constant we could fold this into a fallthrough or unconditional
7287   // branch. However that doesn't happen very often in normal code, because
7288   // Instcombine/SimplifyCFG should have handled the available opportunities.
7289   // If we did this folding here, it would be necessary to update the
7290   // MachineBasicBlock CFG, which is awkward.
7291
7292   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7293   // on the target.
7294   if (N1.getOpcode() == ISD::SETCC &&
7295       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7296                                    N1.getOperand(0).getValueType())) {
7297     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7298                        Chain, N1.getOperand(2),
7299                        N1.getOperand(0), N1.getOperand(1), N2);
7300   }
7301
7302   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7303       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7304        (N1.getOperand(0).hasOneUse() &&
7305         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7306     SDNode *Trunc = nullptr;
7307     if (N1.getOpcode() == ISD::TRUNCATE) {
7308       // Look pass the truncate.
7309       Trunc = N1.getNode();
7310       N1 = N1.getOperand(0);
7311     }
7312
7313     // Match this pattern so that we can generate simpler code:
7314     //
7315     //   %a = ...
7316     //   %b = and i32 %a, 2
7317     //   %c = srl i32 %b, 1
7318     //   brcond i32 %c ...
7319     //
7320     // into
7321     //
7322     //   %a = ...
7323     //   %b = and i32 %a, 2
7324     //   %c = setcc eq %b, 0
7325     //   brcond %c ...
7326     //
7327     // This applies only when the AND constant value has one bit set and the
7328     // SRL constant is equal to the log2 of the AND constant. The back-end is
7329     // smart enough to convert the result into a TEST/JMP sequence.
7330     SDValue Op0 = N1.getOperand(0);
7331     SDValue Op1 = N1.getOperand(1);
7332
7333     if (Op0.getOpcode() == ISD::AND &&
7334         Op1.getOpcode() == ISD::Constant) {
7335       SDValue AndOp1 = Op0.getOperand(1);
7336
7337       if (AndOp1.getOpcode() == ISD::Constant) {
7338         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7339
7340         if (AndConst.isPowerOf2() &&
7341             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7342           SDValue SetCC =
7343             DAG.getSetCC(SDLoc(N),
7344                          getSetCCResultType(Op0.getValueType()),
7345                          Op0, DAG.getConstant(0, Op0.getValueType()),
7346                          ISD::SETNE);
7347
7348           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7349                                           MVT::Other, Chain, SetCC, N2);
7350           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7351           // will convert it back to (X & C1) >> C2.
7352           CombineTo(N, NewBRCond, false);
7353           // Truncate is dead.
7354           if (Trunc) {
7355             removeFromWorkList(Trunc);
7356             DAG.DeleteNode(Trunc);
7357           }
7358           // Replace the uses of SRL with SETCC
7359           WorkListRemover DeadNodes(*this);
7360           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7361           removeFromWorkList(N1.getNode());
7362           DAG.DeleteNode(N1.getNode());
7363           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7364         }
7365       }
7366     }
7367
7368     if (Trunc)
7369       // Restore N1 if the above transformation doesn't match.
7370       N1 = N->getOperand(1);
7371   }
7372
7373   // Transform br(xor(x, y)) -> br(x != y)
7374   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7375   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7376     SDNode *TheXor = N1.getNode();
7377     SDValue Op0 = TheXor->getOperand(0);
7378     SDValue Op1 = TheXor->getOperand(1);
7379     if (Op0.getOpcode() == Op1.getOpcode()) {
7380       // Avoid missing important xor optimizations.
7381       SDValue Tmp = visitXOR(TheXor);
7382       if (Tmp.getNode()) {
7383         if (Tmp.getNode() != TheXor) {
7384           DEBUG(dbgs() << "\nReplacing.8 ";
7385                 TheXor->dump(&DAG);
7386                 dbgs() << "\nWith: ";
7387                 Tmp.getNode()->dump(&DAG);
7388                 dbgs() << '\n');
7389           WorkListRemover DeadNodes(*this);
7390           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7391           removeFromWorkList(TheXor);
7392           DAG.DeleteNode(TheXor);
7393           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7394                              MVT::Other, Chain, Tmp, N2);
7395         }
7396
7397         // visitXOR has changed XOR's operands or replaced the XOR completely,
7398         // bail out.
7399         return SDValue(N, 0);
7400       }
7401     }
7402
7403     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7404       bool Equal = false;
7405       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7406         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7407             Op0.getOpcode() == ISD::XOR) {
7408           TheXor = Op0.getNode();
7409           Equal = true;
7410         }
7411
7412       EVT SetCCVT = N1.getValueType();
7413       if (LegalTypes)
7414         SetCCVT = getSetCCResultType(SetCCVT);
7415       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7416                                    SetCCVT,
7417                                    Op0, Op1,
7418                                    Equal ? ISD::SETEQ : ISD::SETNE);
7419       // Replace the uses of XOR with SETCC
7420       WorkListRemover DeadNodes(*this);
7421       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7422       removeFromWorkList(N1.getNode());
7423       DAG.DeleteNode(N1.getNode());
7424       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7425                          MVT::Other, Chain, SetCC, N2);
7426     }
7427   }
7428
7429   return SDValue();
7430 }
7431
7432 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7433 //
7434 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7435   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7436   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7437
7438   // If N is a constant we could fold this into a fallthrough or unconditional
7439   // branch. However that doesn't happen very often in normal code, because
7440   // Instcombine/SimplifyCFG should have handled the available opportunities.
7441   // If we did this folding here, it would be necessary to update the
7442   // MachineBasicBlock CFG, which is awkward.
7443
7444   // Use SimplifySetCC to simplify SETCC's.
7445   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7446                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7447                                false);
7448   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7449
7450   // fold to a simpler setcc
7451   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7452     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7453                        N->getOperand(0), Simp.getOperand(2),
7454                        Simp.getOperand(0), Simp.getOperand(1),
7455                        N->getOperand(4));
7456
7457   return SDValue();
7458 }
7459
7460 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7461 /// uses N as its base pointer and that N may be folded in the load / store
7462 /// addressing mode.
7463 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7464                                     SelectionDAG &DAG,
7465                                     const TargetLowering &TLI) {
7466   EVT VT;
7467   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7468     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7469       return false;
7470     VT = Use->getValueType(0);
7471   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7472     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7473       return false;
7474     VT = ST->getValue().getValueType();
7475   } else
7476     return false;
7477
7478   TargetLowering::AddrMode AM;
7479   if (N->getOpcode() == ISD::ADD) {
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 if (N->getOpcode() == ISD::SUB) {
7488     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7489     if (Offset)
7490       // [reg +/- imm]
7491       AM.BaseOffs = -Offset->getSExtValue();
7492     else
7493       // [reg +/- reg]
7494       AM.Scale = 1;
7495   } else
7496     return false;
7497
7498   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7499 }
7500
7501 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7502 /// pre-indexed load / store when the base pointer is an add or subtract
7503 /// and it has other uses besides the load / store. After the
7504 /// transformation, the new indexed load / store has effectively folded
7505 /// the add / subtract in and all of its other uses are redirected to the
7506 /// new load / store.
7507 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7508   if (Level < AfterLegalizeDAG)
7509     return false;
7510
7511   bool isLoad = true;
7512   SDValue Ptr;
7513   EVT VT;
7514   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7515     if (LD->isIndexed())
7516       return false;
7517     VT = LD->getMemoryVT();
7518     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7519         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7520       return false;
7521     Ptr = LD->getBasePtr();
7522   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7523     if (ST->isIndexed())
7524       return false;
7525     VT = ST->getMemoryVT();
7526     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7527         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7528       return false;
7529     Ptr = ST->getBasePtr();
7530     isLoad = false;
7531   } else {
7532     return false;
7533   }
7534
7535   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7536   // out.  There is no reason to make this a preinc/predec.
7537   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7538       Ptr.getNode()->hasOneUse())
7539     return false;
7540
7541   // Ask the target to do addressing mode selection.
7542   SDValue BasePtr;
7543   SDValue Offset;
7544   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7545   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7546     return false;
7547
7548   // Backends without true r+i pre-indexed forms may need to pass a
7549   // constant base with a variable offset so that constant coercion
7550   // will work with the patterns in canonical form.
7551   bool Swapped = false;
7552   if (isa<ConstantSDNode>(BasePtr)) {
7553     std::swap(BasePtr, Offset);
7554     Swapped = true;
7555   }
7556
7557   // Don't create a indexed load / store with zero offset.
7558   if (isa<ConstantSDNode>(Offset) &&
7559       cast<ConstantSDNode>(Offset)->isNullValue())
7560     return false;
7561
7562   // Try turning it into a pre-indexed load / store except when:
7563   // 1) The new base ptr is a frame index.
7564   // 2) If N is a store and the new base ptr is either the same as or is a
7565   //    predecessor of the value being stored.
7566   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7567   //    that would create a cycle.
7568   // 4) All uses are load / store ops that use it as old base ptr.
7569
7570   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7571   // (plus the implicit offset) to a register to preinc anyway.
7572   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7573     return false;
7574
7575   // Check #2.
7576   if (!isLoad) {
7577     SDValue Val = cast<StoreSDNode>(N)->getValue();
7578     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7579       return false;
7580   }
7581
7582   // If the offset is a constant, there may be other adds of constants that
7583   // can be folded with this one. We should do this to avoid having to keep
7584   // a copy of the original base pointer.
7585   SmallVector<SDNode *, 16> OtherUses;
7586   if (isa<ConstantSDNode>(Offset))
7587     for (SDNode *Use : BasePtr.getNode()->uses()) {
7588       if (Use == Ptr.getNode())
7589         continue;
7590
7591       if (Use->isPredecessorOf(N))
7592         continue;
7593
7594       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7595         OtherUses.clear();
7596         break;
7597       }
7598
7599       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7600       if (Op1.getNode() == BasePtr.getNode())
7601         std::swap(Op0, Op1);
7602       assert(Op0.getNode() == BasePtr.getNode() &&
7603              "Use of ADD/SUB but not an operand");
7604
7605       if (!isa<ConstantSDNode>(Op1)) {
7606         OtherUses.clear();
7607         break;
7608       }
7609
7610       // FIXME: In some cases, we can be smarter about this.
7611       if (Op1.getValueType() != Offset.getValueType()) {
7612         OtherUses.clear();
7613         break;
7614       }
7615
7616       OtherUses.push_back(Use);
7617     }
7618
7619   if (Swapped)
7620     std::swap(BasePtr, Offset);
7621
7622   // Now check for #3 and #4.
7623   bool RealUse = false;
7624
7625   // Caches for hasPredecessorHelper
7626   SmallPtrSet<const SDNode *, 32> Visited;
7627   SmallVector<const SDNode *, 16> Worklist;
7628
7629   for (SDNode *Use : Ptr.getNode()->uses()) {
7630     if (Use == N)
7631       continue;
7632     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7633       return false;
7634
7635     // If Ptr may be folded in addressing mode of other use, then it's
7636     // not profitable to do this transformation.
7637     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7638       RealUse = true;
7639   }
7640
7641   if (!RealUse)
7642     return false;
7643
7644   SDValue Result;
7645   if (isLoad)
7646     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7647                                 BasePtr, Offset, AM);
7648   else
7649     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7650                                  BasePtr, Offset, AM);
7651   ++PreIndexedNodes;
7652   ++NodesCombined;
7653   DEBUG(dbgs() << "\nReplacing.4 ";
7654         N->dump(&DAG);
7655         dbgs() << "\nWith: ";
7656         Result.getNode()->dump(&DAG);
7657         dbgs() << '\n');
7658   WorkListRemover DeadNodes(*this);
7659   if (isLoad) {
7660     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7661     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7662   } else {
7663     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7664   }
7665
7666   // Finally, since the node is now dead, remove it from the graph.
7667   DAG.DeleteNode(N);
7668
7669   if (Swapped)
7670     std::swap(BasePtr, Offset);
7671
7672   // Replace other uses of BasePtr that can be updated to use Ptr
7673   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7674     unsigned OffsetIdx = 1;
7675     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7676       OffsetIdx = 0;
7677     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7678            BasePtr.getNode() && "Expected BasePtr operand");
7679
7680     // We need to replace ptr0 in the following expression:
7681     //   x0 * offset0 + y0 * ptr0 = t0
7682     // knowing that
7683     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7684     //
7685     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7686     // indexed load/store and the expresion that needs to be re-written.
7687     //
7688     // Therefore, we have:
7689     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7690
7691     ConstantSDNode *CN =
7692       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7693     int X0, X1, Y0, Y1;
7694     APInt Offset0 = CN->getAPIntValue();
7695     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7696
7697     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7698     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7699     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7700     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7701
7702     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7703
7704     APInt CNV = Offset0;
7705     if (X0 < 0) CNV = -CNV;
7706     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7707     else CNV = CNV - Offset1;
7708
7709     // We can now generate the new expression.
7710     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7711     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7712
7713     SDValue NewUse = DAG.getNode(Opcode,
7714                                  SDLoc(OtherUses[i]),
7715                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7716     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7717     removeFromWorkList(OtherUses[i]);
7718     DAG.DeleteNode(OtherUses[i]);
7719   }
7720
7721   // Replace the uses of Ptr with uses of the updated base value.
7722   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7723   removeFromWorkList(Ptr.getNode());
7724   DAG.DeleteNode(Ptr.getNode());
7725
7726   return true;
7727 }
7728
7729 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7730 /// add / sub of the base pointer node into a post-indexed load / store.
7731 /// The transformation folded the add / subtract into the new indexed
7732 /// load / store effectively and all of its uses are redirected to the
7733 /// new load / store.
7734 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7735   if (Level < AfterLegalizeDAG)
7736     return false;
7737
7738   bool isLoad = true;
7739   SDValue Ptr;
7740   EVT VT;
7741   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7742     if (LD->isIndexed())
7743       return false;
7744     VT = LD->getMemoryVT();
7745     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7746         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7747       return false;
7748     Ptr = LD->getBasePtr();
7749   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7750     if (ST->isIndexed())
7751       return false;
7752     VT = ST->getMemoryVT();
7753     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7754         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7755       return false;
7756     Ptr = ST->getBasePtr();
7757     isLoad = false;
7758   } else {
7759     return false;
7760   }
7761
7762   if (Ptr.getNode()->hasOneUse())
7763     return false;
7764
7765   for (SDNode *Op : Ptr.getNode()->uses()) {
7766     if (Op == N ||
7767         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7768       continue;
7769
7770     SDValue BasePtr;
7771     SDValue Offset;
7772     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7773     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7774       // Don't create a indexed load / store with zero offset.
7775       if (isa<ConstantSDNode>(Offset) &&
7776           cast<ConstantSDNode>(Offset)->isNullValue())
7777         continue;
7778
7779       // Try turning it into a post-indexed load / store except when
7780       // 1) All uses are load / store ops that use it as base ptr (and
7781       //    it may be folded as addressing mmode).
7782       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7783       //    nor a successor of N. Otherwise, if Op is folded that would
7784       //    create a cycle.
7785
7786       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7787         continue;
7788
7789       // Check for #1.
7790       bool TryNext = false;
7791       for (SDNode *Use : BasePtr.getNode()->uses()) {
7792         if (Use == Ptr.getNode())
7793           continue;
7794
7795         // If all the uses are load / store addresses, then don't do the
7796         // transformation.
7797         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7798           bool RealUse = false;
7799           for (SDNode *UseUse : Use->uses()) {
7800             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7801               RealUse = true;
7802           }
7803
7804           if (!RealUse) {
7805             TryNext = true;
7806             break;
7807           }
7808         }
7809       }
7810
7811       if (TryNext)
7812         continue;
7813
7814       // Check for #2
7815       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7816         SDValue Result = isLoad
7817           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7818                                BasePtr, Offset, AM)
7819           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7820                                 BasePtr, Offset, AM);
7821         ++PostIndexedNodes;
7822         ++NodesCombined;
7823         DEBUG(dbgs() << "\nReplacing.5 ";
7824               N->dump(&DAG);
7825               dbgs() << "\nWith: ";
7826               Result.getNode()->dump(&DAG);
7827               dbgs() << '\n');
7828         WorkListRemover DeadNodes(*this);
7829         if (isLoad) {
7830           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7831           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7832         } else {
7833           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7834         }
7835
7836         // Finally, since the node is now dead, remove it from the graph.
7837         DAG.DeleteNode(N);
7838
7839         // Replace the uses of Use with uses of the updated base value.
7840         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7841                                       Result.getValue(isLoad ? 1 : 0));
7842         removeFromWorkList(Op);
7843         DAG.DeleteNode(Op);
7844         return true;
7845       }
7846     }
7847   }
7848
7849   return false;
7850 }
7851
7852 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7853   LoadSDNode *LD  = cast<LoadSDNode>(N);
7854   SDValue Chain = LD->getChain();
7855   SDValue Ptr   = LD->getBasePtr();
7856
7857   // If load is not volatile and there are no uses of the loaded value (and
7858   // the updated indexed value in case of indexed loads), change uses of the
7859   // chain value into uses of the chain input (i.e. delete the dead load).
7860   if (!LD->isVolatile()) {
7861     if (N->getValueType(1) == MVT::Other) {
7862       // Unindexed loads.
7863       if (!N->hasAnyUseOfValue(0)) {
7864         // It's not safe to use the two value CombineTo variant here. e.g.
7865         // v1, chain2 = load chain1, loc
7866         // v2, chain3 = load chain2, loc
7867         // v3         = add v2, c
7868         // Now we replace use of chain2 with chain1.  This makes the second load
7869         // isomorphic to the one we are deleting, and thus makes this load live.
7870         DEBUG(dbgs() << "\nReplacing.6 ";
7871               N->dump(&DAG);
7872               dbgs() << "\nWith chain: ";
7873               Chain.getNode()->dump(&DAG);
7874               dbgs() << "\n");
7875         WorkListRemover DeadNodes(*this);
7876         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7877
7878         if (N->use_empty()) {
7879           removeFromWorkList(N);
7880           DAG.DeleteNode(N);
7881         }
7882
7883         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7884       }
7885     } else {
7886       // Indexed loads.
7887       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7888       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7889         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7890         DEBUG(dbgs() << "\nReplacing.7 ";
7891               N->dump(&DAG);
7892               dbgs() << "\nWith: ";
7893               Undef.getNode()->dump(&DAG);
7894               dbgs() << " and 2 other values\n");
7895         WorkListRemover DeadNodes(*this);
7896         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7897         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7898                                       DAG.getUNDEF(N->getValueType(1)));
7899         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7900         removeFromWorkList(N);
7901         DAG.DeleteNode(N);
7902         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7903       }
7904     }
7905   }
7906
7907   // If this load is directly stored, replace the load value with the stored
7908   // value.
7909   // TODO: Handle store large -> read small portion.
7910   // TODO: Handle TRUNCSTORE/LOADEXT
7911   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7912     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7913       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7914       if (PrevST->getBasePtr() == Ptr &&
7915           PrevST->getValue().getValueType() == N->getValueType(0))
7916       return CombineTo(N, Chain.getOperand(1), Chain);
7917     }
7918   }
7919
7920   // Try to infer better alignment information than the load already has.
7921   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7922     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7923       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7924         SDValue NewLoad =
7925                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7926                               LD->getValueType(0),
7927                               Chain, Ptr, LD->getPointerInfo(),
7928                               LD->getMemoryVT(),
7929                               LD->isVolatile(), LD->isNonTemporal(), Align,
7930                               LD->getTBAAInfo());
7931         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7932       }
7933     }
7934   }
7935
7936   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7937     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7938 #ifndef NDEBUG
7939   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7940       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7941     UseAA = false;
7942 #endif
7943   if (UseAA && LD->isUnindexed()) {
7944     // Walk up chain skipping non-aliasing memory nodes.
7945     SDValue BetterChain = FindBetterChain(N, Chain);
7946
7947     // If there is a better chain.
7948     if (Chain != BetterChain) {
7949       SDValue ReplLoad;
7950
7951       // Replace the chain to void dependency.
7952       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7953         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7954                                BetterChain, Ptr, LD->getMemOperand());
7955       } else {
7956         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7957                                   LD->getValueType(0),
7958                                   BetterChain, Ptr, LD->getMemoryVT(),
7959                                   LD->getMemOperand());
7960       }
7961
7962       // Create token factor to keep old chain connected.
7963       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7964                                   MVT::Other, Chain, ReplLoad.getValue(1));
7965
7966       // Make sure the new and old chains are cleaned up.
7967       AddToWorkList(Token.getNode());
7968
7969       // Replace uses with load result and token factor. Don't add users
7970       // to work list.
7971       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7972     }
7973   }
7974
7975   // Try transforming N to an indexed load.
7976   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7977     return SDValue(N, 0);
7978
7979   // Try to slice up N to more direct loads if the slices are mapped to
7980   // different register banks or pairing can take place.
7981   if (SliceUpLoad(N))
7982     return SDValue(N, 0);
7983
7984   return SDValue();
7985 }
7986
7987 namespace {
7988 /// \brief Helper structure used to slice a load in smaller loads.
7989 /// Basically a slice is obtained from the following sequence:
7990 /// Origin = load Ty1, Base
7991 /// Shift = srl Ty1 Origin, CstTy Amount
7992 /// Inst = trunc Shift to Ty2
7993 ///
7994 /// Then, it will be rewriten into:
7995 /// Slice = load SliceTy, Base + SliceOffset
7996 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7997 ///
7998 /// SliceTy is deduced from the number of bits that are actually used to
7999 /// build Inst.
8000 struct LoadedSlice {
8001   /// \brief Helper structure used to compute the cost of a slice.
8002   struct Cost {
8003     /// Are we optimizing for code size.
8004     bool ForCodeSize;
8005     /// Various cost.
8006     unsigned Loads;
8007     unsigned Truncates;
8008     unsigned CrossRegisterBanksCopies;
8009     unsigned ZExts;
8010     unsigned Shift;
8011
8012     Cost(bool ForCodeSize = false)
8013         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8014           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8015
8016     /// \brief Get the cost of one isolated slice.
8017     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8018         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8019           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8020       EVT TruncType = LS.Inst->getValueType(0);
8021       EVT LoadedType = LS.getLoadedType();
8022       if (TruncType != LoadedType &&
8023           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8024         ZExts = 1;
8025     }
8026
8027     /// \brief Account for slicing gain in the current cost.
8028     /// Slicing provide a few gains like removing a shift or a
8029     /// truncate. This method allows to grow the cost of the original
8030     /// load with the gain from this slice.
8031     void addSliceGain(const LoadedSlice &LS) {
8032       // Each slice saves a truncate.
8033       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8034       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8035                               LS.Inst->getOperand(0).getValueType()))
8036         ++Truncates;
8037       // If there is a shift amount, this slice gets rid of it.
8038       if (LS.Shift)
8039         ++Shift;
8040       // If this slice can merge a cross register bank copy, account for it.
8041       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8042         ++CrossRegisterBanksCopies;
8043     }
8044
8045     Cost &operator+=(const Cost &RHS) {
8046       Loads += RHS.Loads;
8047       Truncates += RHS.Truncates;
8048       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8049       ZExts += RHS.ZExts;
8050       Shift += RHS.Shift;
8051       return *this;
8052     }
8053
8054     bool operator==(const Cost &RHS) const {
8055       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8056              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8057              ZExts == RHS.ZExts && Shift == RHS.Shift;
8058     }
8059
8060     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8061
8062     bool operator<(const Cost &RHS) const {
8063       // Assume cross register banks copies are as expensive as loads.
8064       // FIXME: Do we want some more target hooks?
8065       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8066       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8067       // Unless we are optimizing for code size, consider the
8068       // expensive operation first.
8069       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8070         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8071       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8072              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8073     }
8074
8075     bool operator>(const Cost &RHS) const { return RHS < *this; }
8076
8077     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8078
8079     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8080   };
8081   // The last instruction that represent the slice. This should be a
8082   // truncate instruction.
8083   SDNode *Inst;
8084   // The original load instruction.
8085   LoadSDNode *Origin;
8086   // The right shift amount in bits from the original load.
8087   unsigned Shift;
8088   // The DAG from which Origin came from.
8089   // This is used to get some contextual information about legal types, etc.
8090   SelectionDAG *DAG;
8091
8092   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8093               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8094       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8095
8096   LoadedSlice(const LoadedSlice &LS)
8097       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8098
8099   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8100   /// \return Result is \p BitWidth and has used bits set to 1 and
8101   ///         not used bits set to 0.
8102   APInt getUsedBits() const {
8103     // Reproduce the trunc(lshr) sequence:
8104     // - Start from the truncated value.
8105     // - Zero extend to the desired bit width.
8106     // - Shift left.
8107     assert(Origin && "No original load to compare against.");
8108     unsigned BitWidth = Origin->getValueSizeInBits(0);
8109     assert(Inst && "This slice is not bound to an instruction");
8110     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8111            "Extracted slice is bigger than the whole type!");
8112     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8113     UsedBits.setAllBits();
8114     UsedBits = UsedBits.zext(BitWidth);
8115     UsedBits <<= Shift;
8116     return UsedBits;
8117   }
8118
8119   /// \brief Get the size of the slice to be loaded in bytes.
8120   unsigned getLoadedSize() const {
8121     unsigned SliceSize = getUsedBits().countPopulation();
8122     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8123     return SliceSize / 8;
8124   }
8125
8126   /// \brief Get the type that will be loaded for this slice.
8127   /// Note: This may not be the final type for the slice.
8128   EVT getLoadedType() const {
8129     assert(DAG && "Missing context");
8130     LLVMContext &Ctxt = *DAG->getContext();
8131     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8132   }
8133
8134   /// \brief Get the alignment of the load used for this slice.
8135   unsigned getAlignment() const {
8136     unsigned Alignment = Origin->getAlignment();
8137     unsigned Offset = getOffsetFromBase();
8138     if (Offset != 0)
8139       Alignment = MinAlign(Alignment, Alignment + Offset);
8140     return Alignment;
8141   }
8142
8143   /// \brief Check if this slice can be rewritten with legal operations.
8144   bool isLegal() const {
8145     // An invalid slice is not legal.
8146     if (!Origin || !Inst || !DAG)
8147       return false;
8148
8149     // Offsets are for indexed load only, we do not handle that.
8150     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8151       return false;
8152
8153     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8154
8155     // Check that the type is legal.
8156     EVT SliceType = getLoadedType();
8157     if (!TLI.isTypeLegal(SliceType))
8158       return false;
8159
8160     // Check that the load is legal for this type.
8161     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8162       return false;
8163
8164     // Check that the offset can be computed.
8165     // 1. Check its type.
8166     EVT PtrType = Origin->getBasePtr().getValueType();
8167     if (PtrType == MVT::Untyped || PtrType.isExtended())
8168       return false;
8169
8170     // 2. Check that it fits in the immediate.
8171     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8172       return false;
8173
8174     // 3. Check that the computation is legal.
8175     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8176       return false;
8177
8178     // Check that the zext is legal if it needs one.
8179     EVT TruncateType = Inst->getValueType(0);
8180     if (TruncateType != SliceType &&
8181         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8182       return false;
8183
8184     return true;
8185   }
8186
8187   /// \brief Get the offset in bytes of this slice in the original chunk of
8188   /// bits.
8189   /// \pre DAG != nullptr.
8190   uint64_t getOffsetFromBase() const {
8191     assert(DAG && "Missing context.");
8192     bool IsBigEndian =
8193         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8194     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8195     uint64_t Offset = Shift / 8;
8196     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8197     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8198            "The size of the original loaded type is not a multiple of a"
8199            " byte.");
8200     // If Offset is bigger than TySizeInBytes, it means we are loading all
8201     // zeros. This should have been optimized before in the process.
8202     assert(TySizeInBytes > Offset &&
8203            "Invalid shift amount for given loaded size");
8204     if (IsBigEndian)
8205       Offset = TySizeInBytes - Offset - getLoadedSize();
8206     return Offset;
8207   }
8208
8209   /// \brief Generate the sequence of instructions to load the slice
8210   /// represented by this object and redirect the uses of this slice to
8211   /// this new sequence of instructions.
8212   /// \pre this->Inst && this->Origin are valid Instructions and this
8213   /// object passed the legal check: LoadedSlice::isLegal returned true.
8214   /// \return The last instruction of the sequence used to load the slice.
8215   SDValue loadSlice() const {
8216     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8217     const SDValue &OldBaseAddr = Origin->getBasePtr();
8218     SDValue BaseAddr = OldBaseAddr;
8219     // Get the offset in that chunk of bytes w.r.t. the endianess.
8220     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8221     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8222     if (Offset) {
8223       // BaseAddr = BaseAddr + Offset.
8224       EVT ArithType = BaseAddr.getValueType();
8225       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8226                               DAG->getConstant(Offset, ArithType));
8227     }
8228
8229     // Create the type of the loaded slice according to its size.
8230     EVT SliceType = getLoadedType();
8231
8232     // Create the load for the slice.
8233     SDValue LastInst = DAG->getLoad(
8234         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8235         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8236         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8237     // If the final type is not the same as the loaded type, this means that
8238     // we have to pad with zero. Create a zero extend for that.
8239     EVT FinalType = Inst->getValueType(0);
8240     if (SliceType != FinalType)
8241       LastInst =
8242           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8243     return LastInst;
8244   }
8245
8246   /// \brief Check if this slice can be merged with an expensive cross register
8247   /// bank copy. E.g.,
8248   /// i = load i32
8249   /// f = bitcast i32 i to float
8250   bool canMergeExpensiveCrossRegisterBankCopy() const {
8251     if (!Inst || !Inst->hasOneUse())
8252       return false;
8253     SDNode *Use = *Inst->use_begin();
8254     if (Use->getOpcode() != ISD::BITCAST)
8255       return false;
8256     assert(DAG && "Missing context");
8257     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8258     EVT ResVT = Use->getValueType(0);
8259     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8260     const TargetRegisterClass *ArgRC =
8261         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8262     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8263       return false;
8264
8265     // At this point, we know that we perform a cross-register-bank copy.
8266     // Check if it is expensive.
8267     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8268     // Assume bitcasts are cheap, unless both register classes do not
8269     // explicitly share a common sub class.
8270     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8271       return false;
8272
8273     // Check if it will be merged with the load.
8274     // 1. Check the alignment constraint.
8275     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8276         ResVT.getTypeForEVT(*DAG->getContext()));
8277
8278     if (RequiredAlignment > getAlignment())
8279       return false;
8280
8281     // 2. Check that the load is a legal operation for that type.
8282     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8283       return false;
8284
8285     // 3. Check that we do not have a zext in the way.
8286     if (Inst->getValueType(0) != getLoadedType())
8287       return false;
8288
8289     return true;
8290   }
8291 };
8292 }
8293
8294 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8295 /// \p UsedBits looks like 0..0 1..1 0..0.
8296 static bool areUsedBitsDense(const APInt &UsedBits) {
8297   // If all the bits are one, this is dense!
8298   if (UsedBits.isAllOnesValue())
8299     return true;
8300
8301   // Get rid of the unused bits on the right.
8302   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8303   // Get rid of the unused bits on the left.
8304   if (NarrowedUsedBits.countLeadingZeros())
8305     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8306   // Check that the chunk of bits is completely used.
8307   return NarrowedUsedBits.isAllOnesValue();
8308 }
8309
8310 /// \brief Check whether or not \p First and \p Second are next to each other
8311 /// in memory. This means that there is no hole between the bits loaded
8312 /// by \p First and the bits loaded by \p Second.
8313 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8314                                      const LoadedSlice &Second) {
8315   assert(First.Origin == Second.Origin && First.Origin &&
8316          "Unable to match different memory origins.");
8317   APInt UsedBits = First.getUsedBits();
8318   assert((UsedBits & Second.getUsedBits()) == 0 &&
8319          "Slices are not supposed to overlap.");
8320   UsedBits |= Second.getUsedBits();
8321   return areUsedBitsDense(UsedBits);
8322 }
8323
8324 /// \brief Adjust the \p GlobalLSCost according to the target
8325 /// paring capabilities and the layout of the slices.
8326 /// \pre \p GlobalLSCost should account for at least as many loads as
8327 /// there is in the slices in \p LoadedSlices.
8328 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8329                                  LoadedSlice::Cost &GlobalLSCost) {
8330   unsigned NumberOfSlices = LoadedSlices.size();
8331   // If there is less than 2 elements, no pairing is possible.
8332   if (NumberOfSlices < 2)
8333     return;
8334
8335   // Sort the slices so that elements that are likely to be next to each
8336   // other in memory are next to each other in the list.
8337   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8338             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8339     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8340     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8341   });
8342   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8343   // First (resp. Second) is the first (resp. Second) potentially candidate
8344   // to be placed in a paired load.
8345   const LoadedSlice *First = nullptr;
8346   const LoadedSlice *Second = nullptr;
8347   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8348                 // Set the beginning of the pair.
8349                                                            First = Second) {
8350
8351     Second = &LoadedSlices[CurrSlice];
8352
8353     // If First is NULL, it means we start a new pair.
8354     // Get to the next slice.
8355     if (!First)
8356       continue;
8357
8358     EVT LoadedType = First->getLoadedType();
8359
8360     // If the types of the slices are different, we cannot pair them.
8361     if (LoadedType != Second->getLoadedType())
8362       continue;
8363
8364     // Check if the target supplies paired loads for this type.
8365     unsigned RequiredAlignment = 0;
8366     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8367       // move to the next pair, this type is hopeless.
8368       Second = nullptr;
8369       continue;
8370     }
8371     // Check if we meet the alignment requirement.
8372     if (RequiredAlignment > First->getAlignment())
8373       continue;
8374
8375     // Check that both loads are next to each other in memory.
8376     if (!areSlicesNextToEachOther(*First, *Second))
8377       continue;
8378
8379     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8380     --GlobalLSCost.Loads;
8381     // Move to the next pair.
8382     Second = nullptr;
8383   }
8384 }
8385
8386 /// \brief Check the profitability of all involved LoadedSlice.
8387 /// Currently, it is considered profitable if there is exactly two
8388 /// involved slices (1) which are (2) next to each other in memory, and
8389 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8390 ///
8391 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8392 /// the elements themselves.
8393 ///
8394 /// FIXME: When the cost model will be mature enough, we can relax
8395 /// constraints (1) and (2).
8396 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8397                                 const APInt &UsedBits, bool ForCodeSize) {
8398   unsigned NumberOfSlices = LoadedSlices.size();
8399   if (StressLoadSlicing)
8400     return NumberOfSlices > 1;
8401
8402   // Check (1).
8403   if (NumberOfSlices != 2)
8404     return false;
8405
8406   // Check (2).
8407   if (!areUsedBitsDense(UsedBits))
8408     return false;
8409
8410   // Check (3).
8411   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8412   // The original code has one big load.
8413   OrigCost.Loads = 1;
8414   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8415     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8416     // Accumulate the cost of all the slices.
8417     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8418     GlobalSlicingCost += SliceCost;
8419
8420     // Account as cost in the original configuration the gain obtained
8421     // with the current slices.
8422     OrigCost.addSliceGain(LS);
8423   }
8424
8425   // If the target supports paired load, adjust the cost accordingly.
8426   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8427   return OrigCost > GlobalSlicingCost;
8428 }
8429
8430 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8431 /// operations, split it in the various pieces being extracted.
8432 ///
8433 /// This sort of thing is introduced by SROA.
8434 /// This slicing takes care not to insert overlapping loads.
8435 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8436 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8437   if (Level < AfterLegalizeDAG)
8438     return false;
8439
8440   LoadSDNode *LD = cast<LoadSDNode>(N);
8441   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8442       !LD->getValueType(0).isInteger())
8443     return false;
8444
8445   // Keep track of already used bits to detect overlapping values.
8446   // In that case, we will just abort the transformation.
8447   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8448
8449   SmallVector<LoadedSlice, 4> LoadedSlices;
8450
8451   // Check if this load is used as several smaller chunks of bits.
8452   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8453   // of computation for each trunc.
8454   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8455        UI != UIEnd; ++UI) {
8456     // Skip the uses of the chain.
8457     if (UI.getUse().getResNo() != 0)
8458       continue;
8459
8460     SDNode *User = *UI;
8461     unsigned Shift = 0;
8462
8463     // Check if this is a trunc(lshr).
8464     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8465         isa<ConstantSDNode>(User->getOperand(1))) {
8466       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8467       User = *User->use_begin();
8468     }
8469
8470     // At this point, User is a Truncate, iff we encountered, trunc or
8471     // trunc(lshr).
8472     if (User->getOpcode() != ISD::TRUNCATE)
8473       return false;
8474
8475     // The width of the type must be a power of 2 and greater than 8-bits.
8476     // Otherwise the load cannot be represented in LLVM IR.
8477     // Moreover, if we shifted with a non-8-bits multiple, the slice
8478     // will be across several bytes. We do not support that.
8479     unsigned Width = User->getValueSizeInBits(0);
8480     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8481       return 0;
8482
8483     // Build the slice for this chain of computations.
8484     LoadedSlice LS(User, LD, Shift, &DAG);
8485     APInt CurrentUsedBits = LS.getUsedBits();
8486
8487     // Check if this slice overlaps with another.
8488     if ((CurrentUsedBits & UsedBits) != 0)
8489       return false;
8490     // Update the bits used globally.
8491     UsedBits |= CurrentUsedBits;
8492
8493     // Check if the new slice would be legal.
8494     if (!LS.isLegal())
8495       return false;
8496
8497     // Record the slice.
8498     LoadedSlices.push_back(LS);
8499   }
8500
8501   // Abort slicing if it does not seem to be profitable.
8502   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8503     return false;
8504
8505   ++SlicedLoads;
8506
8507   // Rewrite each chain to use an independent load.
8508   // By construction, each chain can be represented by a unique load.
8509
8510   // Prepare the argument for the new token factor for all the slices.
8511   SmallVector<SDValue, 8> ArgChains;
8512   for (SmallVectorImpl<LoadedSlice>::const_iterator
8513            LSIt = LoadedSlices.begin(),
8514            LSItEnd = LoadedSlices.end();
8515        LSIt != LSItEnd; ++LSIt) {
8516     SDValue SliceInst = LSIt->loadSlice();
8517     CombineTo(LSIt->Inst, SliceInst, true);
8518     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8519       SliceInst = SliceInst.getOperand(0);
8520     assert(SliceInst->getOpcode() == ISD::LOAD &&
8521            "It takes more than a zext to get to the loaded slice!!");
8522     ArgChains.push_back(SliceInst.getValue(1));
8523   }
8524
8525   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8526                               &ArgChains[0], ArgChains.size());
8527   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8528   return true;
8529 }
8530
8531 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8532 /// load is having specific bytes cleared out.  If so, return the byte size
8533 /// being masked out and the shift amount.
8534 static std::pair<unsigned, unsigned>
8535 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8536   std::pair<unsigned, unsigned> Result(0, 0);
8537
8538   // Check for the structure we're looking for.
8539   if (V->getOpcode() != ISD::AND ||
8540       !isa<ConstantSDNode>(V->getOperand(1)) ||
8541       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8542     return Result;
8543
8544   // Check the chain and pointer.
8545   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8546   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8547
8548   // The store should be chained directly to the load or be an operand of a
8549   // tokenfactor.
8550   if (LD == Chain.getNode())
8551     ; // ok.
8552   else if (Chain->getOpcode() != ISD::TokenFactor)
8553     return Result; // Fail.
8554   else {
8555     bool isOk = false;
8556     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8557       if (Chain->getOperand(i).getNode() == LD) {
8558         isOk = true;
8559         break;
8560       }
8561     if (!isOk) return Result;
8562   }
8563
8564   // This only handles simple types.
8565   if (V.getValueType() != MVT::i16 &&
8566       V.getValueType() != MVT::i32 &&
8567       V.getValueType() != MVT::i64)
8568     return Result;
8569
8570   // Check the constant mask.  Invert it so that the bits being masked out are
8571   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8572   // follow the sign bit for uniformity.
8573   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8574   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8575   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8576   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8577   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8578   if (NotMaskLZ == 64) return Result;  // All zero mask.
8579
8580   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8581   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8582     return Result;
8583
8584   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8585   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8586     NotMaskLZ -= 64-V.getValueSizeInBits();
8587
8588   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8589   switch (MaskedBytes) {
8590   case 1:
8591   case 2:
8592   case 4: break;
8593   default: return Result; // All one mask, or 5-byte mask.
8594   }
8595
8596   // Verify that the first bit starts at a multiple of mask so that the access
8597   // is aligned the same as the access width.
8598   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8599
8600   Result.first = MaskedBytes;
8601   Result.second = NotMaskTZ/8;
8602   return Result;
8603 }
8604
8605
8606 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8607 /// provides a value as specified by MaskInfo.  If so, replace the specified
8608 /// store with a narrower store of truncated IVal.
8609 static SDNode *
8610 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8611                                 SDValue IVal, StoreSDNode *St,
8612                                 DAGCombiner *DC) {
8613   unsigned NumBytes = MaskInfo.first;
8614   unsigned ByteShift = MaskInfo.second;
8615   SelectionDAG &DAG = DC->getDAG();
8616
8617   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8618   // that uses this.  If not, this is not a replacement.
8619   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8620                                   ByteShift*8, (ByteShift+NumBytes)*8);
8621   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8622
8623   // Check that it is legal on the target to do this.  It is legal if the new
8624   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8625   // legalization.
8626   MVT VT = MVT::getIntegerVT(NumBytes*8);
8627   if (!DC->isTypeLegal(VT))
8628     return nullptr;
8629
8630   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8631   // shifted by ByteShift and truncated down to NumBytes.
8632   if (ByteShift)
8633     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8634                        DAG.getConstant(ByteShift*8,
8635                                     DC->getShiftAmountTy(IVal.getValueType())));
8636
8637   // Figure out the offset for the store and the alignment of the access.
8638   unsigned StOffset;
8639   unsigned NewAlign = St->getAlignment();
8640
8641   if (DAG.getTargetLoweringInfo().isLittleEndian())
8642     StOffset = ByteShift;
8643   else
8644     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8645
8646   SDValue Ptr = St->getBasePtr();
8647   if (StOffset) {
8648     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8649                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8650     NewAlign = MinAlign(NewAlign, StOffset);
8651   }
8652
8653   // Truncate down to the new size.
8654   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8655
8656   ++OpsNarrowed;
8657   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8658                       St->getPointerInfo().getWithOffset(StOffset),
8659                       false, false, NewAlign).getNode();
8660 }
8661
8662
8663 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8664 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8665 /// of the loaded bits, try narrowing the load and store if it would end up
8666 /// being a win for performance or code size.
8667 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8668   StoreSDNode *ST  = cast<StoreSDNode>(N);
8669   if (ST->isVolatile())
8670     return SDValue();
8671
8672   SDValue Chain = ST->getChain();
8673   SDValue Value = ST->getValue();
8674   SDValue Ptr   = ST->getBasePtr();
8675   EVT VT = Value.getValueType();
8676
8677   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8678     return SDValue();
8679
8680   unsigned Opc = Value.getOpcode();
8681
8682   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8683   // is a byte mask indicating a consecutive number of bytes, check to see if
8684   // Y is known to provide just those bytes.  If so, we try to replace the
8685   // load + replace + store sequence with a single (narrower) store, which makes
8686   // the load dead.
8687   if (Opc == ISD::OR) {
8688     std::pair<unsigned, unsigned> MaskedLoad;
8689     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8690     if (MaskedLoad.first)
8691       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8692                                                   Value.getOperand(1), ST,this))
8693         return SDValue(NewST, 0);
8694
8695     // Or is commutative, so try swapping X and Y.
8696     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8697     if (MaskedLoad.first)
8698       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8699                                                   Value.getOperand(0), ST,this))
8700         return SDValue(NewST, 0);
8701   }
8702
8703   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8704       Value.getOperand(1).getOpcode() != ISD::Constant)
8705     return SDValue();
8706
8707   SDValue N0 = Value.getOperand(0);
8708   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8709       Chain == SDValue(N0.getNode(), 1)) {
8710     LoadSDNode *LD = cast<LoadSDNode>(N0);
8711     if (LD->getBasePtr() != Ptr ||
8712         LD->getPointerInfo().getAddrSpace() !=
8713         ST->getPointerInfo().getAddrSpace())
8714       return SDValue();
8715
8716     // Find the type to narrow it the load / op / store to.
8717     SDValue N1 = Value.getOperand(1);
8718     unsigned BitWidth = N1.getValueSizeInBits();
8719     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8720     if (Opc == ISD::AND)
8721       Imm ^= APInt::getAllOnesValue(BitWidth);
8722     if (Imm == 0 || Imm.isAllOnesValue())
8723       return SDValue();
8724     unsigned ShAmt = Imm.countTrailingZeros();
8725     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8726     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8727     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8728     while (NewBW < BitWidth &&
8729            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8730              TLI.isNarrowingProfitable(VT, NewVT))) {
8731       NewBW = NextPowerOf2(NewBW);
8732       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8733     }
8734     if (NewBW >= BitWidth)
8735       return SDValue();
8736
8737     // If the lsb changed does not start at the type bitwidth boundary,
8738     // start at the previous one.
8739     if (ShAmt % NewBW)
8740       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8741     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8742                                    std::min(BitWidth, ShAmt + NewBW));
8743     if ((Imm & Mask) == Imm) {
8744       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8745       if (Opc == ISD::AND)
8746         NewImm ^= APInt::getAllOnesValue(NewBW);
8747       uint64_t PtrOff = ShAmt / 8;
8748       // For big endian targets, we need to adjust the offset to the pointer to
8749       // load the correct bytes.
8750       if (TLI.isBigEndian())
8751         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8752
8753       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8754       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8755       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8756         return SDValue();
8757
8758       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8759                                    Ptr.getValueType(), Ptr,
8760                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8761       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8762                                   LD->getChain(), NewPtr,
8763                                   LD->getPointerInfo().getWithOffset(PtrOff),
8764                                   LD->isVolatile(), LD->isNonTemporal(),
8765                                   LD->isInvariant(), NewAlign,
8766                                   LD->getTBAAInfo());
8767       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8768                                    DAG.getConstant(NewImm, NewVT));
8769       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8770                                    NewVal, NewPtr,
8771                                    ST->getPointerInfo().getWithOffset(PtrOff),
8772                                    false, false, NewAlign);
8773
8774       AddToWorkList(NewPtr.getNode());
8775       AddToWorkList(NewLD.getNode());
8776       AddToWorkList(NewVal.getNode());
8777       WorkListRemover DeadNodes(*this);
8778       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8779       ++OpsNarrowed;
8780       return NewST;
8781     }
8782   }
8783
8784   return SDValue();
8785 }
8786
8787 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8788 /// if the load value isn't used by any other operations, then consider
8789 /// transforming the pair to integer load / store operations if the target
8790 /// deems the transformation profitable.
8791 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8792   StoreSDNode *ST  = cast<StoreSDNode>(N);
8793   SDValue Chain = ST->getChain();
8794   SDValue Value = ST->getValue();
8795   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8796       Value.hasOneUse() &&
8797       Chain == SDValue(Value.getNode(), 1)) {
8798     LoadSDNode *LD = cast<LoadSDNode>(Value);
8799     EVT VT = LD->getMemoryVT();
8800     if (!VT.isFloatingPoint() ||
8801         VT != ST->getMemoryVT() ||
8802         LD->isNonTemporal() ||
8803         ST->isNonTemporal() ||
8804         LD->getPointerInfo().getAddrSpace() != 0 ||
8805         ST->getPointerInfo().getAddrSpace() != 0)
8806       return SDValue();
8807
8808     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8809     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8810         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8811         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8812         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8813       return SDValue();
8814
8815     unsigned LDAlign = LD->getAlignment();
8816     unsigned STAlign = ST->getAlignment();
8817     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8818     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8819     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8820       return SDValue();
8821
8822     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8823                                 LD->getChain(), LD->getBasePtr(),
8824                                 LD->getPointerInfo(),
8825                                 false, false, false, LDAlign);
8826
8827     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8828                                  NewLD, ST->getBasePtr(),
8829                                  ST->getPointerInfo(),
8830                                  false, false, STAlign);
8831
8832     AddToWorkList(NewLD.getNode());
8833     AddToWorkList(NewST.getNode());
8834     WorkListRemover DeadNodes(*this);
8835     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8836     ++LdStFP2Int;
8837     return NewST;
8838   }
8839
8840   return SDValue();
8841 }
8842
8843 /// Helper struct to parse and store a memory address as base + index + offset.
8844 /// We ignore sign extensions when it is safe to do so.
8845 /// The following two expressions are not equivalent. To differentiate we need
8846 /// to store whether there was a sign extension involved in the index
8847 /// computation.
8848 ///  (load (i64 add (i64 copyfromreg %c)
8849 ///                 (i64 signextend (add (i8 load %index)
8850 ///                                      (i8 1))))
8851 /// vs
8852 ///
8853 /// (load (i64 add (i64 copyfromreg %c)
8854 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8855 ///                                         (i32 1)))))
8856 struct BaseIndexOffset {
8857   SDValue Base;
8858   SDValue Index;
8859   int64_t Offset;
8860   bool IsIndexSignExt;
8861
8862   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8863
8864   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8865                   bool IsIndexSignExt) :
8866     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8867
8868   bool equalBaseIndex(const BaseIndexOffset &Other) {
8869     return Other.Base == Base && Other.Index == Index &&
8870       Other.IsIndexSignExt == IsIndexSignExt;
8871   }
8872
8873   /// Parses tree in Ptr for base, index, offset addresses.
8874   static BaseIndexOffset match(SDValue Ptr) {
8875     bool IsIndexSignExt = false;
8876
8877     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8878     // instruction, then it could be just the BASE or everything else we don't
8879     // know how to handle. Just use Ptr as BASE and give up.
8880     if (Ptr->getOpcode() != ISD::ADD)
8881       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8882
8883     // We know that we have at least an ADD instruction. Try to pattern match
8884     // the simple case of BASE + OFFSET.
8885     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8886       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8887       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8888                               IsIndexSignExt);
8889     }
8890
8891     // Inside a loop the current BASE pointer is calculated using an ADD and a
8892     // MUL instruction. In this case Ptr is the actual BASE pointer.
8893     // (i64 add (i64 %array_ptr)
8894     //          (i64 mul (i64 %induction_var)
8895     //                   (i64 %element_size)))
8896     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8897       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8898
8899     // Look at Base + Index + Offset cases.
8900     SDValue Base = Ptr->getOperand(0);
8901     SDValue IndexOffset = Ptr->getOperand(1);
8902
8903     // Skip signextends.
8904     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8905       IndexOffset = IndexOffset->getOperand(0);
8906       IsIndexSignExt = true;
8907     }
8908
8909     // Either the case of Base + Index (no offset) or something else.
8910     if (IndexOffset->getOpcode() != ISD::ADD)
8911       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8912
8913     // Now we have the case of Base + Index + offset.
8914     SDValue Index = IndexOffset->getOperand(0);
8915     SDValue Offset = IndexOffset->getOperand(1);
8916
8917     if (!isa<ConstantSDNode>(Offset))
8918       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8919
8920     // Ignore signextends.
8921     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8922       Index = Index->getOperand(0);
8923       IsIndexSignExt = true;
8924     } else IsIndexSignExt = false;
8925
8926     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8927     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8928   }
8929 };
8930
8931 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8932 /// is located in a sequence of memory operations connected by a chain.
8933 struct MemOpLink {
8934   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8935     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8936   // Ptr to the mem node.
8937   LSBaseSDNode *MemNode;
8938   // Offset from the base ptr.
8939   int64_t OffsetFromBase;
8940   // What is the sequence number of this mem node.
8941   // Lowest mem operand in the DAG starts at zero.
8942   unsigned SequenceNum;
8943 };
8944
8945 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8946   EVT MemVT = St->getMemoryVT();
8947   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8948   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8949     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8950
8951   // Don't merge vectors into wider inputs.
8952   if (MemVT.isVector() || !MemVT.isSimple())
8953     return false;
8954
8955   // Perform an early exit check. Do not bother looking at stored values that
8956   // are not constants or loads.
8957   SDValue StoredVal = St->getValue();
8958   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8959   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8960       !IsLoadSrc)
8961     return false;
8962
8963   // Only look at ends of store sequences.
8964   SDValue Chain = SDValue(St, 1);
8965   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8966     return false;
8967
8968   // This holds the base pointer, index, and the offset in bytes from the base
8969   // pointer.
8970   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8971
8972   // We must have a base and an offset.
8973   if (!BasePtr.Base.getNode())
8974     return false;
8975
8976   // Do not handle stores to undef base pointers.
8977   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8978     return false;
8979
8980   // Save the LoadSDNodes that we find in the chain.
8981   // We need to make sure that these nodes do not interfere with
8982   // any of the store nodes.
8983   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8984
8985   // Save the StoreSDNodes that we find in the chain.
8986   SmallVector<MemOpLink, 8> StoreNodes;
8987
8988   // Walk up the chain and look for nodes with offsets from the same
8989   // base pointer. Stop when reaching an instruction with a different kind
8990   // or instruction which has a different base pointer.
8991   unsigned Seq = 0;
8992   StoreSDNode *Index = St;
8993   while (Index) {
8994     // If the chain has more than one use, then we can't reorder the mem ops.
8995     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8996       break;
8997
8998     // Find the base pointer and offset for this memory node.
8999     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9000
9001     // Check that the base pointer is the same as the original one.
9002     if (!Ptr.equalBaseIndex(BasePtr))
9003       break;
9004
9005     // Check that the alignment is the same.
9006     if (Index->getAlignment() != St->getAlignment())
9007       break;
9008
9009     // The memory operands must not be volatile.
9010     if (Index->isVolatile() || Index->isIndexed())
9011       break;
9012
9013     // No truncation.
9014     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9015       if (St->isTruncatingStore())
9016         break;
9017
9018     // The stored memory type must be the same.
9019     if (Index->getMemoryVT() != MemVT)
9020       break;
9021
9022     // We do not allow unaligned stores because we want to prevent overriding
9023     // stores.
9024     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9025       break;
9026
9027     // We found a potential memory operand to merge.
9028     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9029
9030     // Find the next memory operand in the chain. If the next operand in the
9031     // chain is a store then move up and continue the scan with the next
9032     // memory operand. If the next operand is a load save it and use alias
9033     // information to check if it interferes with anything.
9034     SDNode *NextInChain = Index->getChain().getNode();
9035     while (1) {
9036       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9037         // We found a store node. Use it for the next iteration.
9038         Index = STn;
9039         break;
9040       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9041         if (Ldn->isVolatile()) {
9042           Index = nullptr;
9043           break;
9044         }
9045
9046         // Save the load node for later. Continue the scan.
9047         AliasLoadNodes.push_back(Ldn);
9048         NextInChain = Ldn->getChain().getNode();
9049         continue;
9050       } else {
9051         Index = nullptr;
9052         break;
9053       }
9054     }
9055   }
9056
9057   // Check if there is anything to merge.
9058   if (StoreNodes.size() < 2)
9059     return false;
9060
9061   // Sort the memory operands according to their distance from the base pointer.
9062   std::sort(StoreNodes.begin(), StoreNodes.end(),
9063             [](MemOpLink LHS, MemOpLink RHS) {
9064     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9065            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9066             LHS.SequenceNum > RHS.SequenceNum);
9067   });
9068
9069   // Scan the memory operations on the chain and find the first non-consecutive
9070   // store memory address.
9071   unsigned LastConsecutiveStore = 0;
9072   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9073   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9074
9075     // Check that the addresses are consecutive starting from the second
9076     // element in the list of stores.
9077     if (i > 0) {
9078       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9079       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9080         break;
9081     }
9082
9083     bool Alias = false;
9084     // Check if this store interferes with any of the loads that we found.
9085     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9086       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9087         Alias = true;
9088         break;
9089       }
9090     // We found a load that alias with this store. Stop the sequence.
9091     if (Alias)
9092       break;
9093
9094     // Mark this node as useful.
9095     LastConsecutiveStore = i;
9096   }
9097
9098   // The node with the lowest store address.
9099   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9100
9101   // Store the constants into memory as one consecutive store.
9102   if (!IsLoadSrc) {
9103     unsigned LastLegalType = 0;
9104     unsigned LastLegalVectorType = 0;
9105     bool NonZero = false;
9106     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9107       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9108       SDValue StoredVal = St->getValue();
9109
9110       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9111         NonZero |= !C->isNullValue();
9112       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9113         NonZero |= !C->getConstantFPValue()->isNullValue();
9114       } else {
9115         // Non-constant.
9116         break;
9117       }
9118
9119       // Find a legal type for the constant store.
9120       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9121       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9122       if (TLI.isTypeLegal(StoreTy))
9123         LastLegalType = i+1;
9124       // Or check whether a truncstore is legal.
9125       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9126                TargetLowering::TypePromoteInteger) {
9127         EVT LegalizedStoredValueTy =
9128           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9129         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9130           LastLegalType = i+1;
9131       }
9132
9133       // Find a legal type for the vector store.
9134       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9135       if (TLI.isTypeLegal(Ty))
9136         LastLegalVectorType = i + 1;
9137     }
9138
9139     // We only use vectors if the constant is known to be zero and the
9140     // function is not marked with the noimplicitfloat attribute.
9141     if (NonZero || NoVectors)
9142       LastLegalVectorType = 0;
9143
9144     // Check if we found a legal integer type to store.
9145     if (LastLegalType == 0 && LastLegalVectorType == 0)
9146       return false;
9147
9148     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9149     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9150
9151     // Make sure we have something to merge.
9152     if (NumElem < 2)
9153       return false;
9154
9155     unsigned EarliestNodeUsed = 0;
9156     for (unsigned i=0; i < NumElem; ++i) {
9157       // Find a chain for the new wide-store operand. Notice that some
9158       // of the store nodes that we found may not be selected for inclusion
9159       // in the wide store. The chain we use needs to be the chain of the
9160       // earliest store node which is *used* and replaced by the wide store.
9161       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9162         EarliestNodeUsed = i;
9163     }
9164
9165     // The earliest Node in the DAG.
9166     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9167     SDLoc DL(StoreNodes[0].MemNode);
9168
9169     SDValue StoredVal;
9170     if (UseVector) {
9171       // Find a legal type for the vector store.
9172       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9173       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9174       StoredVal = DAG.getConstant(0, Ty);
9175     } else {
9176       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9177       APInt StoreInt(StoreBW, 0);
9178
9179       // Construct a single integer constant which is made of the smaller
9180       // constant inputs.
9181       bool IsLE = TLI.isLittleEndian();
9182       for (unsigned i = 0; i < NumElem ; ++i) {
9183         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9184         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9185         SDValue Val = St->getValue();
9186         StoreInt<<=ElementSizeBytes*8;
9187         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9188           StoreInt|=C->getAPIntValue().zext(StoreBW);
9189         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9190           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9191         } else {
9192           assert(false && "Invalid constant element type");
9193         }
9194       }
9195
9196       // Create the new Load and Store operations.
9197       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9198       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9199     }
9200
9201     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9202                                     FirstInChain->getBasePtr(),
9203                                     FirstInChain->getPointerInfo(),
9204                                     false, false,
9205                                     FirstInChain->getAlignment());
9206
9207     // Replace the first store with the new store
9208     CombineTo(EarliestOp, NewStore);
9209     // Erase all other stores.
9210     for (unsigned i = 0; i < NumElem ; ++i) {
9211       if (StoreNodes[i].MemNode == EarliestOp)
9212         continue;
9213       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9214       // ReplaceAllUsesWith will replace all uses that existed when it was
9215       // called, but graph optimizations may cause new ones to appear. For
9216       // example, the case in pr14333 looks like
9217       //
9218       //  St's chain -> St -> another store -> X
9219       //
9220       // And the only difference from St to the other store is the chain.
9221       // When we change it's chain to be St's chain they become identical,
9222       // get CSEed and the net result is that X is now a use of St.
9223       // Since we know that St is redundant, just iterate.
9224       while (!St->use_empty())
9225         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9226       removeFromWorkList(St);
9227       DAG.DeleteNode(St);
9228     }
9229
9230     return true;
9231   }
9232
9233   // Below we handle the case of multiple consecutive stores that
9234   // come from multiple consecutive loads. We merge them into a single
9235   // wide load and a single wide store.
9236
9237   // Look for load nodes which are used by the stored values.
9238   SmallVector<MemOpLink, 8> LoadNodes;
9239
9240   // Find acceptable loads. Loads need to have the same chain (token factor),
9241   // must not be zext, volatile, indexed, and they must be consecutive.
9242   BaseIndexOffset LdBasePtr;
9243   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9244     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9245     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9246     if (!Ld) break;
9247
9248     // Loads must only have one use.
9249     if (!Ld->hasNUsesOfValue(1, 0))
9250       break;
9251
9252     // Check that the alignment is the same as the stores.
9253     if (Ld->getAlignment() != St->getAlignment())
9254       break;
9255
9256     // The memory operands must not be volatile.
9257     if (Ld->isVolatile() || Ld->isIndexed())
9258       break;
9259
9260     // We do not accept ext loads.
9261     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9262       break;
9263
9264     // The stored memory type must be the same.
9265     if (Ld->getMemoryVT() != MemVT)
9266       break;
9267
9268     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9269     // If this is not the first ptr that we check.
9270     if (LdBasePtr.Base.getNode()) {
9271       // The base ptr must be the same.
9272       if (!LdPtr.equalBaseIndex(LdBasePtr))
9273         break;
9274     } else {
9275       // Check that all other base pointers are the same as this one.
9276       LdBasePtr = LdPtr;
9277     }
9278
9279     // We found a potential memory operand to merge.
9280     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9281   }
9282
9283   if (LoadNodes.size() < 2)
9284     return false;
9285
9286   // Scan the memory operations on the chain and find the first non-consecutive
9287   // load memory address. These variables hold the index in the store node
9288   // array.
9289   unsigned LastConsecutiveLoad = 0;
9290   // This variable refers to the size and not index in the array.
9291   unsigned LastLegalVectorType = 0;
9292   unsigned LastLegalIntegerType = 0;
9293   StartAddress = LoadNodes[0].OffsetFromBase;
9294   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9295   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9296     // All loads much share the same chain.
9297     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9298       break;
9299
9300     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9301     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9302       break;
9303     LastConsecutiveLoad = i;
9304
9305     // Find a legal type for the vector store.
9306     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9307     if (TLI.isTypeLegal(StoreTy))
9308       LastLegalVectorType = i + 1;
9309
9310     // Find a legal type for the integer store.
9311     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9312     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9313     if (TLI.isTypeLegal(StoreTy))
9314       LastLegalIntegerType = i + 1;
9315     // Or check whether a truncstore and extload is legal.
9316     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9317              TargetLowering::TypePromoteInteger) {
9318       EVT LegalizedStoredValueTy =
9319         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9320       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9321           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9322           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9323           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9324         LastLegalIntegerType = i+1;
9325     }
9326   }
9327
9328   // Only use vector types if the vector type is larger than the integer type.
9329   // If they are the same, use integers.
9330   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9331   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9332
9333   // We add +1 here because the LastXXX variables refer to location while
9334   // the NumElem refers to array/index size.
9335   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9336   NumElem = std::min(LastLegalType, NumElem);
9337
9338   if (NumElem < 2)
9339     return false;
9340
9341   // The earliest Node in the DAG.
9342   unsigned EarliestNodeUsed = 0;
9343   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9344   for (unsigned i=1; i<NumElem; ++i) {
9345     // Find a chain for the new wide-store operand. Notice that some
9346     // of the store nodes that we found may not be selected for inclusion
9347     // in the wide store. The chain we use needs to be the chain of the
9348     // earliest store node which is *used* and replaced by the wide store.
9349     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9350       EarliestNodeUsed = i;
9351   }
9352
9353   // Find if it is better to use vectors or integers to load and store
9354   // to memory.
9355   EVT JointMemOpVT;
9356   if (UseVectorTy) {
9357     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9358   } else {
9359     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9360     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9361   }
9362
9363   SDLoc LoadDL(LoadNodes[0].MemNode);
9364   SDLoc StoreDL(StoreNodes[0].MemNode);
9365
9366   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9367   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9368                                 FirstLoad->getChain(),
9369                                 FirstLoad->getBasePtr(),
9370                                 FirstLoad->getPointerInfo(),
9371                                 false, false, false,
9372                                 FirstLoad->getAlignment());
9373
9374   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9375                                   FirstInChain->getBasePtr(),
9376                                   FirstInChain->getPointerInfo(), false, false,
9377                                   FirstInChain->getAlignment());
9378
9379   // Replace one of the loads with the new load.
9380   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9381   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9382                                 SDValue(NewLoad.getNode(), 1));
9383
9384   // Remove the rest of the load chains.
9385   for (unsigned i = 1; i < NumElem ; ++i) {
9386     // Replace all chain users of the old load nodes with the chain of the new
9387     // load node.
9388     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9389     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9390   }
9391
9392   // Replace the first store with the new store.
9393   CombineTo(EarliestOp, NewStore);
9394   // Erase all other stores.
9395   for (unsigned i = 0; i < NumElem ; ++i) {
9396     // Remove all Store nodes.
9397     if (StoreNodes[i].MemNode == EarliestOp)
9398       continue;
9399     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9400     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9401     removeFromWorkList(St);
9402     DAG.DeleteNode(St);
9403   }
9404
9405   return true;
9406 }
9407
9408 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9409   StoreSDNode *ST  = cast<StoreSDNode>(N);
9410   SDValue Chain = ST->getChain();
9411   SDValue Value = ST->getValue();
9412   SDValue Ptr   = ST->getBasePtr();
9413
9414   // If this is a store of a bit convert, store the input value if the
9415   // resultant store does not need a higher alignment than the original.
9416   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9417       ST->isUnindexed()) {
9418     unsigned OrigAlign = ST->getAlignment();
9419     EVT SVT = Value.getOperand(0).getValueType();
9420     unsigned Align = TLI.getDataLayout()->
9421       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9422     if (Align <= OrigAlign &&
9423         ((!LegalOperations && !ST->isVolatile()) ||
9424          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9425       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9426                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9427                           ST->isNonTemporal(), OrigAlign,
9428                           ST->getTBAAInfo());
9429   }
9430
9431   // Turn 'store undef, Ptr' -> nothing.
9432   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9433     return Chain;
9434
9435   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9436   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9437     // NOTE: If the original store is volatile, this transform must not increase
9438     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9439     // processor operation but an i64 (which is not legal) requires two.  So the
9440     // transform should not be done in this case.
9441     if (Value.getOpcode() != ISD::TargetConstantFP) {
9442       SDValue Tmp;
9443       switch (CFP->getSimpleValueType(0).SimpleTy) {
9444       default: llvm_unreachable("Unknown FP type");
9445       case MVT::f16:    // We don't do this for these yet.
9446       case MVT::f80:
9447       case MVT::f128:
9448       case MVT::ppcf128:
9449         break;
9450       case MVT::f32:
9451         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9452             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9453           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9454                               bitcastToAPInt().getZExtValue(), MVT::i32);
9455           return DAG.getStore(Chain, SDLoc(N), Tmp,
9456                               Ptr, ST->getMemOperand());
9457         }
9458         break;
9459       case MVT::f64:
9460         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9461              !ST->isVolatile()) ||
9462             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9463           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9464                                 getZExtValue(), MVT::i64);
9465           return DAG.getStore(Chain, SDLoc(N), Tmp,
9466                               Ptr, ST->getMemOperand());
9467         }
9468
9469         if (!ST->isVolatile() &&
9470             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9471           // Many FP stores are not made apparent until after legalize, e.g. for
9472           // argument passing.  Since this is so common, custom legalize the
9473           // 64-bit integer store into two 32-bit stores.
9474           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9475           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9476           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9477           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9478
9479           unsigned Alignment = ST->getAlignment();
9480           bool isVolatile = ST->isVolatile();
9481           bool isNonTemporal = ST->isNonTemporal();
9482           const MDNode *TBAAInfo = ST->getTBAAInfo();
9483
9484           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9485                                      Ptr, ST->getPointerInfo(),
9486                                      isVolatile, isNonTemporal,
9487                                      ST->getAlignment(), TBAAInfo);
9488           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9489                             DAG.getConstant(4, Ptr.getValueType()));
9490           Alignment = MinAlign(Alignment, 4U);
9491           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9492                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9493                                      isVolatile, isNonTemporal,
9494                                      Alignment, TBAAInfo);
9495           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9496                              St0, St1);
9497         }
9498
9499         break;
9500       }
9501     }
9502   }
9503
9504   // Try to infer better alignment information than the store already has.
9505   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9506     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9507       if (Align > ST->getAlignment())
9508         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9509                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9510                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9511                                  ST->getTBAAInfo());
9512     }
9513   }
9514
9515   // Try transforming a pair floating point load / store ops to integer
9516   // load / store ops.
9517   SDValue NewST = TransformFPLoadStorePair(N);
9518   if (NewST.getNode())
9519     return NewST;
9520
9521   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9522     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9523 #ifndef NDEBUG
9524   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9525       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9526     UseAA = false;
9527 #endif
9528   if (UseAA && ST->isUnindexed()) {
9529     // Walk up chain skipping non-aliasing memory nodes.
9530     SDValue BetterChain = FindBetterChain(N, Chain);
9531
9532     // If there is a better chain.
9533     if (Chain != BetterChain) {
9534       SDValue ReplStore;
9535
9536       // Replace the chain to avoid dependency.
9537       if (ST->isTruncatingStore()) {
9538         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9539                                       ST->getMemoryVT(), ST->getMemOperand());
9540       } else {
9541         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9542                                  ST->getMemOperand());
9543       }
9544
9545       // Create token to keep both nodes around.
9546       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9547                                   MVT::Other, Chain, ReplStore);
9548
9549       // Make sure the new and old chains are cleaned up.
9550       AddToWorkList(Token.getNode());
9551
9552       // Don't add users to work list.
9553       return CombineTo(N, Token, false);
9554     }
9555   }
9556
9557   // Try transforming N to an indexed store.
9558   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9559     return SDValue(N, 0);
9560
9561   // FIXME: is there such a thing as a truncating indexed store?
9562   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9563       Value.getValueType().isInteger()) {
9564     // See if we can simplify the input to this truncstore with knowledge that
9565     // only the low bits are being used.  For example:
9566     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9567     SDValue Shorter =
9568       GetDemandedBits(Value,
9569                       APInt::getLowBitsSet(
9570                         Value.getValueType().getScalarType().getSizeInBits(),
9571                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9572     AddToWorkList(Value.getNode());
9573     if (Shorter.getNode())
9574       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9575                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9576
9577     // Otherwise, see if we can simplify the operation with
9578     // SimplifyDemandedBits, which only works if the value has a single use.
9579     if (SimplifyDemandedBits(Value,
9580                         APInt::getLowBitsSet(
9581                           Value.getValueType().getScalarType().getSizeInBits(),
9582                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9583       return SDValue(N, 0);
9584   }
9585
9586   // If this is a load followed by a store to the same location, then the store
9587   // is dead/noop.
9588   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9589     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9590         ST->isUnindexed() && !ST->isVolatile() &&
9591         // There can't be any side effects between the load and store, such as
9592         // a call or store.
9593         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9594       // The store is dead, remove it.
9595       return Chain;
9596     }
9597   }
9598
9599   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9600   // truncating store.  We can do this even if this is already a truncstore.
9601   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9602       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9603       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9604                             ST->getMemoryVT())) {
9605     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9606                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9607   }
9608
9609   // Only perform this optimization before the types are legal, because we
9610   // don't want to perform this optimization on every DAGCombine invocation.
9611   if (!LegalTypes) {
9612     bool EverChanged = false;
9613
9614     do {
9615       // There can be multiple store sequences on the same chain.
9616       // Keep trying to merge store sequences until we are unable to do so
9617       // or until we merge the last store on the chain.
9618       bool Changed = MergeConsecutiveStores(ST);
9619       EverChanged |= Changed;
9620       if (!Changed) break;
9621     } while (ST->getOpcode() != ISD::DELETED_NODE);
9622
9623     if (EverChanged)
9624       return SDValue(N, 0);
9625   }
9626
9627   return ReduceLoadOpStoreWidth(N);
9628 }
9629
9630 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9631   SDValue InVec = N->getOperand(0);
9632   SDValue InVal = N->getOperand(1);
9633   SDValue EltNo = N->getOperand(2);
9634   SDLoc dl(N);
9635
9636   // If the inserted element is an UNDEF, just use the input vector.
9637   if (InVal.getOpcode() == ISD::UNDEF)
9638     return InVec;
9639
9640   EVT VT = InVec.getValueType();
9641
9642   // If we can't generate a legal BUILD_VECTOR, exit
9643   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9644     return SDValue();
9645
9646   // Check that we know which element is being inserted
9647   if (!isa<ConstantSDNode>(EltNo))
9648     return SDValue();
9649   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9650
9651   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9652   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9653   // vector elements.
9654   SmallVector<SDValue, 8> Ops;
9655   // Do not combine these two vectors if the output vector will not replace
9656   // the input vector.
9657   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9658     Ops.append(InVec.getNode()->op_begin(),
9659                InVec.getNode()->op_end());
9660   } else if (InVec.getOpcode() == ISD::UNDEF) {
9661     unsigned NElts = VT.getVectorNumElements();
9662     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9663   } else {
9664     return SDValue();
9665   }
9666
9667   // Insert the element
9668   if (Elt < Ops.size()) {
9669     // All the operands of BUILD_VECTOR must have the same type;
9670     // we enforce that here.
9671     EVT OpVT = Ops[0].getValueType();
9672     if (InVal.getValueType() != OpVT)
9673       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9674                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9675                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9676     Ops[Elt] = InVal;
9677   }
9678
9679   // Return the new vector
9680   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9681                      VT, &Ops[0], Ops.size());
9682 }
9683
9684 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9685   // (vextract (scalar_to_vector val, 0) -> val
9686   SDValue InVec = N->getOperand(0);
9687   EVT VT = InVec.getValueType();
9688   EVT NVT = N->getValueType(0);
9689
9690   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9691     // Check if the result type doesn't match the inserted element type. A
9692     // SCALAR_TO_VECTOR may truncate the inserted element and the
9693     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9694     SDValue InOp = InVec.getOperand(0);
9695     if (InOp.getValueType() != NVT) {
9696       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9697       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9698     }
9699     return InOp;
9700   }
9701
9702   SDValue EltNo = N->getOperand(1);
9703   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9704
9705   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9706   // We only perform this optimization before the op legalization phase because
9707   // we may introduce new vector instructions which are not backed by TD
9708   // patterns. For example on AVX, extracting elements from a wide vector
9709   // without using extract_subvector. However, if we can find an underlying
9710   // scalar value, then we can always use that.
9711   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9712       && ConstEltNo) {
9713     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9714     int NumElem = VT.getVectorNumElements();
9715     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9716     // Find the new index to extract from.
9717     int OrigElt = SVOp->getMaskElt(Elt);
9718
9719     // Extracting an undef index is undef.
9720     if (OrigElt == -1)
9721       return DAG.getUNDEF(NVT);
9722
9723     // Select the right vector half to extract from.
9724     SDValue SVInVec;
9725     if (OrigElt < NumElem) {
9726       SVInVec = InVec->getOperand(0);
9727     } else {
9728       SVInVec = InVec->getOperand(1);
9729       OrigElt -= NumElem;
9730     }
9731
9732     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9733       SDValue InOp = SVInVec.getOperand(OrigElt);
9734       if (InOp.getValueType() != NVT) {
9735         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9736         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9737       }
9738
9739       return InOp;
9740     }
9741
9742     // FIXME: We should handle recursing on other vector shuffles and
9743     // scalar_to_vector here as well.
9744
9745     if (!LegalOperations) {
9746       EVT IndexTy = TLI.getVectorIdxTy();
9747       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9748                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9749     }
9750   }
9751
9752   // Perform only after legalization to ensure build_vector / vector_shuffle
9753   // optimizations have already been done.
9754   if (!LegalOperations) return SDValue();
9755
9756   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9757   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9758   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9759
9760   if (ConstEltNo) {
9761     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9762     bool NewLoad = false;
9763     bool BCNumEltsChanged = false;
9764     EVT ExtVT = VT.getVectorElementType();
9765     EVT LVT = ExtVT;
9766
9767     // If the result of load has to be truncated, then it's not necessarily
9768     // profitable.
9769     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9770       return SDValue();
9771
9772     if (InVec.getOpcode() == ISD::BITCAST) {
9773       // Don't duplicate a load with other uses.
9774       if (!InVec.hasOneUse())
9775         return SDValue();
9776
9777       EVT BCVT = InVec.getOperand(0).getValueType();
9778       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9779         return SDValue();
9780       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9781         BCNumEltsChanged = true;
9782       InVec = InVec.getOperand(0);
9783       ExtVT = BCVT.getVectorElementType();
9784       NewLoad = true;
9785     }
9786
9787     LoadSDNode *LN0 = nullptr;
9788     const ShuffleVectorSDNode *SVN = nullptr;
9789     if (ISD::isNormalLoad(InVec.getNode())) {
9790       LN0 = cast<LoadSDNode>(InVec);
9791     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9792                InVec.getOperand(0).getValueType() == ExtVT &&
9793                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9794       // Don't duplicate a load with other uses.
9795       if (!InVec.hasOneUse())
9796         return SDValue();
9797
9798       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9799     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9800       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9801       // =>
9802       // (load $addr+1*size)
9803
9804       // Don't duplicate a load with other uses.
9805       if (!InVec.hasOneUse())
9806         return SDValue();
9807
9808       // If the bit convert changed the number of elements, it is unsafe
9809       // to examine the mask.
9810       if (BCNumEltsChanged)
9811         return SDValue();
9812
9813       // Select the input vector, guarding against out of range extract vector.
9814       unsigned NumElems = VT.getVectorNumElements();
9815       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9816       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9817
9818       if (InVec.getOpcode() == ISD::BITCAST) {
9819         // Don't duplicate a load with other uses.
9820         if (!InVec.hasOneUse())
9821           return SDValue();
9822
9823         InVec = InVec.getOperand(0);
9824       }
9825       if (ISD::isNormalLoad(InVec.getNode())) {
9826         LN0 = cast<LoadSDNode>(InVec);
9827         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9828       }
9829     }
9830
9831     // Make sure we found a non-volatile load and the extractelement is
9832     // the only use.
9833     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9834       return SDValue();
9835
9836     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9837     if (Elt == -1)
9838       return DAG.getUNDEF(LVT);
9839
9840     unsigned Align = LN0->getAlignment();
9841     if (NewLoad) {
9842       // Check the resultant load doesn't need a higher alignment than the
9843       // original load.
9844       unsigned NewAlign =
9845         TLI.getDataLayout()
9846             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9847
9848       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9849         return SDValue();
9850
9851       Align = NewAlign;
9852     }
9853
9854     SDValue NewPtr = LN0->getBasePtr();
9855     unsigned PtrOff = 0;
9856
9857     if (Elt) {
9858       PtrOff = LVT.getSizeInBits() * Elt / 8;
9859       EVT PtrType = NewPtr.getValueType();
9860       if (TLI.isBigEndian())
9861         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9862       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9863                            DAG.getConstant(PtrOff, PtrType));
9864     }
9865
9866     // The replacement we need to do here is a little tricky: we need to
9867     // replace an extractelement of a load with a load.
9868     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9869     // Note that this replacement assumes that the extractvalue is the only
9870     // use of the load; that's okay because we don't want to perform this
9871     // transformation in other cases anyway.
9872     SDValue Load;
9873     SDValue Chain;
9874     if (NVT.bitsGT(LVT)) {
9875       // If the result type of vextract is wider than the load, then issue an
9876       // extending load instead.
9877       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9878         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9879       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9880                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9881                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9882                             Align, LN0->getTBAAInfo());
9883       Chain = Load.getValue(1);
9884     } else {
9885       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9886                          LN0->getPointerInfo().getWithOffset(PtrOff),
9887                          LN0->isVolatile(), LN0->isNonTemporal(),
9888                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9889       Chain = Load.getValue(1);
9890       if (NVT.bitsLT(LVT))
9891         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9892       else
9893         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9894     }
9895     WorkListRemover DeadNodes(*this);
9896     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9897     SDValue To[] = { Load, Chain };
9898     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9899     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9900     // worklist explicitly as well.
9901     AddToWorkList(Load.getNode());
9902     AddUsersToWorkList(Load.getNode()); // Add users too
9903     // Make sure to revisit this node to clean it up; it will usually be dead.
9904     AddToWorkList(N);
9905     return SDValue(N, 0);
9906   }
9907
9908   return SDValue();
9909 }
9910
9911 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9912 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9913   // We perform this optimization post type-legalization because
9914   // the type-legalizer often scalarizes integer-promoted vectors.
9915   // Performing this optimization before may create bit-casts which
9916   // will be type-legalized to complex code sequences.
9917   // We perform this optimization only before the operation legalizer because we
9918   // may introduce illegal operations.
9919   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9920     return SDValue();
9921
9922   unsigned NumInScalars = N->getNumOperands();
9923   SDLoc dl(N);
9924   EVT VT = N->getValueType(0);
9925
9926   // Check to see if this is a BUILD_VECTOR of a bunch of values
9927   // which come from any_extend or zero_extend nodes. If so, we can create
9928   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9929   // optimizations. We do not handle sign-extend because we can't fill the sign
9930   // using shuffles.
9931   EVT SourceType = MVT::Other;
9932   bool AllAnyExt = true;
9933
9934   for (unsigned i = 0; i != NumInScalars; ++i) {
9935     SDValue In = N->getOperand(i);
9936     // Ignore undef inputs.
9937     if (In.getOpcode() == ISD::UNDEF) continue;
9938
9939     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9940     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9941
9942     // Abort if the element is not an extension.
9943     if (!ZeroExt && !AnyExt) {
9944       SourceType = MVT::Other;
9945       break;
9946     }
9947
9948     // The input is a ZeroExt or AnyExt. Check the original type.
9949     EVT InTy = In.getOperand(0).getValueType();
9950
9951     // Check that all of the widened source types are the same.
9952     if (SourceType == MVT::Other)
9953       // First time.
9954       SourceType = InTy;
9955     else if (InTy != SourceType) {
9956       // Multiple income types. Abort.
9957       SourceType = MVT::Other;
9958       break;
9959     }
9960
9961     // Check if all of the extends are ANY_EXTENDs.
9962     AllAnyExt &= AnyExt;
9963   }
9964
9965   // In order to have valid types, all of the inputs must be extended from the
9966   // same source type and all of the inputs must be any or zero extend.
9967   // Scalar sizes must be a power of two.
9968   EVT OutScalarTy = VT.getScalarType();
9969   bool ValidTypes = SourceType != MVT::Other &&
9970                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9971                  isPowerOf2_32(SourceType.getSizeInBits());
9972
9973   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9974   // turn into a single shuffle instruction.
9975   if (!ValidTypes)
9976     return SDValue();
9977
9978   bool isLE = TLI.isLittleEndian();
9979   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9980   assert(ElemRatio > 1 && "Invalid element size ratio");
9981   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9982                                DAG.getConstant(0, SourceType);
9983
9984   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9985   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9986
9987   // Populate the new build_vector
9988   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9989     SDValue Cast = N->getOperand(i);
9990     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9991             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9992             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9993     SDValue In;
9994     if (Cast.getOpcode() == ISD::UNDEF)
9995       In = DAG.getUNDEF(SourceType);
9996     else
9997       In = Cast->getOperand(0);
9998     unsigned Index = isLE ? (i * ElemRatio) :
9999                             (i * ElemRatio + (ElemRatio - 1));
10000
10001     assert(Index < Ops.size() && "Invalid index");
10002     Ops[Index] = In;
10003   }
10004
10005   // The type of the new BUILD_VECTOR node.
10006   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10007   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10008          "Invalid vector size");
10009   // Check if the new vector type is legal.
10010   if (!isTypeLegal(VecVT)) return SDValue();
10011
10012   // Make the new BUILD_VECTOR.
10013   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10014
10015   // The new BUILD_VECTOR node has the potential to be further optimized.
10016   AddToWorkList(BV.getNode());
10017   // Bitcast to the desired type.
10018   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10019 }
10020
10021 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10022   EVT VT = N->getValueType(0);
10023
10024   unsigned NumInScalars = N->getNumOperands();
10025   SDLoc dl(N);
10026
10027   EVT SrcVT = MVT::Other;
10028   unsigned Opcode = ISD::DELETED_NODE;
10029   unsigned NumDefs = 0;
10030
10031   for (unsigned i = 0; i != NumInScalars; ++i) {
10032     SDValue In = N->getOperand(i);
10033     unsigned Opc = In.getOpcode();
10034
10035     if (Opc == ISD::UNDEF)
10036       continue;
10037
10038     // If all scalar values are floats and converted from integers.
10039     if (Opcode == ISD::DELETED_NODE &&
10040         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10041       Opcode = Opc;
10042     }
10043
10044     if (Opc != Opcode)
10045       return SDValue();
10046
10047     EVT InVT = In.getOperand(0).getValueType();
10048
10049     // If all scalar values are typed differently, bail out. It's chosen to
10050     // simplify BUILD_VECTOR of integer types.
10051     if (SrcVT == MVT::Other)
10052       SrcVT = InVT;
10053     if (SrcVT != InVT)
10054       return SDValue();
10055     NumDefs++;
10056   }
10057
10058   // If the vector has just one element defined, it's not worth to fold it into
10059   // a vectorized one.
10060   if (NumDefs < 2)
10061     return SDValue();
10062
10063   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10064          && "Should only handle conversion from integer to float.");
10065   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10066
10067   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10068
10069   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10070     return SDValue();
10071
10072   SmallVector<SDValue, 8> Opnds;
10073   for (unsigned i = 0; i != NumInScalars; ++i) {
10074     SDValue In = N->getOperand(i);
10075
10076     if (In.getOpcode() == ISD::UNDEF)
10077       Opnds.push_back(DAG.getUNDEF(SrcVT));
10078     else
10079       Opnds.push_back(In.getOperand(0));
10080   }
10081   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10082                            &Opnds[0], Opnds.size());
10083   AddToWorkList(BV.getNode());
10084
10085   return DAG.getNode(Opcode, dl, VT, BV);
10086 }
10087
10088 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10089   unsigned NumInScalars = N->getNumOperands();
10090   SDLoc dl(N);
10091   EVT VT = N->getValueType(0);
10092
10093   // A vector built entirely of undefs is undef.
10094   if (ISD::allOperandsUndef(N))
10095     return DAG.getUNDEF(VT);
10096
10097   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10098   if (V.getNode())
10099     return V;
10100
10101   V = reduceBuildVecConvertToConvertBuildVec(N);
10102   if (V.getNode())
10103     return V;
10104
10105   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10106   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10107   // at most two distinct vectors, turn this into a shuffle node.
10108
10109   // May only combine to shuffle after legalize if shuffle is legal.
10110   if (LegalOperations &&
10111       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10112     return SDValue();
10113
10114   SDValue VecIn1, VecIn2;
10115   for (unsigned i = 0; i != NumInScalars; ++i) {
10116     // Ignore undef inputs.
10117     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10118
10119     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10120     // constant index, bail out.
10121     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10122         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10123       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10124       break;
10125     }
10126
10127     // We allow up to two distinct input vectors.
10128     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10129     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10130       continue;
10131
10132     if (!VecIn1.getNode()) {
10133       VecIn1 = ExtractedFromVec;
10134     } else if (!VecIn2.getNode()) {
10135       VecIn2 = ExtractedFromVec;
10136     } else {
10137       // Too many inputs.
10138       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10139       break;
10140     }
10141   }
10142
10143     // If everything is good, we can make a shuffle operation.
10144   if (VecIn1.getNode()) {
10145     SmallVector<int, 8> Mask;
10146     for (unsigned i = 0; i != NumInScalars; ++i) {
10147       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10148         Mask.push_back(-1);
10149         continue;
10150       }
10151
10152       // If extracting from the first vector, just use the index directly.
10153       SDValue Extract = N->getOperand(i);
10154       SDValue ExtVal = Extract.getOperand(1);
10155       if (Extract.getOperand(0) == VecIn1) {
10156         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10157         if (ExtIndex > VT.getVectorNumElements())
10158           return SDValue();
10159
10160         Mask.push_back(ExtIndex);
10161         continue;
10162       }
10163
10164       // Otherwise, use InIdx + VecSize
10165       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10166       Mask.push_back(Idx+NumInScalars);
10167     }
10168
10169     // We can't generate a shuffle node with mismatched input and output types.
10170     // Attempt to transform a single input vector to the correct type.
10171     if ((VT != VecIn1.getValueType())) {
10172       // We don't support shuffeling between TWO values of different types.
10173       if (VecIn2.getNode())
10174         return SDValue();
10175
10176       // We only support widening of vectors which are half the size of the
10177       // output registers. For example XMM->YMM widening on X86 with AVX.
10178       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10179         return SDValue();
10180
10181       // If the input vector type has a different base type to the output
10182       // vector type, bail out.
10183       if (VecIn1.getValueType().getVectorElementType() !=
10184           VT.getVectorElementType())
10185         return SDValue();
10186
10187       // Widen the input vector by adding undef values.
10188       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10189                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10190     }
10191
10192     // If VecIn2 is unused then change it to undef.
10193     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10194
10195     // Check that we were able to transform all incoming values to the same
10196     // type.
10197     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10198         VecIn1.getValueType() != VT)
10199           return SDValue();
10200
10201     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10202     if (!isTypeLegal(VT))
10203       return SDValue();
10204
10205     // Return the new VECTOR_SHUFFLE node.
10206     SDValue Ops[2];
10207     Ops[0] = VecIn1;
10208     Ops[1] = VecIn2;
10209     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10210   }
10211
10212   return SDValue();
10213 }
10214
10215 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10216   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10217   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10218   // inputs come from at most two distinct vectors, turn this into a shuffle
10219   // node.
10220
10221   // If we only have one input vector, we don't need to do any concatenation.
10222   if (N->getNumOperands() == 1)
10223     return N->getOperand(0);
10224
10225   // Check if all of the operands are undefs.
10226   EVT VT = N->getValueType(0);
10227   if (ISD::allOperandsUndef(N))
10228     return DAG.getUNDEF(VT);
10229
10230   // Optimize concat_vectors where one of the vectors is undef.
10231   if (N->getNumOperands() == 2 &&
10232       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10233     SDValue In = N->getOperand(0);
10234     assert(In.getValueType().isVector() && "Must concat vectors");
10235
10236     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10237     if (In->getOpcode() == ISD::BITCAST &&
10238         !In->getOperand(0)->getValueType(0).isVector()) {
10239       SDValue Scalar = In->getOperand(0);
10240       EVT SclTy = Scalar->getValueType(0);
10241
10242       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10243         return SDValue();
10244
10245       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10246                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10247       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10248         return SDValue();
10249
10250       SDLoc dl = SDLoc(N);
10251       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10252       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10253     }
10254   }
10255
10256   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10257   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10258   if (N->getNumOperands() == 2 &&
10259       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10260       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10261     EVT VT = N->getValueType(0);
10262     SDValue N0 = N->getOperand(0);
10263     SDValue N1 = N->getOperand(1);
10264     SmallVector<SDValue, 8> Opnds;
10265     unsigned BuildVecNumElts =  N0.getNumOperands();
10266
10267     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10268       Opnds.push_back(N0.getOperand(i));
10269     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10270       Opnds.push_back(N1.getOperand(i));
10271
10272     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10273                        Opnds.size());
10274   }
10275
10276   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10277   // nodes often generate nop CONCAT_VECTOR nodes.
10278   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10279   // place the incoming vectors at the exact same location.
10280   SDValue SingleSource = SDValue();
10281   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10282
10283   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10284     SDValue Op = N->getOperand(i);
10285
10286     if (Op.getOpcode() == ISD::UNDEF)
10287       continue;
10288
10289     // Check if this is the identity extract:
10290     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10291       return SDValue();
10292
10293     // Find the single incoming vector for the extract_subvector.
10294     if (SingleSource.getNode()) {
10295       if (Op.getOperand(0) != SingleSource)
10296         return SDValue();
10297     } else {
10298       SingleSource = Op.getOperand(0);
10299
10300       // Check the source type is the same as the type of the result.
10301       // If not, this concat may extend the vector, so we can not
10302       // optimize it away.
10303       if (SingleSource.getValueType() != N->getValueType(0))
10304         return SDValue();
10305     }
10306
10307     unsigned IdentityIndex = i * PartNumElem;
10308     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10309     // The extract index must be constant.
10310     if (!CS)
10311       return SDValue();
10312
10313     // Check that we are reading from the identity index.
10314     if (CS->getZExtValue() != IdentityIndex)
10315       return SDValue();
10316   }
10317
10318   if (SingleSource.getNode())
10319     return SingleSource;
10320
10321   return SDValue();
10322 }
10323
10324 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10325   EVT NVT = N->getValueType(0);
10326   SDValue V = N->getOperand(0);
10327
10328   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10329     // Combine:
10330     //    (extract_subvec (concat V1, V2, ...), i)
10331     // Into:
10332     //    Vi if possible
10333     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10334     // type.
10335     if (V->getOperand(0).getValueType() != NVT)
10336       return SDValue();
10337     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10338     unsigned NumElems = NVT.getVectorNumElements();
10339     assert((Idx % NumElems) == 0 &&
10340            "IDX in concat is not a multiple of the result vector length.");
10341     return V->getOperand(Idx / NumElems);
10342   }
10343
10344   // Skip bitcasting
10345   if (V->getOpcode() == ISD::BITCAST)
10346     V = V.getOperand(0);
10347
10348   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10349     SDLoc dl(N);
10350     // Handle only simple case where vector being inserted and vector
10351     // being extracted are of same type, and are half size of larger vectors.
10352     EVT BigVT = V->getOperand(0).getValueType();
10353     EVT SmallVT = V->getOperand(1).getValueType();
10354     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10355       return SDValue();
10356
10357     // Only handle cases where both indexes are constants with the same type.
10358     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10359     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10360
10361     if (InsIdx && ExtIdx &&
10362         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10363         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10364       // Combine:
10365       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10366       // Into:
10367       //    indices are equal or bit offsets are equal => V1
10368       //    otherwise => (extract_subvec V1, ExtIdx)
10369       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10370           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10371         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10372       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10373                          DAG.getNode(ISD::BITCAST, dl,
10374                                      N->getOperand(0).getValueType(),
10375                                      V->getOperand(0)), N->getOperand(1));
10376     }
10377   }
10378
10379   return SDValue();
10380 }
10381
10382 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10383 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10384   EVT VT = N->getValueType(0);
10385   unsigned NumElts = VT.getVectorNumElements();
10386
10387   SDValue N0 = N->getOperand(0);
10388   SDValue N1 = N->getOperand(1);
10389   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10390
10391   SmallVector<SDValue, 4> Ops;
10392   EVT ConcatVT = N0.getOperand(0).getValueType();
10393   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10394   unsigned NumConcats = NumElts / NumElemsPerConcat;
10395
10396   // Look at every vector that's inserted. We're looking for exact
10397   // subvector-sized copies from a concatenated vector
10398   for (unsigned I = 0; I != NumConcats; ++I) {
10399     // Make sure we're dealing with a copy.
10400     unsigned Begin = I * NumElemsPerConcat;
10401     bool AllUndef = true, NoUndef = true;
10402     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10403       if (SVN->getMaskElt(J) >= 0)
10404         AllUndef = false;
10405       else
10406         NoUndef = false;
10407     }
10408
10409     if (NoUndef) {
10410       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10411         return SDValue();
10412
10413       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10414         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10415           return SDValue();
10416
10417       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10418       if (FirstElt < N0.getNumOperands())
10419         Ops.push_back(N0.getOperand(FirstElt));
10420       else
10421         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10422
10423     } else if (AllUndef) {
10424       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10425     } else { // Mixed with general masks and undefs, can't do optimization.
10426       return SDValue();
10427     }
10428   }
10429
10430   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10431                      Ops.size());
10432 }
10433
10434 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10435   EVT VT = N->getValueType(0);
10436   unsigned NumElts = VT.getVectorNumElements();
10437
10438   SDValue N0 = N->getOperand(0);
10439   SDValue N1 = N->getOperand(1);
10440
10441   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10442
10443   // Canonicalize shuffle undef, undef -> undef
10444   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10445     return DAG.getUNDEF(VT);
10446
10447   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10448
10449   // Canonicalize shuffle v, v -> v, undef
10450   if (N0 == N1) {
10451     SmallVector<int, 8> NewMask;
10452     for (unsigned i = 0; i != NumElts; ++i) {
10453       int Idx = SVN->getMaskElt(i);
10454       if (Idx >= (int)NumElts) Idx -= NumElts;
10455       NewMask.push_back(Idx);
10456     }
10457     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10458                                 &NewMask[0]);
10459   }
10460
10461   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10462   if (N0.getOpcode() == ISD::UNDEF) {
10463     SmallVector<int, 8> NewMask;
10464     for (unsigned i = 0; i != NumElts; ++i) {
10465       int Idx = SVN->getMaskElt(i);
10466       if (Idx >= 0) {
10467         if (Idx >= (int)NumElts)
10468           Idx -= NumElts;
10469         else
10470           Idx = -1; // remove reference to lhs
10471       }
10472       NewMask.push_back(Idx);
10473     }
10474     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10475                                 &NewMask[0]);
10476   }
10477
10478   // Remove references to rhs if it is undef
10479   if (N1.getOpcode() == ISD::UNDEF) {
10480     bool Changed = false;
10481     SmallVector<int, 8> NewMask;
10482     for (unsigned i = 0; i != NumElts; ++i) {
10483       int Idx = SVN->getMaskElt(i);
10484       if (Idx >= (int)NumElts) {
10485         Idx = -1;
10486         Changed = true;
10487       }
10488       NewMask.push_back(Idx);
10489     }
10490     if (Changed)
10491       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10492   }
10493
10494   // If it is a splat, check if the argument vector is another splat or a
10495   // build_vector with all scalar elements the same.
10496   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10497     SDNode *V = N0.getNode();
10498
10499     // If this is a bit convert that changes the element type of the vector but
10500     // not the number of vector elements, look through it.  Be careful not to
10501     // look though conversions that change things like v4f32 to v2f64.
10502     if (V->getOpcode() == ISD::BITCAST) {
10503       SDValue ConvInput = V->getOperand(0);
10504       if (ConvInput.getValueType().isVector() &&
10505           ConvInput.getValueType().getVectorNumElements() == NumElts)
10506         V = ConvInput.getNode();
10507     }
10508
10509     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10510       assert(V->getNumOperands() == NumElts &&
10511              "BUILD_VECTOR has wrong number of operands");
10512       SDValue Base;
10513       bool AllSame = true;
10514       for (unsigned i = 0; i != NumElts; ++i) {
10515         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10516           Base = V->getOperand(i);
10517           break;
10518         }
10519       }
10520       // Splat of <u, u, u, u>, return <u, u, u, u>
10521       if (!Base.getNode())
10522         return N0;
10523       for (unsigned i = 0; i != NumElts; ++i) {
10524         if (V->getOperand(i) != Base) {
10525           AllSame = false;
10526           break;
10527         }
10528       }
10529       // Splat of <x, x, x, x>, return <x, x, x, x>
10530       if (AllSame)
10531         return N0;
10532     }
10533   }
10534
10535   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10536       Level < AfterLegalizeVectorOps &&
10537       (N1.getOpcode() == ISD::UNDEF ||
10538       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10539        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10540     SDValue V = partitionShuffleOfConcats(N, DAG);
10541
10542     if (V.getNode())
10543       return V;
10544   }
10545
10546   // If this shuffle node is simply a swizzle of another shuffle node,
10547   // and it reverses the swizzle of the previous shuffle then we can
10548   // optimize shuffle(shuffle(x, undef), undef) -> x.
10549   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10550       N1.getOpcode() == ISD::UNDEF) {
10551
10552     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10553
10554     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10555     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10556       return SDValue();
10557
10558     // The incoming shuffle must be of the same type as the result of the
10559     // current shuffle.
10560     assert(OtherSV->getOperand(0).getValueType() == VT &&
10561            "Shuffle types don't match");
10562
10563     for (unsigned i = 0; i != NumElts; ++i) {
10564       int Idx = SVN->getMaskElt(i);
10565       assert(Idx < (int)NumElts && "Index references undef operand");
10566       // Next, this index comes from the first value, which is the incoming
10567       // shuffle. Adopt the incoming index.
10568       if (Idx >= 0)
10569         Idx = OtherSV->getMaskElt(Idx);
10570
10571       // The combined shuffle must map each index to itself.
10572       if (Idx >= 0 && (unsigned)Idx != i)
10573         return SDValue();
10574     }
10575
10576     return OtherSV->getOperand(0);
10577   }
10578
10579   return SDValue();
10580 }
10581
10582 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10583   SDValue N0 = N->getOperand(0);
10584   SDValue N2 = N->getOperand(2);
10585
10586   // If the input vector is a concatenation, and the insert replaces
10587   // one of the halves, we can optimize into a single concat_vectors.
10588   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10589       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10590     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10591     EVT VT = N->getValueType(0);
10592
10593     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10594     // (concat_vectors Z, Y)
10595     if (InsIdx == 0)
10596       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10597                          N->getOperand(1), N0.getOperand(1));
10598
10599     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10600     // (concat_vectors X, Z)
10601     if (InsIdx == VT.getVectorNumElements()/2)
10602       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10603                          N0.getOperand(0), N->getOperand(1));
10604   }
10605
10606   return SDValue();
10607 }
10608
10609 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10610 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10611 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10612 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10613 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10614   EVT VT = N->getValueType(0);
10615   SDLoc dl(N);
10616   SDValue LHS = N->getOperand(0);
10617   SDValue RHS = N->getOperand(1);
10618   if (N->getOpcode() == ISD::AND) {
10619     if (RHS.getOpcode() == ISD::BITCAST)
10620       RHS = RHS.getOperand(0);
10621     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10622       SmallVector<int, 8> Indices;
10623       unsigned NumElts = RHS.getNumOperands();
10624       for (unsigned i = 0; i != NumElts; ++i) {
10625         SDValue Elt = RHS.getOperand(i);
10626         if (!isa<ConstantSDNode>(Elt))
10627           return SDValue();
10628
10629         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10630           Indices.push_back(i);
10631         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10632           Indices.push_back(NumElts);
10633         else
10634           return SDValue();
10635       }
10636
10637       // Let's see if the target supports this vector_shuffle.
10638       EVT RVT = RHS.getValueType();
10639       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10640         return SDValue();
10641
10642       // Return the new VECTOR_SHUFFLE node.
10643       EVT EltVT = RVT.getVectorElementType();
10644       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10645                                      DAG.getConstant(0, EltVT));
10646       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10647                                  RVT, &ZeroOps[0], ZeroOps.size());
10648       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10649       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10650       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10651     }
10652   }
10653
10654   return SDValue();
10655 }
10656
10657 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10658 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10659   assert(N->getValueType(0).isVector() &&
10660          "SimplifyVBinOp only works on vectors!");
10661
10662   SDValue LHS = N->getOperand(0);
10663   SDValue RHS = N->getOperand(1);
10664   SDValue Shuffle = XformToShuffleWithZero(N);
10665   if (Shuffle.getNode()) return Shuffle;
10666
10667   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10668   // this operation.
10669   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10670       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10671     // Check if both vectors are constants. If not bail out.
10672     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10673           cast<BuildVectorSDNode>(RHS)->isConstant()))
10674       return SDValue();
10675
10676     SmallVector<SDValue, 8> Ops;
10677     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10678       SDValue LHSOp = LHS.getOperand(i);
10679       SDValue RHSOp = RHS.getOperand(i);
10680
10681       // Can't fold divide by zero.
10682       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10683           N->getOpcode() == ISD::FDIV) {
10684         if ((RHSOp.getOpcode() == ISD::Constant &&
10685              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10686             (RHSOp.getOpcode() == ISD::ConstantFP &&
10687              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10688           break;
10689       }
10690
10691       EVT VT = LHSOp.getValueType();
10692       EVT RVT = RHSOp.getValueType();
10693       if (RVT != VT) {
10694         // Integer BUILD_VECTOR operands may have types larger than the element
10695         // size (e.g., when the element type is not legal).  Prior to type
10696         // legalization, the types may not match between the two BUILD_VECTORS.
10697         // Truncate one of the operands to make them match.
10698         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10699           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10700         } else {
10701           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10702           VT = RVT;
10703         }
10704       }
10705       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10706                                    LHSOp, RHSOp);
10707       if (FoldOp.getOpcode() != ISD::UNDEF &&
10708           FoldOp.getOpcode() != ISD::Constant &&
10709           FoldOp.getOpcode() != ISD::ConstantFP)
10710         break;
10711       Ops.push_back(FoldOp);
10712       AddToWorkList(FoldOp.getNode());
10713     }
10714
10715     if (Ops.size() == LHS.getNumOperands())
10716       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10717                          LHS.getValueType(), &Ops[0], Ops.size());
10718   }
10719
10720   return SDValue();
10721 }
10722
10723 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10724 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10725   assert(N->getValueType(0).isVector() &&
10726          "SimplifyVUnaryOp only works on vectors!");
10727
10728   SDValue N0 = N->getOperand(0);
10729
10730   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10731     return SDValue();
10732
10733   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10734   SmallVector<SDValue, 8> Ops;
10735   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10736     SDValue Op = N0.getOperand(i);
10737     if (Op.getOpcode() != ISD::UNDEF &&
10738         Op.getOpcode() != ISD::ConstantFP)
10739       break;
10740     EVT EltVT = Op.getValueType();
10741     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10742     if (FoldOp.getOpcode() != ISD::UNDEF &&
10743         FoldOp.getOpcode() != ISD::ConstantFP)
10744       break;
10745     Ops.push_back(FoldOp);
10746     AddToWorkList(FoldOp.getNode());
10747   }
10748
10749   if (Ops.size() != N0.getNumOperands())
10750     return SDValue();
10751
10752   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10753                      N0.getValueType(), &Ops[0], Ops.size());
10754 }
10755
10756 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10757                                     SDValue N1, SDValue N2){
10758   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10759
10760   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10761                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10762
10763   // If we got a simplified select_cc node back from SimplifySelectCC, then
10764   // break it down into a new SETCC node, and a new SELECT node, and then return
10765   // the SELECT node, since we were called with a SELECT node.
10766   if (SCC.getNode()) {
10767     // Check to see if we got a select_cc back (to turn into setcc/select).
10768     // Otherwise, just return whatever node we got back, like fabs.
10769     if (SCC.getOpcode() == ISD::SELECT_CC) {
10770       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10771                                   N0.getValueType(),
10772                                   SCC.getOperand(0), SCC.getOperand(1),
10773                                   SCC.getOperand(4));
10774       AddToWorkList(SETCC.getNode());
10775       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10776                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10777     }
10778
10779     return SCC;
10780   }
10781   return SDValue();
10782 }
10783
10784 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10785 /// are the two values being selected between, see if we can simplify the
10786 /// select.  Callers of this should assume that TheSelect is deleted if this
10787 /// returns true.  As such, they should return the appropriate thing (e.g. the
10788 /// node) back to the top-level of the DAG combiner loop to avoid it being
10789 /// looked at.
10790 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10791                                     SDValue RHS) {
10792
10793   // Cannot simplify select with vector condition
10794   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10795
10796   // If this is a select from two identical things, try to pull the operation
10797   // through the select.
10798   if (LHS.getOpcode() != RHS.getOpcode() ||
10799       !LHS.hasOneUse() || !RHS.hasOneUse())
10800     return false;
10801
10802   // If this is a load and the token chain is identical, replace the select
10803   // of two loads with a load through a select of the address to load from.
10804   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10805   // constants have been dropped into the constant pool.
10806   if (LHS.getOpcode() == ISD::LOAD) {
10807     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10808     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10809
10810     // Token chains must be identical.
10811     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10812         // Do not let this transformation reduce the number of volatile loads.
10813         LLD->isVolatile() || RLD->isVolatile() ||
10814         // If this is an EXTLOAD, the VT's must match.
10815         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10816         // If this is an EXTLOAD, the kind of extension must match.
10817         (LLD->getExtensionType() != RLD->getExtensionType() &&
10818          // The only exception is if one of the extensions is anyext.
10819          LLD->getExtensionType() != ISD::EXTLOAD &&
10820          RLD->getExtensionType() != ISD::EXTLOAD) ||
10821         // FIXME: this discards src value information.  This is
10822         // over-conservative. It would be beneficial to be able to remember
10823         // both potential memory locations.  Since we are discarding
10824         // src value info, don't do the transformation if the memory
10825         // locations are not in the default address space.
10826         LLD->getPointerInfo().getAddrSpace() != 0 ||
10827         RLD->getPointerInfo().getAddrSpace() != 0 ||
10828         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10829                                       LLD->getBasePtr().getValueType()))
10830       return false;
10831
10832     // Check that the select condition doesn't reach either load.  If so,
10833     // folding this will induce a cycle into the DAG.  If not, this is safe to
10834     // xform, so create a select of the addresses.
10835     SDValue Addr;
10836     if (TheSelect->getOpcode() == ISD::SELECT) {
10837       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10838       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10839           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10840         return false;
10841       // The loads must not depend on one another.
10842       if (LLD->isPredecessorOf(RLD) ||
10843           RLD->isPredecessorOf(LLD))
10844         return false;
10845       Addr = DAG.getSelect(SDLoc(TheSelect),
10846                            LLD->getBasePtr().getValueType(),
10847                            TheSelect->getOperand(0), LLD->getBasePtr(),
10848                            RLD->getBasePtr());
10849     } else {  // Otherwise SELECT_CC
10850       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10851       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10852
10853       if ((LLD->hasAnyUseOfValue(1) &&
10854            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10855           (RLD->hasAnyUseOfValue(1) &&
10856            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10857         return false;
10858
10859       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10860                          LLD->getBasePtr().getValueType(),
10861                          TheSelect->getOperand(0),
10862                          TheSelect->getOperand(1),
10863                          LLD->getBasePtr(), RLD->getBasePtr(),
10864                          TheSelect->getOperand(4));
10865     }
10866
10867     SDValue Load;
10868     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10869       Load = DAG.getLoad(TheSelect->getValueType(0),
10870                          SDLoc(TheSelect),
10871                          // FIXME: Discards pointer and TBAA info.
10872                          LLD->getChain(), Addr, MachinePointerInfo(),
10873                          LLD->isVolatile(), LLD->isNonTemporal(),
10874                          LLD->isInvariant(), LLD->getAlignment());
10875     } else {
10876       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10877                             RLD->getExtensionType() : LLD->getExtensionType(),
10878                             SDLoc(TheSelect),
10879                             TheSelect->getValueType(0),
10880                             // FIXME: Discards pointer and TBAA info.
10881                             LLD->getChain(), Addr, MachinePointerInfo(),
10882                             LLD->getMemoryVT(), LLD->isVolatile(),
10883                             LLD->isNonTemporal(), LLD->getAlignment());
10884     }
10885
10886     // Users of the select now use the result of the load.
10887     CombineTo(TheSelect, Load);
10888
10889     // Users of the old loads now use the new load's chain.  We know the
10890     // old-load value is dead now.
10891     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10892     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10893     return true;
10894   }
10895
10896   return false;
10897 }
10898
10899 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10900 /// where 'cond' is the comparison specified by CC.
10901 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10902                                       SDValue N2, SDValue N3,
10903                                       ISD::CondCode CC, bool NotExtCompare) {
10904   // (x ? y : y) -> y.
10905   if (N2 == N3) return N2;
10906
10907   EVT VT = N2.getValueType();
10908   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10909   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10910   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10911
10912   // Determine if the condition we're dealing with is constant
10913   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10914                               N0, N1, CC, DL, false);
10915   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10916   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10917
10918   // fold select_cc true, x, y -> x
10919   if (SCCC && !SCCC->isNullValue())
10920     return N2;
10921   // fold select_cc false, x, y -> y
10922   if (SCCC && SCCC->isNullValue())
10923     return N3;
10924
10925   // Check to see if we can simplify the select into an fabs node
10926   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10927     // Allow either -0.0 or 0.0
10928     if (CFP->getValueAPF().isZero()) {
10929       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10930       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10931           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10932           N2 == N3.getOperand(0))
10933         return DAG.getNode(ISD::FABS, DL, VT, N0);
10934
10935       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10936       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10937           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10938           N2.getOperand(0) == N3)
10939         return DAG.getNode(ISD::FABS, DL, VT, N3);
10940     }
10941   }
10942
10943   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10944   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10945   // in it.  This is a win when the constant is not otherwise available because
10946   // it replaces two constant pool loads with one.  We only do this if the FP
10947   // type is known to be legal, because if it isn't, then we are before legalize
10948   // types an we want the other legalization to happen first (e.g. to avoid
10949   // messing with soft float) and if the ConstantFP is not legal, because if
10950   // it is legal, we may not need to store the FP constant in a constant pool.
10951   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10952     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10953       if (TLI.isTypeLegal(N2.getValueType()) &&
10954           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10955                TargetLowering::Legal &&
10956            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10957            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10958           // If both constants have multiple uses, then we won't need to do an
10959           // extra load, they are likely around in registers for other users.
10960           (TV->hasOneUse() || FV->hasOneUse())) {
10961         Constant *Elts[] = {
10962           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10963           const_cast<ConstantFP*>(TV->getConstantFPValue())
10964         };
10965         Type *FPTy = Elts[0]->getType();
10966         const DataLayout &TD = *TLI.getDataLayout();
10967
10968         // Create a ConstantArray of the two constants.
10969         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10970         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10971                                             TD.getPrefTypeAlignment(FPTy));
10972         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10973
10974         // Get the offsets to the 0 and 1 element of the array so that we can
10975         // select between them.
10976         SDValue Zero = DAG.getIntPtrConstant(0);
10977         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10978         SDValue One = DAG.getIntPtrConstant(EltSize);
10979
10980         SDValue Cond = DAG.getSetCC(DL,
10981                                     getSetCCResultType(N0.getValueType()),
10982                                     N0, N1, CC);
10983         AddToWorkList(Cond.getNode());
10984         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10985                                           Cond, One, Zero);
10986         AddToWorkList(CstOffset.getNode());
10987         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10988                             CstOffset);
10989         AddToWorkList(CPIdx.getNode());
10990         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10991                            MachinePointerInfo::getConstantPool(), false,
10992                            false, false, Alignment);
10993
10994       }
10995     }
10996
10997   // Check to see if we can perform the "gzip trick", transforming
10998   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10999   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11000       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11001        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11002     EVT XType = N0.getValueType();
11003     EVT AType = N2.getValueType();
11004     if (XType.bitsGE(AType)) {
11005       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11006       // single-bit constant.
11007       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11008         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11009         ShCtV = XType.getSizeInBits()-ShCtV-1;
11010         SDValue ShCt = DAG.getConstant(ShCtV,
11011                                        getShiftAmountTy(N0.getValueType()));
11012         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11013                                     XType, N0, ShCt);
11014         AddToWorkList(Shift.getNode());
11015
11016         if (XType.bitsGT(AType)) {
11017           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11018           AddToWorkList(Shift.getNode());
11019         }
11020
11021         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11022       }
11023
11024       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11025                                   XType, N0,
11026                                   DAG.getConstant(XType.getSizeInBits()-1,
11027                                          getShiftAmountTy(N0.getValueType())));
11028       AddToWorkList(Shift.getNode());
11029
11030       if (XType.bitsGT(AType)) {
11031         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11032         AddToWorkList(Shift.getNode());
11033       }
11034
11035       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11036     }
11037   }
11038
11039   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11040   // where y is has a single bit set.
11041   // A plaintext description would be, we can turn the SELECT_CC into an AND
11042   // when the condition can be materialized as an all-ones register.  Any
11043   // single bit-test can be materialized as an all-ones register with
11044   // shift-left and shift-right-arith.
11045   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11046       N0->getValueType(0) == VT &&
11047       N1C && N1C->isNullValue() &&
11048       N2C && N2C->isNullValue()) {
11049     SDValue AndLHS = N0->getOperand(0);
11050     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11051     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11052       // Shift the tested bit over the sign bit.
11053       APInt AndMask = ConstAndRHS->getAPIntValue();
11054       SDValue ShlAmt =
11055         DAG.getConstant(AndMask.countLeadingZeros(),
11056                         getShiftAmountTy(AndLHS.getValueType()));
11057       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11058
11059       // Now arithmetic right shift it all the way over, so the result is either
11060       // all-ones, or zero.
11061       SDValue ShrAmt =
11062         DAG.getConstant(AndMask.getBitWidth()-1,
11063                         getShiftAmountTy(Shl.getValueType()));
11064       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11065
11066       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11067     }
11068   }
11069
11070   // fold select C, 16, 0 -> shl C, 4
11071   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11072     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11073       TargetLowering::ZeroOrOneBooleanContent) {
11074
11075     // If the caller doesn't want us to simplify this into a zext of a compare,
11076     // don't do it.
11077     if (NotExtCompare && N2C->getAPIntValue() == 1)
11078       return SDValue();
11079
11080     // Get a SetCC of the condition
11081     // NOTE: Don't create a SETCC if it's not legal on this target.
11082     if (!LegalOperations ||
11083         TLI.isOperationLegal(ISD::SETCC,
11084           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11085       SDValue Temp, SCC;
11086       // cast from setcc result type to select result type
11087       if (LegalTypes) {
11088         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11089                             N0, N1, CC);
11090         if (N2.getValueType().bitsLT(SCC.getValueType()))
11091           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11092                                         N2.getValueType());
11093         else
11094           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11095                              N2.getValueType(), SCC);
11096       } else {
11097         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11098         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11099                            N2.getValueType(), SCC);
11100       }
11101
11102       AddToWorkList(SCC.getNode());
11103       AddToWorkList(Temp.getNode());
11104
11105       if (N2C->getAPIntValue() == 1)
11106         return Temp;
11107
11108       // shl setcc result by log2 n2c
11109       return DAG.getNode(
11110           ISD::SHL, DL, N2.getValueType(), Temp,
11111           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11112                           getShiftAmountTy(Temp.getValueType())));
11113     }
11114   }
11115
11116   // Check to see if this is the equivalent of setcc
11117   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11118   // otherwise, go ahead with the folds.
11119   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11120     EVT XType = N0.getValueType();
11121     if (!LegalOperations ||
11122         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11123       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11124       if (Res.getValueType() != VT)
11125         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11126       return Res;
11127     }
11128
11129     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11130     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11131         (!LegalOperations ||
11132          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11133       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11134       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11135                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11136                                        getShiftAmountTy(Ctlz.getValueType())));
11137     }
11138     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11139     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11140       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11141                                   XType, DAG.getConstant(0, XType), N0);
11142       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11143       return DAG.getNode(ISD::SRL, DL, XType,
11144                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11145                          DAG.getConstant(XType.getSizeInBits()-1,
11146                                          getShiftAmountTy(XType)));
11147     }
11148     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11149     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11150       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11151                                  DAG.getConstant(XType.getSizeInBits()-1,
11152                                          getShiftAmountTy(N0.getValueType())));
11153       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11154     }
11155   }
11156
11157   // Check to see if this is an integer abs.
11158   // select_cc setg[te] X,  0,  X, -X ->
11159   // select_cc setgt    X, -1,  X, -X ->
11160   // select_cc setl[te] X,  0, -X,  X ->
11161   // select_cc setlt    X,  1, -X,  X ->
11162   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11163   if (N1C) {
11164     ConstantSDNode *SubC = nullptr;
11165     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11166          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11167         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11168       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11169     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11170               (N1C->isOne() && CC == ISD::SETLT)) &&
11171              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11172       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11173
11174     EVT XType = N0.getValueType();
11175     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11176       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11177                                   N0,
11178                                   DAG.getConstant(XType.getSizeInBits()-1,
11179                                          getShiftAmountTy(N0.getValueType())));
11180       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11181                                 XType, N0, Shift);
11182       AddToWorkList(Shift.getNode());
11183       AddToWorkList(Add.getNode());
11184       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11185     }
11186   }
11187
11188   return SDValue();
11189 }
11190
11191 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11192 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11193                                    SDValue N1, ISD::CondCode Cond,
11194                                    SDLoc DL, bool foldBooleans) {
11195   TargetLowering::DAGCombinerInfo
11196     DagCombineInfo(DAG, Level, false, this);
11197   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11198 }
11199
11200 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11201 /// return a DAG expression to select that will generate the same value by
11202 /// multiplying by a magic number.  See:
11203 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11204 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11205   const APInt *Divisor;
11206   if (N->getValueType(0).isVector()) {
11207     // Handle splat vectors.
11208     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11209     if (ConstantSDNode *C = BV->getConstantSplatValue())
11210       Divisor = &C->getAPIntValue();
11211     else
11212       return SDValue();
11213   } else {
11214     Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11215   }
11216
11217   // Avoid division by zero.
11218   if (!*Divisor)
11219     return SDValue();
11220
11221   std::vector<SDNode*> Built;
11222   SDValue S = TLI.BuildSDIV(N, *Divisor, DAG, LegalOperations, &Built);
11223
11224   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11225        ii != ee; ++ii)
11226     AddToWorkList(*ii);
11227   return S;
11228 }
11229
11230 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11231 /// return a DAG expression to select that will generate the same value by
11232 /// multiplying by a magic number.  See:
11233 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11234 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11235   const APInt *Divisor;
11236   if (N->getValueType(0).isVector()) {
11237     // Handle splat vectors.
11238     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11239     if (ConstantSDNode *C = BV->getConstantSplatValue())
11240       Divisor = &C->getAPIntValue();
11241     else
11242       return SDValue();
11243   } else {
11244     Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11245   }
11246
11247   // Avoid division by zero.
11248   if (!*Divisor)
11249     return SDValue();
11250
11251   std::vector<SDNode*> Built;
11252   SDValue S = TLI.BuildUDIV(N, *Divisor, DAG, LegalOperations, &Built);
11253
11254   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11255        ii != ee; ++ii)
11256     AddToWorkList(*ii);
11257   return S;
11258 }
11259
11260 /// FindBaseOffset - Return true if base is a frame index, which is known not
11261 // to alias with anything but itself.  Provides base object and offset as
11262 // results.
11263 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11264                            const GlobalValue *&GV, const void *&CV) {
11265   // Assume it is a primitive operation.
11266   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11267
11268   // If it's an adding a simple constant then integrate the offset.
11269   if (Base.getOpcode() == ISD::ADD) {
11270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11271       Base = Base.getOperand(0);
11272       Offset += C->getZExtValue();
11273     }
11274   }
11275
11276   // Return the underlying GlobalValue, and update the Offset.  Return false
11277   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11278   // by multiple nodes with different offsets.
11279   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11280     GV = G->getGlobal();
11281     Offset += G->getOffset();
11282     return false;
11283   }
11284
11285   // Return the underlying Constant value, and update the Offset.  Return false
11286   // for ConstantSDNodes since the same constant pool entry may be represented
11287   // by multiple nodes with different offsets.
11288   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11289     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11290                                          : (const void *)C->getConstVal();
11291     Offset += C->getOffset();
11292     return false;
11293   }
11294   // If it's any of the following then it can't alias with anything but itself.
11295   return isa<FrameIndexSDNode>(Base);
11296 }
11297
11298 /// isAlias - Return true if there is any possibility that the two addresses
11299 /// overlap.
11300 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11301   // If they are the same then they must be aliases.
11302   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11303
11304   // If they are both volatile then they cannot be reordered.
11305   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11306
11307   // Gather base node and offset information.
11308   SDValue Base1, Base2;
11309   int64_t Offset1, Offset2;
11310   const GlobalValue *GV1, *GV2;
11311   const void *CV1, *CV2;
11312   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11313                                       Base1, Offset1, GV1, CV1);
11314   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11315                                       Base2, Offset2, GV2, CV2);
11316
11317   // If they have a same base address then check to see if they overlap.
11318   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11319     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11320              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11321
11322   // It is possible for different frame indices to alias each other, mostly
11323   // when tail call optimization reuses return address slots for arguments.
11324   // To catch this case, look up the actual index of frame indices to compute
11325   // the real alias relationship.
11326   if (isFrameIndex1 && isFrameIndex2) {
11327     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11328     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11329     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11330     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11331              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11332   }
11333
11334   // Otherwise, if we know what the bases are, and they aren't identical, then
11335   // we know they cannot alias.
11336   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11337     return false;
11338
11339   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11340   // compared to the size and offset of the access, we may be able to prove they
11341   // do not alias.  This check is conservative for now to catch cases created by
11342   // splitting vector types.
11343   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11344       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11345       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11346        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11347       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11348     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11349     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11350
11351     // There is no overlap between these relatively aligned accesses of similar
11352     // size, return no alias.
11353     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11354         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11355       return false;
11356   }
11357
11358   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11359     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11360 #ifndef NDEBUG
11361   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11362       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11363     UseAA = false;
11364 #endif
11365   if (UseAA &&
11366       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11367     // Use alias analysis information.
11368     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11369                                  Op1->getSrcValueOffset());
11370     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11371         Op0->getSrcValueOffset() - MinOffset;
11372     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11373         Op1->getSrcValueOffset() - MinOffset;
11374     AliasAnalysis::AliasResult AAResult =
11375         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11376                                          Overlap1,
11377                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11378                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11379                                          Overlap2,
11380                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11381     if (AAResult == AliasAnalysis::NoAlias)
11382       return false;
11383   }
11384
11385   // Otherwise we have to assume they alias.
11386   return true;
11387 }
11388
11389 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11390 /// looking for aliasing nodes and adding them to the Aliases vector.
11391 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11392                                    SmallVectorImpl<SDValue> &Aliases) {
11393   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11394   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11395
11396   // Get alias information for node.
11397   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11398
11399   // Starting off.
11400   Chains.push_back(OriginalChain);
11401   unsigned Depth = 0;
11402
11403   // Look at each chain and determine if it is an alias.  If so, add it to the
11404   // aliases list.  If not, then continue up the chain looking for the next
11405   // candidate.
11406   while (!Chains.empty()) {
11407     SDValue Chain = Chains.back();
11408     Chains.pop_back();
11409
11410     // For TokenFactor nodes, look at each operand and only continue up the
11411     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11412     // find more and revert to original chain since the xform is unlikely to be
11413     // profitable.
11414     //
11415     // FIXME: The depth check could be made to return the last non-aliasing
11416     // chain we found before we hit a tokenfactor rather than the original
11417     // chain.
11418     if (Depth > 6 || Aliases.size() == 2) {
11419       Aliases.clear();
11420       Aliases.push_back(OriginalChain);
11421       return;
11422     }
11423
11424     // Don't bother if we've been before.
11425     if (!Visited.insert(Chain.getNode()))
11426       continue;
11427
11428     switch (Chain.getOpcode()) {
11429     case ISD::EntryToken:
11430       // Entry token is ideal chain operand, but handled in FindBetterChain.
11431       break;
11432
11433     case ISD::LOAD:
11434     case ISD::STORE: {
11435       // Get alias information for Chain.
11436       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11437           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11438
11439       // If chain is alias then stop here.
11440       if (!(IsLoad && IsOpLoad) &&
11441           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11442         Aliases.push_back(Chain);
11443       } else {
11444         // Look further up the chain.
11445         Chains.push_back(Chain.getOperand(0));
11446         ++Depth;
11447       }
11448       break;
11449     }
11450
11451     case ISD::TokenFactor:
11452       // We have to check each of the operands of the token factor for "small"
11453       // token factors, so we queue them up.  Adding the operands to the queue
11454       // (stack) in reverse order maintains the original order and increases the
11455       // likelihood that getNode will find a matching token factor (CSE.)
11456       if (Chain.getNumOperands() > 16) {
11457         Aliases.push_back(Chain);
11458         break;
11459       }
11460       for (unsigned n = Chain.getNumOperands(); n;)
11461         Chains.push_back(Chain.getOperand(--n));
11462       ++Depth;
11463       break;
11464
11465     default:
11466       // For all other instructions we will just have to take what we can get.
11467       Aliases.push_back(Chain);
11468       break;
11469     }
11470   }
11471
11472   // We need to be careful here to also search for aliases through the
11473   // value operand of a store, etc. Consider the following situation:
11474   //   Token1 = ...
11475   //   L1 = load Token1, %52
11476   //   S1 = store Token1, L1, %51
11477   //   L2 = load Token1, %52+8
11478   //   S2 = store Token1, L2, %51+8
11479   //   Token2 = Token(S1, S2)
11480   //   L3 = load Token2, %53
11481   //   S3 = store Token2, L3, %52
11482   //   L4 = load Token2, %53+8
11483   //   S4 = store Token2, L4, %52+8
11484   // If we search for aliases of S3 (which loads address %52), and we look
11485   // only through the chain, then we'll miss the trivial dependence on L1
11486   // (which also loads from %52). We then might change all loads and
11487   // stores to use Token1 as their chain operand, which could result in
11488   // copying %53 into %52 before copying %52 into %51 (which should
11489   // happen first).
11490   //
11491   // The problem is, however, that searching for such data dependencies
11492   // can become expensive, and the cost is not directly related to the
11493   // chain depth. Instead, we'll rule out such configurations here by
11494   // insisting that we've visited all chain users (except for users
11495   // of the original chain, which is not necessary). When doing this,
11496   // we need to look through nodes we don't care about (otherwise, things
11497   // like register copies will interfere with trivial cases).
11498
11499   SmallVector<const SDNode *, 16> Worklist;
11500   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11501        IE = Visited.end(); I != IE; ++I)
11502     if (*I != OriginalChain.getNode())
11503       Worklist.push_back(*I);
11504
11505   while (!Worklist.empty()) {
11506     const SDNode *M = Worklist.pop_back_val();
11507
11508     // We have already visited M, and want to make sure we've visited any uses
11509     // of M that we care about. For uses that we've not visisted, and don't
11510     // care about, queue them to the worklist.
11511
11512     for (SDNode::use_iterator UI = M->use_begin(),
11513          UIE = M->use_end(); UI != UIE; ++UI)
11514       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11515         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11516           // We've not visited this use, and we care about it (it could have an
11517           // ordering dependency with the original node).
11518           Aliases.clear();
11519           Aliases.push_back(OriginalChain);
11520           return;
11521         }
11522
11523         // We've not visited this use, but we don't care about it. Mark it as
11524         // visited and enqueue it to the worklist.
11525         Worklist.push_back(*UI);
11526       }
11527   }
11528 }
11529
11530 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11531 /// for a better chain (aliasing node.)
11532 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11533   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11534
11535   // Accumulate all the aliases to this node.
11536   GatherAllAliases(N, OldChain, Aliases);
11537
11538   // If no operands then chain to entry token.
11539   if (Aliases.size() == 0)
11540     return DAG.getEntryNode();
11541
11542   // If a single operand then chain to it.  We don't need to revisit it.
11543   if (Aliases.size() == 1)
11544     return Aliases[0];
11545
11546   // Construct a custom tailored token factor.
11547   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11548                      &Aliases[0], Aliases.size());
11549 }
11550
11551 // SelectionDAG::Combine - This is the entry point for the file.
11552 //
11553 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11554                            CodeGenOpt::Level OptLevel) {
11555   /// run - This is the main entry point to this class.
11556   ///
11557   DAGCombiner(*this, AA, OptLevel).Run(Level);
11558 }