Masked Vector Load and Store Intrinsics.
[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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306     SDValue visitMLOAD(SDNode *N);
307     SDValue visitMSTORE(SDNode *N);
308
309     SDValue XformToShuffleWithZero(SDNode *N);
310     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
311
312     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
313
314     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318                              SDValue N3, ISD::CondCode CC,
319                              bool NotExtCompare = false);
320     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321                           SDLoc DL, bool foldBooleans = true);
322
323     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
324                            SDValue &CC) const;
325     bool isOneUseSetCC(SDValue N) const;
326
327     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
328                                          unsigned HiOp);
329     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331     SDValue BuildSDIV(SDNode *N);
332     SDValue BuildSDIVPow2(SDNode *N);
333     SDValue BuildUDIV(SDNode *N);
334     SDValue BuildReciprocalEstimate(SDValue Op);
335     SDValue BuildRsqrtEstimate(SDValue Op);
336     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339                                bool DemandHighBits = true);
340     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342                               SDValue InnerPos, SDValue InnerNeg,
343                               unsigned PosOpcode, unsigned NegOpcode,
344                               SDLoc DL);
345     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346     SDValue ReduceLoadWidth(SDNode *N);
347     SDValue ReduceLoadOpStoreWidth(SDNode *N);
348     SDValue TransformFPLoadStorePair(SDNode *N);
349     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
351
352     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
353
354     /// Walk up chain skipping non-aliasing memory nodes,
355     /// looking for aliasing nodes and adding them to the Aliases vector.
356     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357                           SmallVectorImpl<SDValue> &Aliases);
358
359     /// Return true if there is any possibility that the two addresses overlap.
360     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
361
362     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363     /// chain (aliasing node.)
364     SDValue FindBetterChain(SDNode *N, SDValue Chain);
365
366     /// Merge consecutive store operations into a wide store.
367     /// This optimization uses wide integers or vectors when possible.
368     /// \return True if some memory operations were changed.
369     bool MergeConsecutiveStores(StoreSDNode *N);
370
371     /// \brief Try to transform a truncation where C is a constant:
372     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
373     ///
374     /// \p N needs to be a truncation and its first operand an AND. Other
375     /// requirements are checked by the function (e.g. that trunc is
376     /// single-use) and if missed an empty SDValue is returned.
377     SDValue distributeTruncateThroughAnd(SDNode *N);
378
379   public:
380     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383       AttributeSet FnAttrs =
384           DAG.getMachineFunction().getFunction()->getAttributes();
385       ForCodeSize =
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387                                Attribute::OptimizeForSize) ||
388           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389     }
390
391     /// Runs the dag combiner on all nodes in the work list
392     void Run(CombineLevel AtLevel);
393
394     SelectionDAG &getDAG() const { return DAG; }
395
396     /// Returns a type large enough to hold any valid shift amount - before type
397     /// legalization these can be huge.
398     EVT getShiftAmountTy(EVT LHSTy) {
399       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400       if (LHSTy.isVector())
401         return LHSTy;
402       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403                         : TLI.getPointerTy();
404     }
405
406     /// This method returns true if we are running before type legalization or
407     /// if the specified VT is legal.
408     bool isTypeLegal(const EVT &VT) {
409       if (!LegalTypes) return true;
410       return TLI.isTypeLegal(VT);
411     }
412
413     /// Convenience wrapper around TargetLowering::getSetCCResultType
414     EVT getSetCCResultType(EVT VT) const {
415       return TLI.getSetCCResultType(*DAG.getContext(), VT);
416     }
417     int& MLD();
418   };
419 }
420
421
422 namespace {
423 /// This class is a DAGUpdateListener that removes any deleted
424 /// nodes from the worklist.
425 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
426   DAGCombiner &DC;
427 public:
428   explicit WorklistRemover(DAGCombiner &dc)
429     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
430
431   void NodeDeleted(SDNode *N, SDNode *E) override {
432     DC.removeFromWorklist(N);
433   }
434 };
435 }
436
437 //===----------------------------------------------------------------------===//
438 //  TargetLowering::DAGCombinerInfo implementation
439 //===----------------------------------------------------------------------===//
440
441 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
442   ((DAGCombiner*)DC)->AddToWorklist(N);
443 }
444
445 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
446   ((DAGCombiner*)DC)->removeFromWorklist(N);
447 }
448
449 SDValue TargetLowering::DAGCombinerInfo::
450 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
451   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
452 }
453
454 SDValue TargetLowering::DAGCombinerInfo::
455 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
456   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
457 }
458
459
460 SDValue TargetLowering::DAGCombinerInfo::
461 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
462   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
463 }
464
465 void TargetLowering::DAGCombinerInfo::
466 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
467   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
468 }
469
470 //===----------------------------------------------------------------------===//
471 // Helper Functions
472 //===----------------------------------------------------------------------===//
473
474 void DAGCombiner::deleteAndRecombine(SDNode *N) {
475   removeFromWorklist(N);
476
477   // If the operands of this node are only used by the node, they will now be
478   // dead. Make sure to re-visit them and recursively delete dead nodes.
479   for (const SDValue &Op : N->ops())
480     // For an operand generating multiple values, one of the values may
481     // become dead allowing further simplification (e.g. split index
482     // arithmetic from an indexed load).
483     if (Op->hasOneUse() || Op->getNumValues() > 1)
484       AddToWorklist(Op.getNode());
485
486   DAG.DeleteNode(N);
487 }
488
489 /// Return 1 if we can compute the negated form of the specified expression for
490 /// the same cost as the expression itself, or 2 if we can compute the negated
491 /// form more cheaply than the expression itself.
492 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
493                                const TargetLowering &TLI,
494                                const TargetOptions *Options,
495                                unsigned Depth = 0) {
496   // fneg is removable even if it has multiple uses.
497   if (Op.getOpcode() == ISD::FNEG) return 2;
498
499   // Don't allow anything with multiple uses.
500   if (!Op.hasOneUse()) return 0;
501
502   // Don't recurse exponentially.
503   if (Depth > 6) return 0;
504
505   switch (Op.getOpcode()) {
506   default: return false;
507   case ISD::ConstantFP:
508     // Don't invert constant FP values after legalize.  The negated constant
509     // isn't necessarily legal.
510     return LegalOperations ? 0 : 1;
511   case ISD::FADD:
512     // FIXME: determine better conditions for this xform.
513     if (!Options->UnsafeFPMath) return 0;
514
515     // After operation legalization, it might not be legal to create new FSUBs.
516     if (LegalOperations &&
517         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
518       return 0;
519
520     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
521     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
522                                     Options, Depth + 1))
523       return V;
524     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
525     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
526                               Depth + 1);
527   case ISD::FSUB:
528     // We can't turn -(A-B) into B-A when we honor signed zeros.
529     if (!Options->UnsafeFPMath) return 0;
530
531     // fold (fneg (fsub A, B)) -> (fsub B, A)
532     return 1;
533
534   case ISD::FMUL:
535   case ISD::FDIV:
536     if (Options->HonorSignDependentRoundingFPMath()) return 0;
537
538     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
539     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
540                                     Options, Depth + 1))
541       return V;
542
543     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
544                               Depth + 1);
545
546   case ISD::FP_EXTEND:
547   case ISD::FP_ROUND:
548   case ISD::FSIN:
549     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
550                               Depth + 1);
551   }
552 }
553
554 /// If isNegatibleForFree returns true, return the newly negated expression.
555 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
556                                     bool LegalOperations, unsigned Depth = 0) {
557   const TargetOptions &Options = DAG.getTarget().Options;
558   // fneg is removable even if it has multiple uses.
559   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
560
561   // Don't allow anything with multiple uses.
562   assert(Op.hasOneUse() && "Unknown reuse!");
563
564   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
565   switch (Op.getOpcode()) {
566   default: llvm_unreachable("Unknown code");
567   case ISD::ConstantFP: {
568     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
569     V.changeSign();
570     return DAG.getConstantFP(V, Op.getValueType());
571   }
572   case ISD::FADD:
573     // FIXME: determine better conditions for this xform.
574     assert(Options.UnsafeFPMath);
575
576     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
577     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
578                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
579       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
580                          GetNegatedExpression(Op.getOperand(0), DAG,
581                                               LegalOperations, Depth+1),
582                          Op.getOperand(1));
583     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
584     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
585                        GetNegatedExpression(Op.getOperand(1), DAG,
586                                             LegalOperations, Depth+1),
587                        Op.getOperand(0));
588   case ISD::FSUB:
589     // We can't turn -(A-B) into B-A when we honor signed zeros.
590     assert(Options.UnsafeFPMath);
591
592     // fold (fneg (fsub 0, B)) -> B
593     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
594       if (N0CFP->getValueAPF().isZero())
595         return Op.getOperand(1);
596
597     // fold (fneg (fsub A, B)) -> (fsub B, A)
598     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
599                        Op.getOperand(1), Op.getOperand(0));
600
601   case ISD::FMUL:
602   case ISD::FDIV:
603     assert(!Options.HonorSignDependentRoundingFPMath());
604
605     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
606     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
607                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
608       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
609                          GetNegatedExpression(Op.getOperand(0), DAG,
610                                               LegalOperations, Depth+1),
611                          Op.getOperand(1));
612
613     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
614     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
615                        Op.getOperand(0),
616                        GetNegatedExpression(Op.getOperand(1), DAG,
617                                             LegalOperations, Depth+1));
618
619   case ISD::FP_EXTEND:
620   case ISD::FSIN:
621     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
622                        GetNegatedExpression(Op.getOperand(0), DAG,
623                                             LegalOperations, Depth+1));
624   case ISD::FP_ROUND:
625       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
626                          GetNegatedExpression(Op.getOperand(0), DAG,
627                                               LegalOperations, Depth+1),
628                          Op.getOperand(1));
629   }
630 }
631
632 // Return true if this node is a setcc, or is a select_cc
633 // that selects between the target values used for true and false, making it
634 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
635 // the appropriate nodes based on the type of node we are checking. This
636 // simplifies life a bit for the callers.
637 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
638                                     SDValue &CC) const {
639   if (N.getOpcode() == ISD::SETCC) {
640     LHS = N.getOperand(0);
641     RHS = N.getOperand(1);
642     CC  = N.getOperand(2);
643     return true;
644   }
645
646   if (N.getOpcode() != ISD::SELECT_CC ||
647       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
648       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
649     return false;
650
651   if (TLI.getBooleanContents(N.getValueType()) ==
652       TargetLowering::UndefinedBooleanContent)
653     return false;
654
655   LHS = N.getOperand(0);
656   RHS = N.getOperand(1);
657   CC  = N.getOperand(4);
658   return true;
659 }
660
661 /// Return true if this is a SetCC-equivalent operation with only one use.
662 /// If this is true, it allows the users to invert the operation for free when
663 /// it is profitable to do so.
664 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
665   SDValue N0, N1, N2;
666   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
667     return true;
668   return false;
669 }
670
671 /// Returns true if N is a BUILD_VECTOR node whose
672 /// elements are all the same constant or undefined.
673 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
674   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
675   if (!C)
676     return false;
677
678   APInt SplatUndef;
679   unsigned SplatBitSize;
680   bool HasAnyUndefs;
681   EVT EltVT = N->getValueType(0).getVectorElementType();
682   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
683                              HasAnyUndefs) &&
684           EltVT.getSizeInBits() >= SplatBitSize);
685 }
686
687 // \brief Returns the SDNode if it is a constant BuildVector or constant.
688 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
689   if (isa<ConstantSDNode>(N))
690     return N.getNode();
691   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
692   if (BV && BV->isConstant())
693     return BV;
694   return nullptr;
695 }
696
697 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
698 // int.
699 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
700   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
701     return CN;
702
703   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
704     BitVector UndefElements;
705     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
706
707     // BuildVectors can truncate their operands. Ignore that case here.
708     // FIXME: We blindly ignore splats which include undef which is overly
709     // pessimistic.
710     if (CN && UndefElements.none() &&
711         CN->getValueType(0) == N.getValueType().getScalarType())
712       return CN;
713   }
714
715   return nullptr;
716 }
717
718 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
719 // float.
720 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
721   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
722     return CN;
723
724   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
725     BitVector UndefElements;
726     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
727
728     if (CN && UndefElements.none())
729       return CN;
730   }
731
732   return nullptr;
733 }
734
735 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
736                                     SDValue N0, SDValue N1) {
737   EVT VT = N0.getValueType();
738   if (N0.getOpcode() == Opc) {
739     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
740       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
741         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
742         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
743         if (!OpNode.getNode())
744           return SDValue();
745         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
746       }
747       if (N0.hasOneUse()) {
748         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
749         // use
750         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
751         if (!OpNode.getNode())
752           return SDValue();
753         AddToWorklist(OpNode.getNode());
754         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
755       }
756     }
757   }
758
759   if (N1.getOpcode() == Opc) {
760     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
761       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
762         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
763         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
764         if (!OpNode.getNode())
765           return SDValue();
766         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
767       }
768       if (N1.hasOneUse()) {
769         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
770         // use
771         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
772         if (!OpNode.getNode())
773           return SDValue();
774         AddToWorklist(OpNode.getNode());
775         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
776       }
777     }
778   }
779
780   return SDValue();
781 }
782
783 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
784                                bool AddTo) {
785   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
786   ++NodesCombined;
787   DEBUG(dbgs() << "\nReplacing.1 ";
788         N->dump(&DAG);
789         dbgs() << "\nWith: ";
790         To[0].getNode()->dump(&DAG);
791         dbgs() << " and " << NumTo-1 << " other values\n";
792         for (unsigned i = 0, e = NumTo; i != e; ++i)
793           assert((!To[i].getNode() ||
794                   N->getValueType(i) == To[i].getValueType()) &&
795                  "Cannot combine value to value of different type!"));
796   WorklistRemover DeadNodes(*this);
797   DAG.ReplaceAllUsesWith(N, To);
798   if (AddTo) {
799     // Push the new nodes and any users onto the worklist
800     for (unsigned i = 0, e = NumTo; i != e; ++i) {
801       if (To[i].getNode()) {
802         AddToWorklist(To[i].getNode());
803         AddUsersToWorklist(To[i].getNode());
804       }
805     }
806   }
807
808   // Finally, if the node is now dead, remove it from the graph.  The node
809   // may not be dead if the replacement process recursively simplified to
810   // something else needing this node.
811   if (N->use_empty())
812     deleteAndRecombine(N);
813   return SDValue(N, 0);
814 }
815
816 void DAGCombiner::
817 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
818   // Replace all uses.  If any nodes become isomorphic to other nodes and
819   // are deleted, make sure to remove them from our worklist.
820   WorklistRemover DeadNodes(*this);
821   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
822
823   // Push the new node and any (possibly new) users onto the worklist.
824   AddToWorklist(TLO.New.getNode());
825   AddUsersToWorklist(TLO.New.getNode());
826
827   // Finally, if the node is now dead, remove it from the graph.  The node
828   // may not be dead if the replacement process recursively simplified to
829   // something else needing this node.
830   if (TLO.Old.getNode()->use_empty())
831     deleteAndRecombine(TLO.Old.getNode());
832 }
833
834 /// Check the specified integer node value to see if it can be simplified or if
835 /// things it uses can be simplified by bit propagation. If so, return true.
836 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
837   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
838   APInt KnownZero, KnownOne;
839   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
840     return false;
841
842   // Revisit the node.
843   AddToWorklist(Op.getNode());
844
845   // Replace the old value with the new one.
846   ++NodesCombined;
847   DEBUG(dbgs() << "\nReplacing.2 ";
848         TLO.Old.getNode()->dump(&DAG);
849         dbgs() << "\nWith: ";
850         TLO.New.getNode()->dump(&DAG);
851         dbgs() << '\n');
852
853   CommitTargetLoweringOpt(TLO);
854   return true;
855 }
856
857 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
858   SDLoc dl(Load);
859   EVT VT = Load->getValueType(0);
860   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
861
862   DEBUG(dbgs() << "\nReplacing.9 ";
863         Load->dump(&DAG);
864         dbgs() << "\nWith: ";
865         Trunc.getNode()->dump(&DAG);
866         dbgs() << '\n');
867   WorklistRemover DeadNodes(*this);
868   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
869   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
870   deleteAndRecombine(Load);
871   AddToWorklist(Trunc.getNode());
872 }
873
874 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
875   Replace = false;
876   SDLoc dl(Op);
877   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
878     EVT MemVT = LD->getMemoryVT();
879     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
880       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
881                                                   : ISD::EXTLOAD)
882       : LD->getExtensionType();
883     Replace = true;
884     return DAG.getExtLoad(ExtType, dl, PVT,
885                           LD->getChain(), LD->getBasePtr(),
886                           MemVT, LD->getMemOperand());
887   }
888
889   unsigned Opc = Op.getOpcode();
890   switch (Opc) {
891   default: break;
892   case ISD::AssertSext:
893     return DAG.getNode(ISD::AssertSext, dl, PVT,
894                        SExtPromoteOperand(Op.getOperand(0), PVT),
895                        Op.getOperand(1));
896   case ISD::AssertZext:
897     return DAG.getNode(ISD::AssertZext, dl, PVT,
898                        ZExtPromoteOperand(Op.getOperand(0), PVT),
899                        Op.getOperand(1));
900   case ISD::Constant: {
901     unsigned ExtOpc =
902       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
903     return DAG.getNode(ExtOpc, dl, PVT, Op);
904   }
905   }
906
907   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
908     return SDValue();
909   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
910 }
911
912 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
913   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
914     return SDValue();
915   EVT OldVT = Op.getValueType();
916   SDLoc dl(Op);
917   bool Replace = false;
918   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
919   if (!NewOp.getNode())
920     return SDValue();
921   AddToWorklist(NewOp.getNode());
922
923   if (Replace)
924     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
925   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
926                      DAG.getValueType(OldVT));
927 }
928
929 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
930   EVT OldVT = Op.getValueType();
931   SDLoc dl(Op);
932   bool Replace = false;
933   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
934   if (!NewOp.getNode())
935     return SDValue();
936   AddToWorklist(NewOp.getNode());
937
938   if (Replace)
939     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
940   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
941 }
942
943 /// Promote the specified integer binary operation if the target indicates it is
944 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
945 /// i32 since i16 instructions are longer.
946 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
947   if (!LegalOperations)
948     return SDValue();
949
950   EVT VT = Op.getValueType();
951   if (VT.isVector() || !VT.isInteger())
952     return SDValue();
953
954   // If operation type is 'undesirable', e.g. i16 on x86, consider
955   // promoting it.
956   unsigned Opc = Op.getOpcode();
957   if (TLI.isTypeDesirableForOp(Opc, VT))
958     return SDValue();
959
960   EVT PVT = VT;
961   // Consult target whether it is a good idea to promote this operation and
962   // what's the right type to promote it to.
963   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
964     assert(PVT != VT && "Don't know what type to promote to!");
965
966     bool Replace0 = false;
967     SDValue N0 = Op.getOperand(0);
968     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
969     if (!NN0.getNode())
970       return SDValue();
971
972     bool Replace1 = false;
973     SDValue N1 = Op.getOperand(1);
974     SDValue NN1;
975     if (N0 == N1)
976       NN1 = NN0;
977     else {
978       NN1 = PromoteOperand(N1, PVT, Replace1);
979       if (!NN1.getNode())
980         return SDValue();
981     }
982
983     AddToWorklist(NN0.getNode());
984     if (NN1.getNode())
985       AddToWorklist(NN1.getNode());
986
987     if (Replace0)
988       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
989     if (Replace1)
990       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
991
992     DEBUG(dbgs() << "\nPromoting ";
993           Op.getNode()->dump(&DAG));
994     SDLoc dl(Op);
995     return DAG.getNode(ISD::TRUNCATE, dl, VT,
996                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
997   }
998   return SDValue();
999 }
1000
1001 /// Promote the specified integer shift operation if the target indicates it is
1002 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1003 /// i32 since i16 instructions are longer.
1004 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1005   if (!LegalOperations)
1006     return SDValue();
1007
1008   EVT VT = Op.getValueType();
1009   if (VT.isVector() || !VT.isInteger())
1010     return SDValue();
1011
1012   // If operation type is 'undesirable', e.g. i16 on x86, consider
1013   // promoting it.
1014   unsigned Opc = Op.getOpcode();
1015   if (TLI.isTypeDesirableForOp(Opc, VT))
1016     return SDValue();
1017
1018   EVT PVT = VT;
1019   // Consult target whether it is a good idea to promote this operation and
1020   // what's the right type to promote it to.
1021   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1022     assert(PVT != VT && "Don't know what type to promote to!");
1023
1024     bool Replace = false;
1025     SDValue N0 = Op.getOperand(0);
1026     if (Opc == ISD::SRA)
1027       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1028     else if (Opc == ISD::SRL)
1029       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1030     else
1031       N0 = PromoteOperand(N0, PVT, Replace);
1032     if (!N0.getNode())
1033       return SDValue();
1034
1035     AddToWorklist(N0.getNode());
1036     if (Replace)
1037       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1038
1039     DEBUG(dbgs() << "\nPromoting ";
1040           Op.getNode()->dump(&DAG));
1041     SDLoc dl(Op);
1042     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1043                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1044   }
1045   return SDValue();
1046 }
1047
1048 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1049   if (!LegalOperations)
1050     return SDValue();
1051
1052   EVT VT = Op.getValueType();
1053   if (VT.isVector() || !VT.isInteger())
1054     return SDValue();
1055
1056   // If operation type is 'undesirable', e.g. i16 on x86, consider
1057   // promoting it.
1058   unsigned Opc = Op.getOpcode();
1059   if (TLI.isTypeDesirableForOp(Opc, VT))
1060     return SDValue();
1061
1062   EVT PVT = VT;
1063   // Consult target whether it is a good idea to promote this operation and
1064   // what's the right type to promote it to.
1065   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1066     assert(PVT != VT && "Don't know what type to promote to!");
1067     // fold (aext (aext x)) -> (aext x)
1068     // fold (aext (zext x)) -> (zext x)
1069     // fold (aext (sext x)) -> (sext x)
1070     DEBUG(dbgs() << "\nPromoting ";
1071           Op.getNode()->dump(&DAG));
1072     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1073   }
1074   return SDValue();
1075 }
1076
1077 bool DAGCombiner::PromoteLoad(SDValue Op) {
1078   if (!LegalOperations)
1079     return false;
1080
1081   EVT VT = Op.getValueType();
1082   if (VT.isVector() || !VT.isInteger())
1083     return false;
1084
1085   // If operation type is 'undesirable', e.g. i16 on x86, consider
1086   // promoting it.
1087   unsigned Opc = Op.getOpcode();
1088   if (TLI.isTypeDesirableForOp(Opc, VT))
1089     return false;
1090
1091   EVT PVT = VT;
1092   // Consult target whether it is a good idea to promote this operation and
1093   // what's the right type to promote it to.
1094   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095     assert(PVT != VT && "Don't know what type to promote to!");
1096
1097     SDLoc dl(Op);
1098     SDNode *N = Op.getNode();
1099     LoadSDNode *LD = cast<LoadSDNode>(N);
1100     EVT MemVT = LD->getMemoryVT();
1101     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1102       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1103                                                   : ISD::EXTLOAD)
1104       : LD->getExtensionType();
1105     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1106                                    LD->getChain(), LD->getBasePtr(),
1107                                    MemVT, LD->getMemOperand());
1108     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1109
1110     DEBUG(dbgs() << "\nPromoting ";
1111           N->dump(&DAG);
1112           dbgs() << "\nTo: ";
1113           Result.getNode()->dump(&DAG);
1114           dbgs() << '\n');
1115     WorklistRemover DeadNodes(*this);
1116     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1117     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1118     deleteAndRecombine(N);
1119     AddToWorklist(Result.getNode());
1120     return true;
1121   }
1122   return false;
1123 }
1124
1125 /// \brief Recursively delete a node which has no uses and any operands for
1126 /// which it is the only use.
1127 ///
1128 /// Note that this both deletes the nodes and removes them from the worklist.
1129 /// It also adds any nodes who have had a user deleted to the worklist as they
1130 /// may now have only one use and subject to other combines.
1131 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1132   if (!N->use_empty())
1133     return false;
1134
1135   SmallSetVector<SDNode *, 16> Nodes;
1136   Nodes.insert(N);
1137   do {
1138     N = Nodes.pop_back_val();
1139     if (!N)
1140       continue;
1141
1142     if (N->use_empty()) {
1143       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1144         Nodes.insert(N->getOperand(i).getNode());
1145
1146       removeFromWorklist(N);
1147       DAG.DeleteNode(N);
1148     } else {
1149       AddToWorklist(N);
1150     }
1151   } while (!Nodes.empty());
1152   return true;
1153 }
1154
1155 //===----------------------------------------------------------------------===//
1156 //  Main DAG Combiner implementation
1157 //===----------------------------------------------------------------------===//
1158
1159 void DAGCombiner::Run(CombineLevel AtLevel) {
1160   // set the instance variables, so that the various visit routines may use it.
1161   Level = AtLevel;
1162   LegalOperations = Level >= AfterLegalizeVectorOps;
1163   LegalTypes = Level >= AfterLegalizeTypes;
1164
1165   // Early exit if this basic block is in an optnone function.
1166   AttributeSet FnAttrs =
1167     DAG.getMachineFunction().getFunction()->getAttributes();
1168   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1169                            Attribute::OptimizeNone))
1170     return;
1171
1172   // Add all the dag nodes to the worklist.
1173   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1174        E = DAG.allnodes_end(); I != E; ++I)
1175     AddToWorklist(I);
1176
1177   // Create a dummy node (which is not added to allnodes), that adds a reference
1178   // to the root node, preventing it from being deleted, and tracking any
1179   // changes of the root.
1180   HandleSDNode Dummy(DAG.getRoot());
1181
1182   // while the worklist isn't empty, find a node and
1183   // try and combine it.
1184   while (!WorklistMap.empty()) {
1185     SDNode *N;
1186     // The Worklist holds the SDNodes in order, but it may contain null entries.
1187     do {
1188       N = Worklist.pop_back_val();
1189     } while (!N);
1190
1191     bool GoodWorklistEntry = WorklistMap.erase(N);
1192     (void)GoodWorklistEntry;
1193     assert(GoodWorklistEntry &&
1194            "Found a worklist entry without a corresponding map entry!");
1195
1196     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1197     // N is deleted from the DAG, since they too may now be dead or may have a
1198     // reduced number of uses, allowing other xforms.
1199     if (recursivelyDeleteUnusedNodes(N))
1200       continue;
1201
1202     WorklistRemover DeadNodes(*this);
1203
1204     // If this combine is running after legalizing the DAG, re-legalize any
1205     // nodes pulled off the worklist.
1206     if (Level == AfterLegalizeDAG) {
1207       SmallSetVector<SDNode *, 16> UpdatedNodes;
1208       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1209
1210       for (SDNode *LN : UpdatedNodes) {
1211         AddToWorklist(LN);
1212         AddUsersToWorklist(LN);
1213       }
1214       if (!NIsValid)
1215         continue;
1216     }
1217
1218     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1219
1220     // Add any operands of the new node which have not yet been combined to the
1221     // worklist as well. Because the worklist uniques things already, this
1222     // won't repeatedly process the same operand.
1223     CombinedNodes.insert(N);
1224     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1225       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1226         AddToWorklist(N->getOperand(i).getNode());
1227
1228     SDValue RV = combine(N);
1229
1230     if (!RV.getNode())
1231       continue;
1232
1233     ++NodesCombined;
1234
1235     // If we get back the same node we passed in, rather than a new node or
1236     // zero, we know that the node must have defined multiple values and
1237     // CombineTo was used.  Since CombineTo takes care of the worklist
1238     // mechanics for us, we have no work to do in this case.
1239     if (RV.getNode() == N)
1240       continue;
1241
1242     assert(N->getOpcode() != ISD::DELETED_NODE &&
1243            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1244            "Node was deleted but visit returned new node!");
1245
1246     DEBUG(dbgs() << " ... into: ";
1247           RV.getNode()->dump(&DAG));
1248
1249     // Transfer debug value.
1250     DAG.TransferDbgValues(SDValue(N, 0), RV);
1251     if (N->getNumValues() == RV.getNode()->getNumValues())
1252       DAG.ReplaceAllUsesWith(N, RV.getNode());
1253     else {
1254       assert(N->getValueType(0) == RV.getValueType() &&
1255              N->getNumValues() == 1 && "Type mismatch");
1256       SDValue OpV = RV;
1257       DAG.ReplaceAllUsesWith(N, &OpV);
1258     }
1259
1260     // Push the new node and any users onto the worklist
1261     AddToWorklist(RV.getNode());
1262     AddUsersToWorklist(RV.getNode());
1263
1264     // Finally, if the node is now dead, remove it from the graph.  The node
1265     // may not be dead if the replacement process recursively simplified to
1266     // something else needing this node. This will also take care of adding any
1267     // operands which have lost a user to the worklist.
1268     recursivelyDeleteUnusedNodes(N);
1269   }
1270
1271   // If the root changed (e.g. it was a dead load, update the root).
1272   DAG.setRoot(Dummy.getValue());
1273   DAG.RemoveDeadNodes();
1274 }
1275
1276 SDValue DAGCombiner::visit(SDNode *N) {
1277   switch (N->getOpcode()) {
1278   default: break;
1279   case ISD::TokenFactor:        return visitTokenFactor(N);
1280   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1281   case ISD::ADD:                return visitADD(N);
1282   case ISD::SUB:                return visitSUB(N);
1283   case ISD::ADDC:               return visitADDC(N);
1284   case ISD::SUBC:               return visitSUBC(N);
1285   case ISD::ADDE:               return visitADDE(N);
1286   case ISD::SUBE:               return visitSUBE(N);
1287   case ISD::MUL:                return visitMUL(N);
1288   case ISD::SDIV:               return visitSDIV(N);
1289   case ISD::UDIV:               return visitUDIV(N);
1290   case ISD::SREM:               return visitSREM(N);
1291   case ISD::UREM:               return visitUREM(N);
1292   case ISD::MULHU:              return visitMULHU(N);
1293   case ISD::MULHS:              return visitMULHS(N);
1294   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1295   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1296   case ISD::SMULO:              return visitSMULO(N);
1297   case ISD::UMULO:              return visitUMULO(N);
1298   case ISD::SDIVREM:            return visitSDIVREM(N);
1299   case ISD::UDIVREM:            return visitUDIVREM(N);
1300   case ISD::AND:                return visitAND(N);
1301   case ISD::OR:                 return visitOR(N);
1302   case ISD::XOR:                return visitXOR(N);
1303   case ISD::SHL:                return visitSHL(N);
1304   case ISD::SRA:                return visitSRA(N);
1305   case ISD::SRL:                return visitSRL(N);
1306   case ISD::ROTR:
1307   case ISD::ROTL:               return visitRotate(N);
1308   case ISD::CTLZ:               return visitCTLZ(N);
1309   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1310   case ISD::CTTZ:               return visitCTTZ(N);
1311   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1312   case ISD::CTPOP:              return visitCTPOP(N);
1313   case ISD::SELECT:             return visitSELECT(N);
1314   case ISD::VSELECT:            return visitVSELECT(N);
1315   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1316   case ISD::SETCC:              return visitSETCC(N);
1317   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1318   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1319   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1320   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1321   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1322   case ISD::BITCAST:            return visitBITCAST(N);
1323   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1324   case ISD::FADD:               return visitFADD(N);
1325   case ISD::FSUB:               return visitFSUB(N);
1326   case ISD::FMUL:               return visitFMUL(N);
1327   case ISD::FMA:                return visitFMA(N);
1328   case ISD::FDIV:               return visitFDIV(N);
1329   case ISD::FREM:               return visitFREM(N);
1330   case ISD::FSQRT:              return visitFSQRT(N);
1331   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1332   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1333   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1334   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1335   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1336   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1337   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1338   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1339   case ISD::FNEG:               return visitFNEG(N);
1340   case ISD::FABS:               return visitFABS(N);
1341   case ISD::FFLOOR:             return visitFFLOOR(N);
1342   case ISD::FMINNUM:            return visitFMINNUM(N);
1343   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1344   case ISD::FCEIL:              return visitFCEIL(N);
1345   case ISD::FTRUNC:             return visitFTRUNC(N);
1346   case ISD::BRCOND:             return visitBRCOND(N);
1347   case ISD::BR_CC:              return visitBR_CC(N);
1348   case ISD::LOAD:               return visitLOAD(N);
1349   case ISD::STORE:              return visitSTORE(N);
1350   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1351   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1352   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1353   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1354   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1355   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1356   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1357   case ISD::MLOAD:              return visitMLOAD(N);
1358   case ISD::MSTORE:             return visitMSTORE(N);
1359   }
1360   return SDValue();
1361 }
1362
1363 SDValue DAGCombiner::combine(SDNode *N) {
1364   SDValue RV = visit(N);
1365
1366   // If nothing happened, try a target-specific DAG combine.
1367   if (!RV.getNode()) {
1368     assert(N->getOpcode() != ISD::DELETED_NODE &&
1369            "Node was deleted but visit returned NULL!");
1370
1371     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1372         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1373
1374       // Expose the DAG combiner to the target combiner impls.
1375       TargetLowering::DAGCombinerInfo
1376         DagCombineInfo(DAG, Level, false, this);
1377
1378       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1379     }
1380   }
1381
1382   // If nothing happened still, try promoting the operation.
1383   if (!RV.getNode()) {
1384     switch (N->getOpcode()) {
1385     default: break;
1386     case ISD::ADD:
1387     case ISD::SUB:
1388     case ISD::MUL:
1389     case ISD::AND:
1390     case ISD::OR:
1391     case ISD::XOR:
1392       RV = PromoteIntBinOp(SDValue(N, 0));
1393       break;
1394     case ISD::SHL:
1395     case ISD::SRA:
1396     case ISD::SRL:
1397       RV = PromoteIntShiftOp(SDValue(N, 0));
1398       break;
1399     case ISD::SIGN_EXTEND:
1400     case ISD::ZERO_EXTEND:
1401     case ISD::ANY_EXTEND:
1402       RV = PromoteExtend(SDValue(N, 0));
1403       break;
1404     case ISD::LOAD:
1405       if (PromoteLoad(SDValue(N, 0)))
1406         RV = SDValue(N, 0);
1407       break;
1408     }
1409   }
1410
1411   // If N is a commutative binary node, try commuting it to enable more
1412   // sdisel CSE.
1413   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1414       N->getNumValues() == 1) {
1415     SDValue N0 = N->getOperand(0);
1416     SDValue N1 = N->getOperand(1);
1417
1418     // Constant operands are canonicalized to RHS.
1419     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1420       SDValue Ops[] = {N1, N0};
1421       SDNode *CSENode;
1422       if (const BinaryWithFlagsSDNode *BinNode =
1423               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1424         CSENode = DAG.getNodeIfExists(
1425             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1426             BinNode->hasNoSignedWrap(), BinNode->isExact());
1427       } else {
1428         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1429       }
1430       if (CSENode)
1431         return SDValue(CSENode, 0);
1432     }
1433   }
1434
1435   return RV;
1436 }
1437
1438 /// Given a node, return its input chain if it has one, otherwise return a null
1439 /// sd operand.
1440 static SDValue getInputChainForNode(SDNode *N) {
1441   if (unsigned NumOps = N->getNumOperands()) {
1442     if (N->getOperand(0).getValueType() == MVT::Other)
1443       return N->getOperand(0);
1444     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1445       return N->getOperand(NumOps-1);
1446     for (unsigned i = 1; i < NumOps-1; ++i)
1447       if (N->getOperand(i).getValueType() == MVT::Other)
1448         return N->getOperand(i);
1449   }
1450   return SDValue();
1451 }
1452
1453 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1454   // If N has two operands, where one has an input chain equal to the other,
1455   // the 'other' chain is redundant.
1456   if (N->getNumOperands() == 2) {
1457     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1458       return N->getOperand(0);
1459     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1460       return N->getOperand(1);
1461   }
1462
1463   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1464   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1465   SmallPtrSet<SDNode*, 16> SeenOps;
1466   bool Changed = false;             // If we should replace this token factor.
1467
1468   // Start out with this token factor.
1469   TFs.push_back(N);
1470
1471   // Iterate through token factors.  The TFs grows when new token factors are
1472   // encountered.
1473   for (unsigned i = 0; i < TFs.size(); ++i) {
1474     SDNode *TF = TFs[i];
1475
1476     // Check each of the operands.
1477     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1478       SDValue Op = TF->getOperand(i);
1479
1480       switch (Op.getOpcode()) {
1481       case ISD::EntryToken:
1482         // Entry tokens don't need to be added to the list. They are
1483         // rededundant.
1484         Changed = true;
1485         break;
1486
1487       case ISD::TokenFactor:
1488         if (Op.hasOneUse() &&
1489             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1490           // Queue up for processing.
1491           TFs.push_back(Op.getNode());
1492           // Clean up in case the token factor is removed.
1493           AddToWorklist(Op.getNode());
1494           Changed = true;
1495           break;
1496         }
1497         // Fall thru
1498
1499       default:
1500         // Only add if it isn't already in the list.
1501         if (SeenOps.insert(Op.getNode()).second)
1502           Ops.push_back(Op);
1503         else
1504           Changed = true;
1505         break;
1506       }
1507     }
1508   }
1509
1510   SDValue Result;
1511
1512   // If we've change things around then replace token factor.
1513   if (Changed) {
1514     if (Ops.empty()) {
1515       // The entry token is the only possible outcome.
1516       Result = DAG.getEntryNode();
1517     } else {
1518       // New and improved token factor.
1519       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1520     }
1521
1522     // Don't add users to work list.
1523     return CombineTo(N, Result, false);
1524   }
1525
1526   return Result;
1527 }
1528
1529 /// MERGE_VALUES can always be eliminated.
1530 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1531   WorklistRemover DeadNodes(*this);
1532   // Replacing results may cause a different MERGE_VALUES to suddenly
1533   // be CSE'd with N, and carry its uses with it. Iterate until no
1534   // uses remain, to ensure that the node can be safely deleted.
1535   // First add the users of this node to the work list so that they
1536   // can be tried again once they have new operands.
1537   AddUsersToWorklist(N);
1538   do {
1539     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1540       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1541   } while (!N->use_empty());
1542   deleteAndRecombine(N);
1543   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1544 }
1545
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547   SDValue N0 = N->getOperand(0);
1548   SDValue N1 = N->getOperand(1);
1549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551   EVT VT = N0.getValueType();
1552
1553   // fold vector ops
1554   if (VT.isVector()) {
1555     SDValue FoldedVOp = SimplifyVBinOp(N);
1556     if (FoldedVOp.getNode()) return FoldedVOp;
1557
1558     // fold (add x, 0) -> x, vector edition
1559     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560       return N0;
1561     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1562       return N1;
1563   }
1564
1565   // fold (add x, undef) -> undef
1566   if (N0.getOpcode() == ISD::UNDEF)
1567     return N0;
1568   if (N1.getOpcode() == ISD::UNDEF)
1569     return N1;
1570   // fold (add c1, c2) -> c1+c2
1571   if (N0C && N1C)
1572     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573   // canonicalize constant to RHS
1574   if (N0C && !N1C)
1575     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576   // fold (add x, 0) -> x
1577   if (N1C && N1C->isNullValue())
1578     return N0;
1579   // fold (add Sym, c) -> Sym+c
1580   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582         GA->getOpcode() == ISD::GlobalAddress)
1583       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584                                   GA->getOffset() +
1585                                     (uint64_t)N1C->getSExtValue());
1586   // fold ((c1-A)+c2) -> (c1+c2)-A
1587   if (N1C && N0.getOpcode() == ISD::SUB)
1588     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590                          DAG.getConstant(N1C->getAPIntValue()+
1591                                          N0C->getAPIntValue(), VT),
1592                          N0.getOperand(1));
1593   // reassociate add
1594   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1595   if (RADD.getNode())
1596     return RADD;
1597   // fold ((0-A) + B) -> B-A
1598   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601   // fold (A + (0-B)) -> A-B
1602   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605   // fold (A+(B-A)) -> B
1606   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607     return N1.getOperand(0);
1608   // fold ((B-A)+A) -> B
1609   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610     return N0.getOperand(0);
1611   // fold (A+(B-(A+C))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(0))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(1));
1616   // fold (A+(B-(C+A))) to (B-C)
1617   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618       N0 == N1.getOperand(1).getOperand(1))
1619     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620                        N1.getOperand(1).getOperand(0));
1621   // fold (A+((B-A)+or-C)) to (B+or-C)
1622   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623       N1.getOperand(0).getOpcode() == ISD::SUB &&
1624       N0 == N1.getOperand(0).getOperand(1))
1625     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1627
1628   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630     SDValue N00 = N0.getOperand(0);
1631     SDValue N01 = N0.getOperand(1);
1632     SDValue N10 = N1.getOperand(0);
1633     SDValue N11 = N1.getOperand(1);
1634
1635     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1639   }
1640
1641   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642     return SDValue(N, 0);
1643
1644   // fold (a+b) -> (a|b) iff a and b share no bits.
1645   if (VT.isInteger() && !VT.isVector()) {
1646     APInt LHSZero, LHSOne;
1647     APInt RHSZero, RHSOne;
1648     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1649
1650     if (LHSZero.getBoolValue()) {
1651       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1652
1653       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1658       }
1659     }
1660   }
1661
1662   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1663   if (N1.getOpcode() == ISD::SHL &&
1664       N1.getOperand(0).getOpcode() == ISD::SUB)
1665     if (ConstantSDNode *C =
1666           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1667       if (C->getAPIntValue() == 0)
1668         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1669                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670                                        N1.getOperand(0).getOperand(1),
1671                                        N1.getOperand(1)));
1672   if (N0.getOpcode() == ISD::SHL &&
1673       N0.getOperand(0).getOpcode() == ISD::SUB)
1674     if (ConstantSDNode *C =
1675           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1676       if (C->getAPIntValue() == 0)
1677         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1678                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1679                                        N0.getOperand(0).getOperand(1),
1680                                        N0.getOperand(1)));
1681
1682   if (N1.getOpcode() == ISD::AND) {
1683     SDValue AndOp0 = N1.getOperand(0);
1684     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1685     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1686     unsigned DestBits = VT.getScalarType().getSizeInBits();
1687
1688     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1689     // and similar xforms where the inner op is either ~0 or 0.
1690     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1691       SDLoc DL(N);
1692       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1693     }
1694   }
1695
1696   // add (sext i1), X -> sub X, (zext i1)
1697   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1698       N0.getOperand(0).getValueType() == MVT::i1 &&
1699       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1700     SDLoc DL(N);
1701     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1702     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1703   }
1704
1705   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1706   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1707     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1708     if (TN->getVT() == MVT::i1) {
1709       SDLoc DL(N);
1710       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1711                                  DAG.getConstant(1, VT));
1712       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1713     }
1714   }
1715
1716   return SDValue();
1717 }
1718
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720   SDValue N0 = N->getOperand(0);
1721   SDValue N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724   EVT VT = N0.getValueType();
1725
1726   // If the flag result is dead, turn this into an ADD.
1727   if (!N->hasAnyUseOfValue(1))
1728     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729                      DAG.getNode(ISD::CARRY_FALSE,
1730                                  SDLoc(N), MVT::Glue));
1731
1732   // canonicalize constant to RHS.
1733   if (N0C && !N1C)
1734     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735
1736   // fold (addc x, 0) -> x + no carry out
1737   if (N1C && N1C->isNullValue())
1738     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739                                         SDLoc(N), MVT::Glue));
1740
1741   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742   APInt LHSZero, LHSOne;
1743   APInt RHSZero, RHSOne;
1744   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745
1746   if (LHSZero.getBoolValue()) {
1747     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748
1749     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753                        DAG.getNode(ISD::CARRY_FALSE,
1754                                    SDLoc(N), MVT::Glue));
1755   }
1756
1757   return SDValue();
1758 }
1759
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761   SDValue N0 = N->getOperand(0);
1762   SDValue N1 = N->getOperand(1);
1763   SDValue CarryIn = N->getOperand(2);
1764   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766
1767   // canonicalize constant to RHS
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1770                        N1, N0, CarryIn);
1771
1772   // fold (adde x, y, false) -> (addc x, y)
1773   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1775
1776   return SDValue();
1777 }
1778
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782                              SelectionDAG &DAG,
1783                              bool LegalOperations, bool LegalTypes) {
1784   if (!VT.isVector())
1785     return DAG.getConstant(0, VT);
1786   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787     return DAG.getConstant(0, VT);
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798   EVT VT = N0.getValueType();
1799
1800   // fold vector ops
1801   if (VT.isVector()) {
1802     SDValue FoldedVOp = SimplifyVBinOp(N);
1803     if (FoldedVOp.getNode()) return FoldedVOp;
1804
1805     // fold (sub x, 0) -> x, vector edition
1806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1807       return N0;
1808   }
1809
1810   // fold (sub x, x) -> 0
1811   // FIXME: Refactor this and xor and other similar operations together.
1812   if (N0 == N1)
1813     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814   // fold (sub c1, c2) -> c1-c2
1815   if (N0C && N1C)
1816     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817   // fold (sub x, c) -> (add x, -c)
1818   if (N1C)
1819     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1821   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822   if (N0C && N0C->isAllOnesValue())
1823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824   // fold A-(A-B) -> B
1825   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826     return N1.getOperand(1);
1827   // fold (A+B)-A -> B
1828   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829     return N0.getOperand(1);
1830   // fold (A+B)-B -> A
1831   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832     return N0.getOperand(0);
1833   // fold C2-(A+C1) -> (C2-C1)-A
1834   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836                                    VT);
1837     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1838                        N1.getOperand(0));
1839   }
1840   // fold ((A+(B+or-C))-B) -> A+or-C
1841   if (N0.getOpcode() == ISD::ADD &&
1842       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844       N0.getOperand(1).getOperand(0) == N1)
1845     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847   // fold ((A+(C+B))-B) -> A+C
1848   if (N0.getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOpcode() == ISD::ADD &&
1850       N0.getOperand(1).getOperand(1) == N1)
1851     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853   // fold ((A-(B-C))-C) -> A-B
1854   if (N0.getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOpcode() == ISD::SUB &&
1856       N0.getOperand(1).getOperand(1) == N1)
1857     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859
1860   // If either operand of a sub is undef, the result is undef
1861   if (N0.getOpcode() == ISD::UNDEF)
1862     return N0;
1863   if (N1.getOpcode() == ISD::UNDEF)
1864     return N1;
1865
1866   // If the relocation model supports it, consider symbol offsets.
1867   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869       // fold (sub Sym, c) -> Sym-c
1870       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872                                     GA->getOffset() -
1873                                       (uint64_t)N1C->getSExtValue());
1874       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876         if (GA->getGlobal() == GB->getGlobal())
1877           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1878                                  VT);
1879     }
1880
1881   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1882   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1883     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1884     if (TN->getVT() == MVT::i1) {
1885       SDLoc DL(N);
1886       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1887                                  DAG.getConstant(1, VT));
1888       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1889     }
1890   }
1891
1892   return SDValue();
1893 }
1894
1895 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1896   SDValue N0 = N->getOperand(0);
1897   SDValue N1 = N->getOperand(1);
1898   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1899   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1900   EVT VT = N0.getValueType();
1901
1902   // If the flag result is dead, turn this into an SUB.
1903   if (!N->hasAnyUseOfValue(1))
1904     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1905                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1906                                  MVT::Glue));
1907
1908   // fold (subc x, x) -> 0 + no borrow
1909   if (N0 == N1)
1910     return CombineTo(N, DAG.getConstant(0, VT),
1911                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                  MVT::Glue));
1913
1914   // fold (subc x, 0) -> x + no borrow
1915   if (N1C && N1C->isNullValue())
1916     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1917                                         MVT::Glue));
1918
1919   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1920   if (N0C && N0C->isAllOnesValue())
1921     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1922                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1923                                  MVT::Glue));
1924
1925   return SDValue();
1926 }
1927
1928 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   SDValue CarryIn = N->getOperand(2);
1932
1933   // fold (sube x, y, false) -> (subc x, y)
1934   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1935     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1936
1937   return SDValue();
1938 }
1939
1940 SDValue DAGCombiner::visitMUL(SDNode *N) {
1941   SDValue N0 = N->getOperand(0);
1942   SDValue N1 = N->getOperand(1);
1943   EVT VT = N0.getValueType();
1944
1945   // fold (mul x, undef) -> 0
1946   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1947     return DAG.getConstant(0, VT);
1948
1949   bool N0IsConst = false;
1950   bool N1IsConst = false;
1951   APInt ConstValue0, ConstValue1;
1952   // fold vector ops
1953   if (VT.isVector()) {
1954     SDValue FoldedVOp = SimplifyVBinOp(N);
1955     if (FoldedVOp.getNode()) return FoldedVOp;
1956
1957     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1958     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1959   } else {
1960     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1961     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1962                             : APInt();
1963     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1964     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1965                             : APInt();
1966   }
1967
1968   // fold (mul c1, c2) -> c1*c2
1969   if (N0IsConst && N1IsConst)
1970     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1971
1972   // canonicalize constant to RHS
1973   if (N0IsConst && !N1IsConst)
1974     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1975   // fold (mul x, 0) -> 0
1976   if (N1IsConst && ConstValue1 == 0)
1977     return N1;
1978   // We require a splat of the entire scalar bit width for non-contiguous
1979   // bit patterns.
1980   bool IsFullSplat =
1981     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1982   // fold (mul x, 1) -> x
1983   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1984     return N0;
1985   // fold (mul x, -1) -> 0-x
1986   if (N1IsConst && ConstValue1.isAllOnesValue())
1987     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988                        DAG.getConstant(0, VT), N0);
1989   // fold (mul x, (1 << c)) -> x << c
1990   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1991     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1992                        DAG.getConstant(ConstValue1.logBase2(),
1993                                        getShiftAmountTy(N0.getValueType())));
1994   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1995   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1996     unsigned Log2Val = (-ConstValue1).logBase2();
1997     // FIXME: If the input is something that is easily negated (e.g. a
1998     // single-use add), we should put the negate there.
1999     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000                        DAG.getConstant(0, VT),
2001                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2002                             DAG.getConstant(Log2Val,
2003                                       getShiftAmountTy(N0.getValueType()))));
2004   }
2005
2006   APInt Val;
2007   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2008   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2009       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2010                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2011     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2012                              N1, N0.getOperand(1));
2013     AddToWorklist(C3.getNode());
2014     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2015                        N0.getOperand(0), C3);
2016   }
2017
2018   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2019   // use.
2020   {
2021     SDValue Sh(nullptr,0), Y(nullptr,0);
2022     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2023     if (N0.getOpcode() == ISD::SHL &&
2024         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2025                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2026         N0.getNode()->hasOneUse()) {
2027       Sh = N0; Y = N1;
2028     } else if (N1.getOpcode() == ISD::SHL &&
2029                isa<ConstantSDNode>(N1.getOperand(1)) &&
2030                N1.getNode()->hasOneUse()) {
2031       Sh = N1; Y = N0;
2032     }
2033
2034     if (Sh.getNode()) {
2035       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036                                 Sh.getOperand(0), Y);
2037       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2038                          Mul, Sh.getOperand(1));
2039     }
2040   }
2041
2042   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2043   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2044       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2045                      isa<ConstantSDNode>(N0.getOperand(1))))
2046     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2047                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2048                                    N0.getOperand(0), N1),
2049                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2050                                    N0.getOperand(1), N1));
2051
2052   // reassociate mul
2053   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2054   if (RMUL.getNode())
2055     return RMUL;
2056
2057   return SDValue();
2058 }
2059
2060 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2061   SDValue N0 = N->getOperand(0);
2062   SDValue N1 = N->getOperand(1);
2063   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2064   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2065   EVT VT = N->getValueType(0);
2066
2067   // fold vector ops
2068   if (VT.isVector()) {
2069     SDValue FoldedVOp = SimplifyVBinOp(N);
2070     if (FoldedVOp.getNode()) return FoldedVOp;
2071   }
2072
2073   // fold (sdiv c1, c2) -> c1/c2
2074   if (N0C && N1C && !N1C->isNullValue())
2075     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2076   // fold (sdiv X, 1) -> X
2077   if (N1C && N1C->getAPIntValue() == 1LL)
2078     return N0;
2079   // fold (sdiv X, -1) -> 0-X
2080   if (N1C && N1C->isAllOnesValue())
2081     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2082                        DAG.getConstant(0, VT), N0);
2083   // If we know the sign bits of both operands are zero, strength reduce to a
2084   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2085   if (!VT.isVector()) {
2086     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2088                          N0, N1);
2089   }
2090
2091   // fold (sdiv X, pow2) -> simple ops after legalize
2092   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2093                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2094     // If dividing by powers of two is cheap, then don't perform the following
2095     // fold.
2096     if (TLI.isPow2SDivCheap())
2097       return SDValue();
2098
2099     // Target-specific implementation of sdiv x, pow2.
2100     SDValue Res = BuildSDIVPow2(N);
2101     if (Res.getNode())
2102       return Res;
2103
2104     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2105
2106     // Splat the sign bit into the register
2107     SDValue SGN =
2108         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2109                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2110                                     getShiftAmountTy(N0.getValueType())));
2111     AddToWorklist(SGN.getNode());
2112
2113     // Add (N0 < 0) ? abs2 - 1 : 0;
2114     SDValue SRL =
2115         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2116                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2117                                     getShiftAmountTy(SGN.getValueType())));
2118     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2119     AddToWorklist(SRL.getNode());
2120     AddToWorklist(ADD.getNode());    // Divide by pow2
2121     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2122                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2123
2124     // If we're dividing by a positive value, we're done.  Otherwise, we must
2125     // negate the result.
2126     if (N1C->getAPIntValue().isNonNegative())
2127       return SRA;
2128
2129     AddToWorklist(SRA.getNode());
2130     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2131   }
2132
2133   // if integer divide is expensive and we satisfy the requirements, emit an
2134   // alternate sequence.
2135   if (N1C && !TLI.isIntDivCheap()) {
2136     SDValue Op = BuildSDIV(N);
2137     if (Op.getNode()) return Op;
2138   }
2139
2140   // undef / X -> 0
2141   if (N0.getOpcode() == ISD::UNDEF)
2142     return DAG.getConstant(0, VT);
2143   // X / undef -> undef
2144   if (N1.getOpcode() == ISD::UNDEF)
2145     return N1;
2146
2147   return SDValue();
2148 }
2149
2150 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2151   SDValue N0 = N->getOperand(0);
2152   SDValue N1 = N->getOperand(1);
2153   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2154   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2155   EVT VT = N->getValueType(0);
2156
2157   // fold vector ops
2158   if (VT.isVector()) {
2159     SDValue FoldedVOp = SimplifyVBinOp(N);
2160     if (FoldedVOp.getNode()) return FoldedVOp;
2161   }
2162
2163   // fold (udiv c1, c2) -> c1/c2
2164   if (N0C && N1C && !N1C->isNullValue())
2165     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2166   // fold (udiv x, (1 << c)) -> x >>u c
2167   if (N1C && N1C->getAPIntValue().isPowerOf2())
2168     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2169                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2170                                        getShiftAmountTy(N0.getValueType())));
2171   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2172   if (N1.getOpcode() == ISD::SHL) {
2173     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174       if (SHC->getAPIntValue().isPowerOf2()) {
2175         EVT ADDVT = N1.getOperand(1).getValueType();
2176         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2177                                   N1.getOperand(1),
2178                                   DAG.getConstant(SHC->getAPIntValue()
2179                                                                   .logBase2(),
2180                                                   ADDVT));
2181         AddToWorklist(Add.getNode());
2182         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2183       }
2184     }
2185   }
2186   // fold (udiv x, c) -> alternate
2187   if (N1C && !TLI.isIntDivCheap()) {
2188     SDValue Op = BuildUDIV(N);
2189     if (Op.getNode()) return Op;
2190   }
2191
2192   // undef / X -> 0
2193   if (N0.getOpcode() == ISD::UNDEF)
2194     return DAG.getConstant(0, VT);
2195   // X / undef -> undef
2196   if (N1.getOpcode() == ISD::UNDEF)
2197     return N1;
2198
2199   return SDValue();
2200 }
2201
2202 SDValue DAGCombiner::visitSREM(SDNode *N) {
2203   SDValue N0 = N->getOperand(0);
2204   SDValue N1 = N->getOperand(1);
2205   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2207   EVT VT = N->getValueType(0);
2208
2209   // fold (srem c1, c2) -> c1%c2
2210   if (N0C && N1C && !N1C->isNullValue())
2211     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2212   // If we know the sign bits of both operands are zero, strength reduce to a
2213   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2214   if (!VT.isVector()) {
2215     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2216       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2217   }
2218
2219   // If X/C can be simplified by the division-by-constant logic, lower
2220   // X%C to the equivalent of X-X/C*C.
2221   if (N1C && !N1C->isNullValue()) {
2222     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2223     AddToWorklist(Div.getNode());
2224     SDValue OptimizedDiv = combine(Div.getNode());
2225     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2226       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2227                                 OptimizedDiv, N1);
2228       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2229       AddToWorklist(Mul.getNode());
2230       return Sub;
2231     }
2232   }
2233
2234   // undef % X -> 0
2235   if (N0.getOpcode() == ISD::UNDEF)
2236     return DAG.getConstant(0, VT);
2237   // X % undef -> undef
2238   if (N1.getOpcode() == ISD::UNDEF)
2239     return N1;
2240
2241   return SDValue();
2242 }
2243
2244 SDValue DAGCombiner::visitUREM(SDNode *N) {
2245   SDValue N0 = N->getOperand(0);
2246   SDValue N1 = N->getOperand(1);
2247   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2248   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2249   EVT VT = N->getValueType(0);
2250
2251   // fold (urem c1, c2) -> c1%c2
2252   if (N0C && N1C && !N1C->isNullValue())
2253     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2254   // fold (urem x, pow2) -> (and x, pow2-1)
2255   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2256     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2257                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2258   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2259   if (N1.getOpcode() == ISD::SHL) {
2260     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2261       if (SHC->getAPIntValue().isPowerOf2()) {
2262         SDValue Add =
2263           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2264                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2265                                  VT));
2266         AddToWorklist(Add.getNode());
2267         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2268       }
2269     }
2270   }
2271
2272   // If X/C can be simplified by the division-by-constant logic, lower
2273   // X%C to the equivalent of X-X/C*C.
2274   if (N1C && !N1C->isNullValue()) {
2275     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2276     AddToWorklist(Div.getNode());
2277     SDValue OptimizedDiv = combine(Div.getNode());
2278     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2279       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2280                                 OptimizedDiv, N1);
2281       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2282       AddToWorklist(Mul.getNode());
2283       return Sub;
2284     }
2285   }
2286
2287   // undef % X -> 0
2288   if (N0.getOpcode() == ISD::UNDEF)
2289     return DAG.getConstant(0, VT);
2290   // X % undef -> undef
2291   if (N1.getOpcode() == ISD::UNDEF)
2292     return N1;
2293
2294   return SDValue();
2295 }
2296
2297 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2298   SDValue N0 = N->getOperand(0);
2299   SDValue N1 = N->getOperand(1);
2300   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301   EVT VT = N->getValueType(0);
2302   SDLoc DL(N);
2303
2304   // fold (mulhs x, 0) -> 0
2305   if (N1C && N1C->isNullValue())
2306     return N1;
2307   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2308   if (N1C && N1C->getAPIntValue() == 1)
2309     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2310                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2311                                        getShiftAmountTy(N0.getValueType())));
2312   // fold (mulhs x, undef) -> 0
2313   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2314     return DAG.getConstant(0, VT);
2315
2316   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2317   // plus a shift.
2318   if (VT.isSimple() && !VT.isVector()) {
2319     MVT Simple = VT.getSimpleVT();
2320     unsigned SimpleSize = Simple.getSizeInBits();
2321     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2322     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2323       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2324       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2325       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2326       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2327             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2328       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2329     }
2330   }
2331
2332   return SDValue();
2333 }
2334
2335 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2336   SDValue N0 = N->getOperand(0);
2337   SDValue N1 = N->getOperand(1);
2338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2339   EVT VT = N->getValueType(0);
2340   SDLoc DL(N);
2341
2342   // fold (mulhu x, 0) -> 0
2343   if (N1C && N1C->isNullValue())
2344     return N1;
2345   // fold (mulhu x, 1) -> 0
2346   if (N1C && N1C->getAPIntValue() == 1)
2347     return DAG.getConstant(0, N0.getValueType());
2348   // fold (mulhu x, undef) -> 0
2349   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2350     return DAG.getConstant(0, VT);
2351
2352   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353   // plus a shift.
2354   if (VT.isSimple() && !VT.isVector()) {
2355     MVT Simple = VT.getSimpleVT();
2356     unsigned SimpleSize = Simple.getSizeInBits();
2357     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2360       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2361       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2362       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2363             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2364       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2365     }
2366   }
2367
2368   return SDValue();
2369 }
2370
2371 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2372 /// give the opcodes for the two computations that are being performed. Return
2373 /// true if a simplification was made.
2374 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2375                                                 unsigned HiOp) {
2376   // If the high half is not needed, just compute the low half.
2377   bool HiExists = N->hasAnyUseOfValue(1);
2378   if (!HiExists &&
2379       (!LegalOperations ||
2380        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2381     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2382     return CombineTo(N, Res, Res);
2383   }
2384
2385   // If the low half is not needed, just compute the high half.
2386   bool LoExists = N->hasAnyUseOfValue(0);
2387   if (!LoExists &&
2388       (!LegalOperations ||
2389        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2390     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2391     return CombineTo(N, Res, Res);
2392   }
2393
2394   // If both halves are used, return as it is.
2395   if (LoExists && HiExists)
2396     return SDValue();
2397
2398   // If the two computed results can be simplified separately, separate them.
2399   if (LoExists) {
2400     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2401     AddToWorklist(Lo.getNode());
2402     SDValue LoOpt = combine(Lo.getNode());
2403     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2404         (!LegalOperations ||
2405          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2406       return CombineTo(N, LoOpt, LoOpt);
2407   }
2408
2409   if (HiExists) {
2410     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2411     AddToWorklist(Hi.getNode());
2412     SDValue HiOpt = combine(Hi.getNode());
2413     if (HiOpt.getNode() && HiOpt != Hi &&
2414         (!LegalOperations ||
2415          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2416       return CombineTo(N, HiOpt, HiOpt);
2417   }
2418
2419   return SDValue();
2420 }
2421
2422 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2423   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2424   if (Res.getNode()) return Res;
2425
2426   EVT VT = N->getValueType(0);
2427   SDLoc DL(N);
2428
2429   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2430   // plus a shift.
2431   if (VT.isSimple() && !VT.isVector()) {
2432     MVT Simple = VT.getSimpleVT();
2433     unsigned SimpleSize = Simple.getSizeInBits();
2434     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2435     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2436       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2437       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2438       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2439       // Compute the high part as N1.
2440       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2441             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2442       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2443       // Compute the low part as N0.
2444       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2445       return CombineTo(N, Lo, Hi);
2446     }
2447   }
2448
2449   return SDValue();
2450 }
2451
2452 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2453   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2454   if (Res.getNode()) return Res;
2455
2456   EVT VT = N->getValueType(0);
2457   SDLoc DL(N);
2458
2459   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2460   // plus a shift.
2461   if (VT.isSimple() && !VT.isVector()) {
2462     MVT Simple = VT.getSimpleVT();
2463     unsigned SimpleSize = Simple.getSizeInBits();
2464     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2467       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2468       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469       // Compute the high part as N1.
2470       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2471             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2472       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473       // Compute the low part as N0.
2474       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475       return CombineTo(N, Lo, Hi);
2476     }
2477   }
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2483   // (smulo x, 2) -> (saddo x, x)
2484   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2485     if (C2->getAPIntValue() == 2)
2486       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2487                          N->getOperand(0), N->getOperand(0));
2488
2489   return SDValue();
2490 }
2491
2492 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2493   // (umulo x, 2) -> (uaddo x, x)
2494   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2495     if (C2->getAPIntValue() == 2)
2496       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2497                          N->getOperand(0), N->getOperand(0));
2498
2499   return SDValue();
2500 }
2501
2502 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2503   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2504   if (Res.getNode()) return Res;
2505
2506   return SDValue();
2507 }
2508
2509 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2510   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2511   if (Res.getNode()) return Res;
2512
2513   return SDValue();
2514 }
2515
2516 /// If this is a binary operator with two operands of the same opcode, try to
2517 /// simplify it.
2518 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2519   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2520   EVT VT = N0.getValueType();
2521   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2522
2523   // Bail early if none of these transforms apply.
2524   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2525
2526   // For each of OP in AND/OR/XOR:
2527   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2528   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2529   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2530   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2531   //
2532   // do not sink logical op inside of a vector extend, since it may combine
2533   // into a vsetcc.
2534   EVT Op0VT = N0.getOperand(0).getValueType();
2535   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2536        N0.getOpcode() == ISD::SIGN_EXTEND ||
2537        // Avoid infinite looping with PromoteIntBinOp.
2538        (N0.getOpcode() == ISD::ANY_EXTEND &&
2539         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2540        (N0.getOpcode() == ISD::TRUNCATE &&
2541         (!TLI.isZExtFree(VT, Op0VT) ||
2542          !TLI.isTruncateFree(Op0VT, VT)) &&
2543         TLI.isTypeLegal(Op0VT))) &&
2544       !VT.isVector() &&
2545       Op0VT == N1.getOperand(0).getValueType() &&
2546       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2547     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2548                                  N0.getOperand(0).getValueType(),
2549                                  N0.getOperand(0), N1.getOperand(0));
2550     AddToWorklist(ORNode.getNode());
2551     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2552   }
2553
2554   // For each of OP in SHL/SRL/SRA/AND...
2555   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2556   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2557   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2558   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2559        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2560       N0.getOperand(1) == N1.getOperand(1)) {
2561     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2562                                  N0.getOperand(0).getValueType(),
2563                                  N0.getOperand(0), N1.getOperand(0));
2564     AddToWorklist(ORNode.getNode());
2565     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2566                        ORNode, N0.getOperand(1));
2567   }
2568
2569   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2570   // Only perform this optimization after type legalization and before
2571   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2572   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2573   // we don't want to undo this promotion.
2574   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2575   // on scalars.
2576   if ((N0.getOpcode() == ISD::BITCAST ||
2577        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2578       Level == AfterLegalizeTypes) {
2579     SDValue In0 = N0.getOperand(0);
2580     SDValue In1 = N1.getOperand(0);
2581     EVT In0Ty = In0.getValueType();
2582     EVT In1Ty = In1.getValueType();
2583     SDLoc DL(N);
2584     // If both incoming values are integers, and the original types are the
2585     // same.
2586     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2587       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2588       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2589       AddToWorklist(Op.getNode());
2590       return BC;
2591     }
2592   }
2593
2594   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2595   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2596   // If both shuffles use the same mask, and both shuffle within a single
2597   // vector, then it is worthwhile to move the swizzle after the operation.
2598   // The type-legalizer generates this pattern when loading illegal
2599   // vector types from memory. In many cases this allows additional shuffle
2600   // optimizations.
2601   // There are other cases where moving the shuffle after the xor/and/or
2602   // is profitable even if shuffles don't perform a swizzle.
2603   // If both shuffles use the same mask, and both shuffles have the same first
2604   // or second operand, then it might still be profitable to move the shuffle
2605   // after the xor/and/or operation.
2606   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2607     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2608     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2609
2610     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2611            "Inputs to shuffles are not the same type");
2612
2613     // Check that both shuffles use the same mask. The masks are known to be of
2614     // the same length because the result vector type is the same.
2615     // Check also that shuffles have only one use to avoid introducing extra
2616     // instructions.
2617     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2618         SVN0->getMask().equals(SVN1->getMask())) {
2619       SDValue ShOp = N0->getOperand(1);
2620
2621       // Don't try to fold this node if it requires introducing a
2622       // build vector of all zeros that might be illegal at this stage.
2623       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2624         if (!LegalTypes)
2625           ShOp = DAG.getConstant(0, VT);
2626         else
2627           ShOp = SDValue();
2628       }
2629
2630       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2631       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2632       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2633       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2634         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2635                                       N0->getOperand(0), N1->getOperand(0));
2636         AddToWorklist(NewNode.getNode());
2637         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2638                                     &SVN0->getMask()[0]);
2639       }
2640
2641       // Don't try to fold this node if it requires introducing a
2642       // build vector of all zeros that might be illegal at this stage.
2643       ShOp = N0->getOperand(0);
2644       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2645         if (!LegalTypes)
2646           ShOp = DAG.getConstant(0, VT);
2647         else
2648           ShOp = SDValue();
2649       }
2650
2651       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2652       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2653       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2654       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2655         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2656                                       N0->getOperand(1), N1->getOperand(1));
2657         AddToWorklist(NewNode.getNode());
2658         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2659                                     &SVN0->getMask()[0]);
2660       }
2661     }
2662   }
2663
2664   return SDValue();
2665 }
2666
2667 SDValue DAGCombiner::visitAND(SDNode *N) {
2668   SDValue N0 = N->getOperand(0);
2669   SDValue N1 = N->getOperand(1);
2670   SDValue LL, LR, RL, RR, CC0, CC1;
2671   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2672   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2673   EVT VT = N1.getValueType();
2674   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2675
2676   // fold vector ops
2677   if (VT.isVector()) {
2678     SDValue FoldedVOp = SimplifyVBinOp(N);
2679     if (FoldedVOp.getNode()) return FoldedVOp;
2680
2681     // fold (and x, 0) -> 0, vector edition
2682     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2683       // do not return N0, because undef node may exist in N0
2684       return DAG.getConstant(
2685           APInt::getNullValue(
2686               N0.getValueType().getScalarType().getSizeInBits()),
2687           N0.getValueType());
2688     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2689       // do not return N1, because undef node may exist in N1
2690       return DAG.getConstant(
2691           APInt::getNullValue(
2692               N1.getValueType().getScalarType().getSizeInBits()),
2693           N1.getValueType());
2694
2695     // fold (and x, -1) -> x, vector edition
2696     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2697       return N1;
2698     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2699       return N0;
2700   }
2701
2702   // fold (and x, undef) -> 0
2703   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2704     return DAG.getConstant(0, VT);
2705   // fold (and c1, c2) -> c1&c2
2706   if (N0C && N1C)
2707     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2708   // canonicalize constant to RHS
2709   if (N0C && !N1C)
2710     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2711   // fold (and x, -1) -> x
2712   if (N1C && N1C->isAllOnesValue())
2713     return N0;
2714   // if (and x, c) is known to be zero, return 0
2715   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2716                                    APInt::getAllOnesValue(BitWidth)))
2717     return DAG.getConstant(0, VT);
2718   // reassociate and
2719   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2720   if (RAND.getNode())
2721     return RAND;
2722   // fold (and (or x, C), D) -> D if (C & D) == D
2723   if (N1C && N0.getOpcode() == ISD::OR)
2724     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2725       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2726         return N1;
2727   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2728   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2729     SDValue N0Op0 = N0.getOperand(0);
2730     APInt Mask = ~N1C->getAPIntValue();
2731     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2732     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2733       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2734                                  N0.getValueType(), N0Op0);
2735
2736       // Replace uses of the AND with uses of the Zero extend node.
2737       CombineTo(N, Zext);
2738
2739       // We actually want to replace all uses of the any_extend with the
2740       // zero_extend, to avoid duplicating things.  This will later cause this
2741       // AND to be folded.
2742       CombineTo(N0.getNode(), Zext);
2743       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2744     }
2745   }
2746   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2747   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2748   // already be zero by virtue of the width of the base type of the load.
2749   //
2750   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2751   // more cases.
2752   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2753        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2754       N0.getOpcode() == ISD::LOAD) {
2755     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2756                                          N0 : N0.getOperand(0) );
2757
2758     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2759     // This can be a pure constant or a vector splat, in which case we treat the
2760     // vector as a scalar and use the splat value.
2761     APInt Constant = APInt::getNullValue(1);
2762     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2763       Constant = C->getAPIntValue();
2764     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2765       APInt SplatValue, SplatUndef;
2766       unsigned SplatBitSize;
2767       bool HasAnyUndefs;
2768       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2769                                              SplatBitSize, HasAnyUndefs);
2770       if (IsSplat) {
2771         // Undef bits can contribute to a possible optimisation if set, so
2772         // set them.
2773         SplatValue |= SplatUndef;
2774
2775         // The splat value may be something like "0x00FFFFFF", which means 0 for
2776         // the first vector value and FF for the rest, repeating. We need a mask
2777         // that will apply equally to all members of the vector, so AND all the
2778         // lanes of the constant together.
2779         EVT VT = Vector->getValueType(0);
2780         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2781
2782         // If the splat value has been compressed to a bitlength lower
2783         // than the size of the vector lane, we need to re-expand it to
2784         // the lane size.
2785         if (BitWidth > SplatBitSize)
2786           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2787                SplatBitSize < BitWidth;
2788                SplatBitSize = SplatBitSize * 2)
2789             SplatValue |= SplatValue.shl(SplatBitSize);
2790
2791         Constant = APInt::getAllOnesValue(BitWidth);
2792         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2793           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2794       }
2795     }
2796
2797     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2798     // actually legal and isn't going to get expanded, else this is a false
2799     // optimisation.
2800     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2801                                                     Load->getMemoryVT());
2802
2803     // Resize the constant to the same size as the original memory access before
2804     // extension. If it is still the AllOnesValue then this AND is completely
2805     // unneeded.
2806     Constant =
2807       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2808
2809     bool B;
2810     switch (Load->getExtensionType()) {
2811     default: B = false; break;
2812     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2813     case ISD::ZEXTLOAD:
2814     case ISD::NON_EXTLOAD: B = true; break;
2815     }
2816
2817     if (B && Constant.isAllOnesValue()) {
2818       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2819       // preserve semantics once we get rid of the AND.
2820       SDValue NewLoad(Load, 0);
2821       if (Load->getExtensionType() == ISD::EXTLOAD) {
2822         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2823                               Load->getValueType(0), SDLoc(Load),
2824                               Load->getChain(), Load->getBasePtr(),
2825                               Load->getOffset(), Load->getMemoryVT(),
2826                               Load->getMemOperand());
2827         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2828         if (Load->getNumValues() == 3) {
2829           // PRE/POST_INC loads have 3 values.
2830           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2831                            NewLoad.getValue(2) };
2832           CombineTo(Load, To, 3, true);
2833         } else {
2834           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2835         }
2836       }
2837
2838       // Fold the AND away, taking care not to fold to the old load node if we
2839       // replaced it.
2840       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2841
2842       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2843     }
2844   }
2845   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2846   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2847     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2848     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2849
2850     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2851         LL.getValueType().isInteger()) {
2852       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2853       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2854         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2855                                      LR.getValueType(), LL, RL);
2856         AddToWorklist(ORNode.getNode());
2857         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2858       }
2859       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2860       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2861         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2862                                       LR.getValueType(), LL, RL);
2863         AddToWorklist(ANDNode.getNode());
2864         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2865       }
2866       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2867       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2868         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2869                                      LR.getValueType(), LL, RL);
2870         AddToWorklist(ORNode.getNode());
2871         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2872       }
2873     }
2874     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2875     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2876         Op0 == Op1 && LL.getValueType().isInteger() &&
2877       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2878                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2879                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2880                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2881       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2882                                     LL, DAG.getConstant(1, LL.getValueType()));
2883       AddToWorklist(ADDNode.getNode());
2884       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2885                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2886     }
2887     // canonicalize equivalent to ll == rl
2888     if (LL == RR && LR == RL) {
2889       Op1 = ISD::getSetCCSwappedOperands(Op1);
2890       std::swap(RL, RR);
2891     }
2892     if (LL == RL && LR == RR) {
2893       bool isInteger = LL.getValueType().isInteger();
2894       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2895       if (Result != ISD::SETCC_INVALID &&
2896           (!LegalOperations ||
2897            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2898             TLI.isOperationLegal(ISD::SETCC,
2899                             getSetCCResultType(N0.getSimpleValueType())))))
2900         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2901                             LL, LR, Result);
2902     }
2903   }
2904
2905   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2906   if (N0.getOpcode() == N1.getOpcode()) {
2907     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2908     if (Tmp.getNode()) return Tmp;
2909   }
2910
2911   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2912   // fold (and (sra)) -> (and (srl)) when possible.
2913   if (!VT.isVector() &&
2914       SimplifyDemandedBits(SDValue(N, 0)))
2915     return SDValue(N, 0);
2916
2917   // fold (zext_inreg (extload x)) -> (zextload x)
2918   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2919     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2920     EVT MemVT = LN0->getMemoryVT();
2921     // If we zero all the possible extended bits, then we can turn this into
2922     // a zextload if we are running before legalize or the operation is legal.
2923     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2924     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2925                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2926         ((!LegalOperations && !LN0->isVolatile()) ||
2927          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2928       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2929                                        LN0->getChain(), LN0->getBasePtr(),
2930                                        MemVT, LN0->getMemOperand());
2931       AddToWorklist(N);
2932       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2933       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2934     }
2935   }
2936   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2937   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2938       N0.hasOneUse()) {
2939     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2940     EVT MemVT = LN0->getMemoryVT();
2941     // If we zero all the possible extended bits, then we can turn this into
2942     // a zextload if we are running before legalize or the operation is legal.
2943     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2944     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2945                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2946         ((!LegalOperations && !LN0->isVolatile()) ||
2947          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2948       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2949                                        LN0->getChain(), LN0->getBasePtr(),
2950                                        MemVT, LN0->getMemOperand());
2951       AddToWorklist(N);
2952       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2953       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2954     }
2955   }
2956
2957   // fold (and (load x), 255) -> (zextload x, i8)
2958   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2959   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2960   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2961               (N0.getOpcode() == ISD::ANY_EXTEND &&
2962                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2963     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2964     LoadSDNode *LN0 = HasAnyExt
2965       ? cast<LoadSDNode>(N0.getOperand(0))
2966       : cast<LoadSDNode>(N0);
2967     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2968         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2969       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2970       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2971         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2972         EVT LoadedVT = LN0->getMemoryVT();
2973
2974         if (ExtVT == LoadedVT &&
2975             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2976           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2977
2978           SDValue NewLoad =
2979             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2980                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2981                            LN0->getMemOperand());
2982           AddToWorklist(N);
2983           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2984           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2985         }
2986
2987         // Do not change the width of a volatile load.
2988         // Do not generate loads of non-round integer types since these can
2989         // be expensive (and would be wrong if the type is not byte sized).
2990         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2991             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2992           EVT PtrType = LN0->getOperand(1).getValueType();
2993
2994           unsigned Alignment = LN0->getAlignment();
2995           SDValue NewPtr = LN0->getBasePtr();
2996
2997           // For big endian targets, we need to add an offset to the pointer
2998           // to load the correct bytes.  For little endian systems, we merely
2999           // need to read fewer bytes from the same pointer.
3000           if (TLI.isBigEndian()) {
3001             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3002             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3003             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3004             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3005                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3006             Alignment = MinAlign(Alignment, PtrOff);
3007           }
3008
3009           AddToWorklist(NewPtr.getNode());
3010
3011           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3012           SDValue Load =
3013             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3014                            LN0->getChain(), NewPtr,
3015                            LN0->getPointerInfo(),
3016                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3017                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3018           AddToWorklist(N);
3019           CombineTo(LN0, Load, Load.getValue(1));
3020           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3021         }
3022       }
3023     }
3024   }
3025
3026   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3027       VT.getSizeInBits() <= 64) {
3028     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3029       APInt ADDC = ADDI->getAPIntValue();
3030       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3031         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3032         // immediate for an add, but it is legal if its top c2 bits are set,
3033         // transform the ADD so the immediate doesn't need to be materialized
3034         // in a register.
3035         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3036           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3037                                              SRLI->getZExtValue());
3038           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3039             ADDC |= Mask;
3040             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3041               SDValue NewAdd =
3042                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3043                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3044               CombineTo(N0.getNode(), NewAdd);
3045               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3046             }
3047           }
3048         }
3049       }
3050     }
3051   }
3052
3053   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3054   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3055     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3056                                        N0.getOperand(1), false);
3057     if (BSwap.getNode())
3058       return BSwap;
3059   }
3060
3061   return SDValue();
3062 }
3063
3064 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3065 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3066                                         bool DemandHighBits) {
3067   if (!LegalOperations)
3068     return SDValue();
3069
3070   EVT VT = N->getValueType(0);
3071   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3072     return SDValue();
3073   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3074     return SDValue();
3075
3076   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3077   bool LookPassAnd0 = false;
3078   bool LookPassAnd1 = false;
3079   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3080       std::swap(N0, N1);
3081   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3082       std::swap(N0, N1);
3083   if (N0.getOpcode() == ISD::AND) {
3084     if (!N0.getNode()->hasOneUse())
3085       return SDValue();
3086     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3087     if (!N01C || N01C->getZExtValue() != 0xFF00)
3088       return SDValue();
3089     N0 = N0.getOperand(0);
3090     LookPassAnd0 = true;
3091   }
3092
3093   if (N1.getOpcode() == ISD::AND) {
3094     if (!N1.getNode()->hasOneUse())
3095       return SDValue();
3096     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3097     if (!N11C || N11C->getZExtValue() != 0xFF)
3098       return SDValue();
3099     N1 = N1.getOperand(0);
3100     LookPassAnd1 = true;
3101   }
3102
3103   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3104     std::swap(N0, N1);
3105   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3106     return SDValue();
3107   if (!N0.getNode()->hasOneUse() ||
3108       !N1.getNode()->hasOneUse())
3109     return SDValue();
3110
3111   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3112   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3113   if (!N01C || !N11C)
3114     return SDValue();
3115   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3116     return SDValue();
3117
3118   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3119   SDValue N00 = N0->getOperand(0);
3120   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3121     if (!N00.getNode()->hasOneUse())
3122       return SDValue();
3123     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3124     if (!N001C || N001C->getZExtValue() != 0xFF)
3125       return SDValue();
3126     N00 = N00.getOperand(0);
3127     LookPassAnd0 = true;
3128   }
3129
3130   SDValue N10 = N1->getOperand(0);
3131   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3132     if (!N10.getNode()->hasOneUse())
3133       return SDValue();
3134     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3135     if (!N101C || N101C->getZExtValue() != 0xFF00)
3136       return SDValue();
3137     N10 = N10.getOperand(0);
3138     LookPassAnd1 = true;
3139   }
3140
3141   if (N00 != N10)
3142     return SDValue();
3143
3144   // Make sure everything beyond the low halfword gets set to zero since the SRL
3145   // 16 will clear the top bits.
3146   unsigned OpSizeInBits = VT.getSizeInBits();
3147   if (DemandHighBits && OpSizeInBits > 16) {
3148     // If the left-shift isn't masked out then the only way this is a bswap is
3149     // if all bits beyond the low 8 are 0. In that case the entire pattern
3150     // reduces to a left shift anyway: leave it for other parts of the combiner.
3151     if (!LookPassAnd0)
3152       return SDValue();
3153
3154     // However, if the right shift isn't masked out then it might be because
3155     // it's not needed. See if we can spot that too.
3156     if (!LookPassAnd1 &&
3157         !DAG.MaskedValueIsZero(
3158             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3159       return SDValue();
3160   }
3161
3162   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3163   if (OpSizeInBits > 16)
3164     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3165                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3166   return Res;
3167 }
3168
3169 /// Return true if the specified node is an element that makes up a 32-bit
3170 /// packed halfword byteswap.
3171 /// ((x & 0x000000ff) << 8) |
3172 /// ((x & 0x0000ff00) >> 8) |
3173 /// ((x & 0x00ff0000) << 8) |
3174 /// ((x & 0xff000000) >> 8)
3175 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3176   if (!N.getNode()->hasOneUse())
3177     return false;
3178
3179   unsigned Opc = N.getOpcode();
3180   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3181     return false;
3182
3183   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3184   if (!N1C)
3185     return false;
3186
3187   unsigned Num;
3188   switch (N1C->getZExtValue()) {
3189   default:
3190     return false;
3191   case 0xFF:       Num = 0; break;
3192   case 0xFF00:     Num = 1; break;
3193   case 0xFF0000:   Num = 2; break;
3194   case 0xFF000000: Num = 3; break;
3195   }
3196
3197   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3198   SDValue N0 = N.getOperand(0);
3199   if (Opc == ISD::AND) {
3200     if (Num == 0 || Num == 2) {
3201       // (x >> 8) & 0xff
3202       // (x >> 8) & 0xff0000
3203       if (N0.getOpcode() != ISD::SRL)
3204         return false;
3205       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3206       if (!C || C->getZExtValue() != 8)
3207         return false;
3208     } else {
3209       // (x << 8) & 0xff00
3210       // (x << 8) & 0xff000000
3211       if (N0.getOpcode() != ISD::SHL)
3212         return false;
3213       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3214       if (!C || C->getZExtValue() != 8)
3215         return false;
3216     }
3217   } else if (Opc == ISD::SHL) {
3218     // (x & 0xff) << 8
3219     // (x & 0xff0000) << 8
3220     if (Num != 0 && Num != 2)
3221       return false;
3222     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3223     if (!C || C->getZExtValue() != 8)
3224       return false;
3225   } else { // Opc == ISD::SRL
3226     // (x & 0xff00) >> 8
3227     // (x & 0xff000000) >> 8
3228     if (Num != 1 && Num != 3)
3229       return false;
3230     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3231     if (!C || C->getZExtValue() != 8)
3232       return false;
3233   }
3234
3235   if (Parts[Num])
3236     return false;
3237
3238   Parts[Num] = N0.getOperand(0).getNode();
3239   return true;
3240 }
3241
3242 /// Match a 32-bit packed halfword bswap. That is
3243 /// ((x & 0x000000ff) << 8) |
3244 /// ((x & 0x0000ff00) >> 8) |
3245 /// ((x & 0x00ff0000) << 8) |
3246 /// ((x & 0xff000000) >> 8)
3247 /// => (rotl (bswap x), 16)
3248 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3249   if (!LegalOperations)
3250     return SDValue();
3251
3252   EVT VT = N->getValueType(0);
3253   if (VT != MVT::i32)
3254     return SDValue();
3255   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3256     return SDValue();
3257
3258   // Look for either
3259   // (or (or (and), (and)), (or (and), (and)))
3260   // (or (or (or (and), (and)), (and)), (and))
3261   if (N0.getOpcode() != ISD::OR)
3262     return SDValue();
3263   SDValue N00 = N0.getOperand(0);
3264   SDValue N01 = N0.getOperand(1);
3265   SDNode *Parts[4] = {};
3266
3267   if (N1.getOpcode() == ISD::OR &&
3268       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3269     // (or (or (and), (and)), (or (and), (and)))
3270     SDValue N000 = N00.getOperand(0);
3271     if (!isBSwapHWordElement(N000, Parts))
3272       return SDValue();
3273
3274     SDValue N001 = N00.getOperand(1);
3275     if (!isBSwapHWordElement(N001, Parts))
3276       return SDValue();
3277     SDValue N010 = N01.getOperand(0);
3278     if (!isBSwapHWordElement(N010, Parts))
3279       return SDValue();
3280     SDValue N011 = N01.getOperand(1);
3281     if (!isBSwapHWordElement(N011, Parts))
3282       return SDValue();
3283   } else {
3284     // (or (or (or (and), (and)), (and)), (and))
3285     if (!isBSwapHWordElement(N1, Parts))
3286       return SDValue();
3287     if (!isBSwapHWordElement(N01, Parts))
3288       return SDValue();
3289     if (N00.getOpcode() != ISD::OR)
3290       return SDValue();
3291     SDValue N000 = N00.getOperand(0);
3292     if (!isBSwapHWordElement(N000, Parts))
3293       return SDValue();
3294     SDValue N001 = N00.getOperand(1);
3295     if (!isBSwapHWordElement(N001, Parts))
3296       return SDValue();
3297   }
3298
3299   // Make sure the parts are all coming from the same node.
3300   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3301     return SDValue();
3302
3303   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3304                               SDValue(Parts[0],0));
3305
3306   // Result of the bswap should be rotated by 16. If it's not legal, then
3307   // do  (x << 16) | (x >> 16).
3308   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3309   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3310     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3311   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3312     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3313   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3314                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3315                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3316 }
3317
3318 SDValue DAGCombiner::visitOR(SDNode *N) {
3319   SDValue N0 = N->getOperand(0);
3320   SDValue N1 = N->getOperand(1);
3321   SDValue LL, LR, RL, RR, CC0, CC1;
3322   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3324   EVT VT = N1.getValueType();
3325
3326   // fold vector ops
3327   if (VT.isVector()) {
3328     SDValue FoldedVOp = SimplifyVBinOp(N);
3329     if (FoldedVOp.getNode()) return FoldedVOp;
3330
3331     // fold (or x, 0) -> x, vector edition
3332     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3333       return N1;
3334     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3335       return N0;
3336
3337     // fold (or x, -1) -> -1, vector edition
3338     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3339       // do not return N0, because undef node may exist in N0
3340       return DAG.getConstant(
3341           APInt::getAllOnesValue(
3342               N0.getValueType().getScalarType().getSizeInBits()),
3343           N0.getValueType());
3344     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3345       // do not return N1, because undef node may exist in N1
3346       return DAG.getConstant(
3347           APInt::getAllOnesValue(
3348               N1.getValueType().getScalarType().getSizeInBits()),
3349           N1.getValueType());
3350
3351     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3352     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3353     // Do this only if the resulting shuffle is legal.
3354     if (isa<ShuffleVectorSDNode>(N0) &&
3355         isa<ShuffleVectorSDNode>(N1) &&
3356         // Avoid folding a node with illegal type.
3357         TLI.isTypeLegal(VT) &&
3358         N0->getOperand(1) == N1->getOperand(1) &&
3359         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3360       bool CanFold = true;
3361       unsigned NumElts = VT.getVectorNumElements();
3362       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3363       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3364       // We construct two shuffle masks:
3365       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3366       // and N1 as the second operand.
3367       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3368       // and N0 as the second operand.
3369       // We do this because OR is commutable and therefore there might be
3370       // two ways to fold this node into a shuffle.
3371       SmallVector<int,4> Mask1;
3372       SmallVector<int,4> Mask2;
3373
3374       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3375         int M0 = SV0->getMaskElt(i);
3376         int M1 = SV1->getMaskElt(i);
3377
3378         // Both shuffle indexes are undef. Propagate Undef.
3379         if (M0 < 0 && M1 < 0) {
3380           Mask1.push_back(M0);
3381           Mask2.push_back(M0);
3382           continue;
3383         }
3384
3385         if (M0 < 0 || M1 < 0 ||
3386             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3387             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3388           CanFold = false;
3389           break;
3390         }
3391
3392         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3393         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3394       }
3395
3396       if (CanFold) {
3397         // Fold this sequence only if the resulting shuffle is 'legal'.
3398         if (TLI.isShuffleMaskLegal(Mask1, VT))
3399           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3400                                       N1->getOperand(0), &Mask1[0]);
3401         if (TLI.isShuffleMaskLegal(Mask2, VT))
3402           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3403                                       N0->getOperand(0), &Mask2[0]);
3404       }
3405     }
3406   }
3407
3408   // fold (or x, undef) -> -1
3409   if (!LegalOperations &&
3410       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3411     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3412     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3413   }
3414   // fold (or c1, c2) -> c1|c2
3415   if (N0C && N1C)
3416     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3417   // canonicalize constant to RHS
3418   if (N0C && !N1C)
3419     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3420   // fold (or x, 0) -> x
3421   if (N1C && N1C->isNullValue())
3422     return N0;
3423   // fold (or x, -1) -> -1
3424   if (N1C && N1C->isAllOnesValue())
3425     return N1;
3426   // fold (or x, c) -> c iff (x & ~c) == 0
3427   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3428     return N1;
3429
3430   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3431   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3432   if (BSwap.getNode())
3433     return BSwap;
3434   BSwap = MatchBSwapHWordLow(N, N0, N1);
3435   if (BSwap.getNode())
3436     return BSwap;
3437
3438   // reassociate or
3439   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3440   if (ROR.getNode())
3441     return ROR;
3442   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3443   // iff (c1 & c2) == 0.
3444   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3445              isa<ConstantSDNode>(N0.getOperand(1))) {
3446     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3447     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3448       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3449       if (!COR.getNode())
3450         return SDValue();
3451       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3452                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3453                                      N0.getOperand(0), N1), COR);
3454     }
3455   }
3456   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3457   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3458     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3459     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3460
3461     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3462         LL.getValueType().isInteger()) {
3463       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3464       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3465       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3466           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3467         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3468                                      LR.getValueType(), LL, RL);
3469         AddToWorklist(ORNode.getNode());
3470         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3471       }
3472       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3473       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3474       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3475           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3476         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3477                                       LR.getValueType(), LL, RL);
3478         AddToWorklist(ANDNode.getNode());
3479         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3480       }
3481     }
3482     // canonicalize equivalent to ll == rl
3483     if (LL == RR && LR == RL) {
3484       Op1 = ISD::getSetCCSwappedOperands(Op1);
3485       std::swap(RL, RR);
3486     }
3487     if (LL == RL && LR == RR) {
3488       bool isInteger = LL.getValueType().isInteger();
3489       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3490       if (Result != ISD::SETCC_INVALID &&
3491           (!LegalOperations ||
3492            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3493             TLI.isOperationLegal(ISD::SETCC,
3494               getSetCCResultType(N0.getValueType())))))
3495         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3496                             LL, LR, Result);
3497     }
3498   }
3499
3500   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3501   if (N0.getOpcode() == N1.getOpcode()) {
3502     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3503     if (Tmp.getNode()) return Tmp;
3504   }
3505
3506   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3507   if (N0.getOpcode() == ISD::AND &&
3508       N1.getOpcode() == ISD::AND &&
3509       N0.getOperand(1).getOpcode() == ISD::Constant &&
3510       N1.getOperand(1).getOpcode() == ISD::Constant &&
3511       // Don't increase # computations.
3512       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3513     // We can only do this xform if we know that bits from X that are set in C2
3514     // but not in C1 are already zero.  Likewise for Y.
3515     const APInt &LHSMask =
3516       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3517     const APInt &RHSMask =
3518       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3519
3520     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3521         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3522       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3523                               N0.getOperand(0), N1.getOperand(0));
3524       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3525                          DAG.getConstant(LHSMask | RHSMask, VT));
3526     }
3527   }
3528
3529   // See if this is some rotate idiom.
3530   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3531     return SDValue(Rot, 0);
3532
3533   // Simplify the operands using demanded-bits information.
3534   if (!VT.isVector() &&
3535       SimplifyDemandedBits(SDValue(N, 0)))
3536     return SDValue(N, 0);
3537
3538   return SDValue();
3539 }
3540
3541 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3542 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3543   if (Op.getOpcode() == ISD::AND) {
3544     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3545       Mask = Op.getOperand(1);
3546       Op = Op.getOperand(0);
3547     } else {
3548       return false;
3549     }
3550   }
3551
3552   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3553     Shift = Op;
3554     return true;
3555   }
3556
3557   return false;
3558 }
3559
3560 // Return true if we can prove that, whenever Neg and Pos are both in the
3561 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3562 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3563 //
3564 //     (or (shift1 X, Neg), (shift2 X, Pos))
3565 //
3566 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3567 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3568 // to consider shift amounts with defined behavior.
3569 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3570   // If OpSize is a power of 2 then:
3571   //
3572   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3573   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3574   //
3575   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3576   // for the stronger condition:
3577   //
3578   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3579   //
3580   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3581   // we can just replace Neg with Neg' for the rest of the function.
3582   //
3583   // In other cases we check for the even stronger condition:
3584   //
3585   //     Neg == OpSize - Pos                                    [B]
3586   //
3587   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3588   // behavior if Pos == 0 (and consequently Neg == OpSize).
3589   //
3590   // We could actually use [A] whenever OpSize is a power of 2, but the
3591   // only extra cases that it would match are those uninteresting ones
3592   // where Neg and Pos are never in range at the same time.  E.g. for
3593   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3594   // as well as (sub 32, Pos), but:
3595   //
3596   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3597   //
3598   // always invokes undefined behavior for 32-bit X.
3599   //
3600   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3601   unsigned MaskLoBits = 0;
3602   if (Neg.getOpcode() == ISD::AND &&
3603       isPowerOf2_64(OpSize) &&
3604       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3605       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3606     Neg = Neg.getOperand(0);
3607     MaskLoBits = Log2_64(OpSize);
3608   }
3609
3610   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3611   if (Neg.getOpcode() != ISD::SUB)
3612     return 0;
3613   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3614   if (!NegC)
3615     return 0;
3616   SDValue NegOp1 = Neg.getOperand(1);
3617
3618   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3619   // Pos'.  The truncation is redundant for the purpose of the equality.
3620   if (MaskLoBits &&
3621       Pos.getOpcode() == ISD::AND &&
3622       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3623       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3624     Pos = Pos.getOperand(0);
3625
3626   // The condition we need is now:
3627   //
3628   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3629   //
3630   // If NegOp1 == Pos then we need:
3631   //
3632   //              OpSize & Mask == NegC & Mask
3633   //
3634   // (because "x & Mask" is a truncation and distributes through subtraction).
3635   APInt Width;
3636   if (Pos == NegOp1)
3637     Width = NegC->getAPIntValue();
3638   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3639   // Then the condition we want to prove becomes:
3640   //
3641   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3642   //
3643   // which, again because "x & Mask" is a truncation, becomes:
3644   //
3645   //                NegC & Mask == (OpSize - PosC) & Mask
3646   //              OpSize & Mask == (NegC + PosC) & Mask
3647   else if (Pos.getOpcode() == ISD::ADD &&
3648            Pos.getOperand(0) == NegOp1 &&
3649            Pos.getOperand(1).getOpcode() == ISD::Constant)
3650     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3651              NegC->getAPIntValue());
3652   else
3653     return false;
3654
3655   // Now we just need to check that OpSize & Mask == Width & Mask.
3656   if (MaskLoBits)
3657     // Opsize & Mask is 0 since Mask is Opsize - 1.
3658     return Width.getLoBits(MaskLoBits) == 0;
3659   return Width == OpSize;
3660 }
3661
3662 // A subroutine of MatchRotate used once we have found an OR of two opposite
3663 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3664 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3665 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3666 // Neg with outer conversions stripped away.
3667 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3668                                        SDValue Neg, SDValue InnerPos,
3669                                        SDValue InnerNeg, unsigned PosOpcode,
3670                                        unsigned NegOpcode, SDLoc DL) {
3671   // fold (or (shl x, (*ext y)),
3672   //          (srl x, (*ext (sub 32, y)))) ->
3673   //   (rotl x, y) or (rotr x, (sub 32, y))
3674   //
3675   // fold (or (shl x, (*ext (sub 32, y))),
3676   //          (srl x, (*ext y))) ->
3677   //   (rotr x, y) or (rotl x, (sub 32, y))
3678   EVT VT = Shifted.getValueType();
3679   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3680     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3681     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3682                        HasPos ? Pos : Neg).getNode();
3683   }
3684
3685   return nullptr;
3686 }
3687
3688 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3689 // idioms for rotate, and if the target supports rotation instructions, generate
3690 // a rot[lr].
3691 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3692   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3693   EVT VT = LHS.getValueType();
3694   if (!TLI.isTypeLegal(VT)) return nullptr;
3695
3696   // The target must have at least one rotate flavor.
3697   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3698   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3699   if (!HasROTL && !HasROTR) return nullptr;
3700
3701   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3702   SDValue LHSShift;   // The shift.
3703   SDValue LHSMask;    // AND value if any.
3704   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3705     return nullptr; // Not part of a rotate.
3706
3707   SDValue RHSShift;   // The shift.
3708   SDValue RHSMask;    // AND value if any.
3709   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3710     return nullptr; // Not part of a rotate.
3711
3712   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3713     return nullptr;   // Not shifting the same value.
3714
3715   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3716     return nullptr;   // Shifts must disagree.
3717
3718   // Canonicalize shl to left side in a shl/srl pair.
3719   if (RHSShift.getOpcode() == ISD::SHL) {
3720     std::swap(LHS, RHS);
3721     std::swap(LHSShift, RHSShift);
3722     std::swap(LHSMask , RHSMask );
3723   }
3724
3725   unsigned OpSizeInBits = VT.getSizeInBits();
3726   SDValue LHSShiftArg = LHSShift.getOperand(0);
3727   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3728   SDValue RHSShiftArg = RHSShift.getOperand(0);
3729   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3730
3731   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3732   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3733   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3734       RHSShiftAmt.getOpcode() == ISD::Constant) {
3735     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3736     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3737     if ((LShVal + RShVal) != OpSizeInBits)
3738       return nullptr;
3739
3740     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3741                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3742
3743     // If there is an AND of either shifted operand, apply it to the result.
3744     if (LHSMask.getNode() || RHSMask.getNode()) {
3745       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3746
3747       if (LHSMask.getNode()) {
3748         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3749         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3750       }
3751       if (RHSMask.getNode()) {
3752         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3753         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3754       }
3755
3756       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3757     }
3758
3759     return Rot.getNode();
3760   }
3761
3762   // If there is a mask here, and we have a variable shift, we can't be sure
3763   // that we're masking out the right stuff.
3764   if (LHSMask.getNode() || RHSMask.getNode())
3765     return nullptr;
3766
3767   // If the shift amount is sign/zext/any-extended just peel it off.
3768   SDValue LExtOp0 = LHSShiftAmt;
3769   SDValue RExtOp0 = RHSShiftAmt;
3770   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3771        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3772        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3773        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3774       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3775        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3776        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3777        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3778     LExtOp0 = LHSShiftAmt.getOperand(0);
3779     RExtOp0 = RHSShiftAmt.getOperand(0);
3780   }
3781
3782   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3783                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3784   if (TryL)
3785     return TryL;
3786
3787   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3788                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3789   if (TryR)
3790     return TryR;
3791
3792   return nullptr;
3793 }
3794
3795 SDValue DAGCombiner::visitXOR(SDNode *N) {
3796   SDValue N0 = N->getOperand(0);
3797   SDValue N1 = N->getOperand(1);
3798   SDValue LHS, RHS, CC;
3799   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3800   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3801   EVT VT = N0.getValueType();
3802
3803   // fold vector ops
3804   if (VT.isVector()) {
3805     SDValue FoldedVOp = SimplifyVBinOp(N);
3806     if (FoldedVOp.getNode()) return FoldedVOp;
3807
3808     // fold (xor x, 0) -> x, vector edition
3809     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3810       return N1;
3811     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3812       return N0;
3813   }
3814
3815   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3816   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3817     return DAG.getConstant(0, VT);
3818   // fold (xor x, undef) -> undef
3819   if (N0.getOpcode() == ISD::UNDEF)
3820     return N0;
3821   if (N1.getOpcode() == ISD::UNDEF)
3822     return N1;
3823   // fold (xor c1, c2) -> c1^c2
3824   if (N0C && N1C)
3825     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3826   // canonicalize constant to RHS
3827   if (N0C && !N1C)
3828     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3829   // fold (xor x, 0) -> x
3830   if (N1C && N1C->isNullValue())
3831     return N0;
3832   // reassociate xor
3833   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3834   if (RXOR.getNode())
3835     return RXOR;
3836
3837   // fold !(x cc y) -> (x !cc y)
3838   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3839     bool isInt = LHS.getValueType().isInteger();
3840     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3841                                                isInt);
3842
3843     if (!LegalOperations ||
3844         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3845       switch (N0.getOpcode()) {
3846       default:
3847         llvm_unreachable("Unhandled SetCC Equivalent!");
3848       case ISD::SETCC:
3849         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3850       case ISD::SELECT_CC:
3851         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3852                                N0.getOperand(3), NotCC);
3853       }
3854     }
3855   }
3856
3857   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3858   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3859       N0.getNode()->hasOneUse() &&
3860       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3861     SDValue V = N0.getOperand(0);
3862     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3863                     DAG.getConstant(1, V.getValueType()));
3864     AddToWorklist(V.getNode());
3865     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3866   }
3867
3868   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3869   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3870       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3871     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3872     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3873       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3874       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3875       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3876       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3877       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3878     }
3879   }
3880   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3881   if (N1C && N1C->isAllOnesValue() &&
3882       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3883     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3884     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3885       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3886       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3887       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3888       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3889       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3890     }
3891   }
3892   // fold (xor (and x, y), y) -> (and (not x), y)
3893   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3894       N0->getOperand(1) == N1) {
3895     SDValue X = N0->getOperand(0);
3896     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3897     AddToWorklist(NotX.getNode());
3898     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3899   }
3900   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3901   if (N1C && N0.getOpcode() == ISD::XOR) {
3902     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3903     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3904     if (N00C)
3905       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3906                          DAG.getConstant(N1C->getAPIntValue() ^
3907                                          N00C->getAPIntValue(), VT));
3908     if (N01C)
3909       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3910                          DAG.getConstant(N1C->getAPIntValue() ^
3911                                          N01C->getAPIntValue(), VT));
3912   }
3913   // fold (xor x, x) -> 0
3914   if (N0 == N1)
3915     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3916
3917   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3918   if (N0.getOpcode() == N1.getOpcode()) {
3919     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3920     if (Tmp.getNode()) return Tmp;
3921   }
3922
3923   // Simplify the expression using non-local knowledge.
3924   if (!VT.isVector() &&
3925       SimplifyDemandedBits(SDValue(N, 0)))
3926     return SDValue(N, 0);
3927
3928   return SDValue();
3929 }
3930
3931 /// Handle transforms common to the three shifts, when the shift amount is a
3932 /// constant.
3933 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3934   // We can't and shouldn't fold opaque constants.
3935   if (Amt->isOpaque())
3936     return SDValue();
3937
3938   SDNode *LHS = N->getOperand(0).getNode();
3939   if (!LHS->hasOneUse()) return SDValue();
3940
3941   // We want to pull some binops through shifts, so that we have (and (shift))
3942   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3943   // thing happens with address calculations, so it's important to canonicalize
3944   // it.
3945   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3946
3947   switch (LHS->getOpcode()) {
3948   default: return SDValue();
3949   case ISD::OR:
3950   case ISD::XOR:
3951     HighBitSet = false; // We can only transform sra if the high bit is clear.
3952     break;
3953   case ISD::AND:
3954     HighBitSet = true;  // We can only transform sra if the high bit is set.
3955     break;
3956   case ISD::ADD:
3957     if (N->getOpcode() != ISD::SHL)
3958       return SDValue(); // only shl(add) not sr[al](add).
3959     HighBitSet = false; // We can only transform sra if the high bit is clear.
3960     break;
3961   }
3962
3963   // We require the RHS of the binop to be a constant and not opaque as well.
3964   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3965   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3966
3967   // FIXME: disable this unless the input to the binop is a shift by a constant.
3968   // If it is not a shift, it pessimizes some common cases like:
3969   //
3970   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3971   //    int bar(int *X, int i) { return X[i & 255]; }
3972   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3973   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3974        BinOpLHSVal->getOpcode() != ISD::SRA &&
3975        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3976       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3977     return SDValue();
3978
3979   EVT VT = N->getValueType(0);
3980
3981   // If this is a signed shift right, and the high bit is modified by the
3982   // logical operation, do not perform the transformation. The highBitSet
3983   // boolean indicates the value of the high bit of the constant which would
3984   // cause it to be modified for this operation.
3985   if (N->getOpcode() == ISD::SRA) {
3986     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3987     if (BinOpRHSSignSet != HighBitSet)
3988       return SDValue();
3989   }
3990
3991   if (!TLI.isDesirableToCommuteWithShift(LHS))
3992     return SDValue();
3993
3994   // Fold the constants, shifting the binop RHS by the shift amount.
3995   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3996                                N->getValueType(0),
3997                                LHS->getOperand(1), N->getOperand(1));
3998   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3999
4000   // Create the new shift.
4001   SDValue NewShift = DAG.getNode(N->getOpcode(),
4002                                  SDLoc(LHS->getOperand(0)),
4003                                  VT, LHS->getOperand(0), N->getOperand(1));
4004
4005   // Create the new binop.
4006   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4007 }
4008
4009 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4010   assert(N->getOpcode() == ISD::TRUNCATE);
4011   assert(N->getOperand(0).getOpcode() == ISD::AND);
4012
4013   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4014   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4015     SDValue N01 = N->getOperand(0).getOperand(1);
4016
4017     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4018       EVT TruncVT = N->getValueType(0);
4019       SDValue N00 = N->getOperand(0).getOperand(0);
4020       APInt TruncC = N01C->getAPIntValue();
4021       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4022
4023       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4024                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4025                          DAG.getConstant(TruncC, TruncVT));
4026     }
4027   }
4028
4029   return SDValue();
4030 }
4031
4032 SDValue DAGCombiner::visitRotate(SDNode *N) {
4033   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4034   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4035       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4036     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4037     if (NewOp1.getNode())
4038       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4039                          N->getOperand(0), NewOp1);
4040   }
4041   return SDValue();
4042 }
4043
4044 SDValue DAGCombiner::visitSHL(SDNode *N) {
4045   SDValue N0 = N->getOperand(0);
4046   SDValue N1 = N->getOperand(1);
4047   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4048   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4049   EVT VT = N0.getValueType();
4050   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4051
4052   // fold vector ops
4053   if (VT.isVector()) {
4054     SDValue FoldedVOp = SimplifyVBinOp(N);
4055     if (FoldedVOp.getNode()) return FoldedVOp;
4056
4057     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4058     // If setcc produces all-one true value then:
4059     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4060     if (N1CV && N1CV->isConstant()) {
4061       if (N0.getOpcode() == ISD::AND) {
4062         SDValue N00 = N0->getOperand(0);
4063         SDValue N01 = N0->getOperand(1);
4064         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4065
4066         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4067             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4068                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4069           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4070           if (C.getNode())
4071             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4072         }
4073       } else {
4074         N1C = isConstOrConstSplat(N1);
4075       }
4076     }
4077   }
4078
4079   // fold (shl c1, c2) -> c1<<c2
4080   if (N0C && N1C)
4081     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4082   // fold (shl 0, x) -> 0
4083   if (N0C && N0C->isNullValue())
4084     return N0;
4085   // fold (shl x, c >= size(x)) -> undef
4086   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4087     return DAG.getUNDEF(VT);
4088   // fold (shl x, 0) -> x
4089   if (N1C && N1C->isNullValue())
4090     return N0;
4091   // fold (shl undef, x) -> 0
4092   if (N0.getOpcode() == ISD::UNDEF)
4093     return DAG.getConstant(0, VT);
4094   // if (shl x, c) is known to be zero, return 0
4095   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4096                             APInt::getAllOnesValue(OpSizeInBits)))
4097     return DAG.getConstant(0, VT);
4098   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4099   if (N1.getOpcode() == ISD::TRUNCATE &&
4100       N1.getOperand(0).getOpcode() == ISD::AND) {
4101     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4102     if (NewOp1.getNode())
4103       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4104   }
4105
4106   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4107     return SDValue(N, 0);
4108
4109   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4110   if (N1C && N0.getOpcode() == ISD::SHL) {
4111     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4112       uint64_t c1 = N0C1->getZExtValue();
4113       uint64_t c2 = N1C->getZExtValue();
4114       if (c1 + c2 >= OpSizeInBits)
4115         return DAG.getConstant(0, VT);
4116       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4117                          DAG.getConstant(c1 + c2, N1.getValueType()));
4118     }
4119   }
4120
4121   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4122   // For this to be valid, the second form must not preserve any of the bits
4123   // that are shifted out by the inner shift in the first form.  This means
4124   // the outer shift size must be >= the number of bits added by the ext.
4125   // As a corollary, we don't care what kind of ext it is.
4126   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4127               N0.getOpcode() == ISD::ANY_EXTEND ||
4128               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4129       N0.getOperand(0).getOpcode() == ISD::SHL) {
4130     SDValue N0Op0 = N0.getOperand(0);
4131     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4132       uint64_t c1 = N0Op0C1->getZExtValue();
4133       uint64_t c2 = N1C->getZExtValue();
4134       EVT InnerShiftVT = N0Op0.getValueType();
4135       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4136       if (c2 >= OpSizeInBits - InnerShiftSize) {
4137         if (c1 + c2 >= OpSizeInBits)
4138           return DAG.getConstant(0, VT);
4139         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4140                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4141                                        N0Op0->getOperand(0)),
4142                            DAG.getConstant(c1 + c2, N1.getValueType()));
4143       }
4144     }
4145   }
4146
4147   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4148   // Only fold this if the inner zext has no other uses to avoid increasing
4149   // the total number of instructions.
4150   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4151       N0.getOperand(0).getOpcode() == ISD::SRL) {
4152     SDValue N0Op0 = N0.getOperand(0);
4153     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4154       uint64_t c1 = N0Op0C1->getZExtValue();
4155       if (c1 < VT.getScalarSizeInBits()) {
4156         uint64_t c2 = N1C->getZExtValue();
4157         if (c1 == c2) {
4158           SDValue NewOp0 = N0.getOperand(0);
4159           EVT CountVT = NewOp0.getOperand(1).getValueType();
4160           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4161                                        NewOp0, DAG.getConstant(c2, CountVT));
4162           AddToWorklist(NewSHL.getNode());
4163           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4164         }
4165       }
4166     }
4167   }
4168
4169   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4170   //                               (and (srl x, (sub c1, c2), MASK)
4171   // Only fold this if the inner shift has no other uses -- if it does, folding
4172   // this will increase the total number of instructions.
4173   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4174     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4175       uint64_t c1 = N0C1->getZExtValue();
4176       if (c1 < OpSizeInBits) {
4177         uint64_t c2 = N1C->getZExtValue();
4178         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4179         SDValue Shift;
4180         if (c2 > c1) {
4181           Mask = Mask.shl(c2 - c1);
4182           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4183                               DAG.getConstant(c2 - c1, N1.getValueType()));
4184         } else {
4185           Mask = Mask.lshr(c1 - c2);
4186           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4187                               DAG.getConstant(c1 - c2, N1.getValueType()));
4188         }
4189         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4190                            DAG.getConstant(Mask, VT));
4191       }
4192     }
4193   }
4194   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4195   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4196     unsigned BitSize = VT.getScalarSizeInBits();
4197     SDValue HiBitsMask =
4198       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4199                                             BitSize - N1C->getZExtValue()), VT);
4200     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4201                        HiBitsMask);
4202   }
4203
4204   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4205   // Variant of version done on multiply, except mul by a power of 2 is turned
4206   // into a shift.
4207   APInt Val;
4208   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4209       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4210        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4211     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4212     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4213     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4214   }
4215
4216   if (N1C) {
4217     SDValue NewSHL = visitShiftByConstant(N, N1C);
4218     if (NewSHL.getNode())
4219       return NewSHL;
4220   }
4221
4222   return SDValue();
4223 }
4224
4225 SDValue DAGCombiner::visitSRA(SDNode *N) {
4226   SDValue N0 = N->getOperand(0);
4227   SDValue N1 = N->getOperand(1);
4228   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4229   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4230   EVT VT = N0.getValueType();
4231   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4232
4233   // fold vector ops
4234   if (VT.isVector()) {
4235     SDValue FoldedVOp = SimplifyVBinOp(N);
4236     if (FoldedVOp.getNode()) return FoldedVOp;
4237
4238     N1C = isConstOrConstSplat(N1);
4239   }
4240
4241   // fold (sra c1, c2) -> (sra c1, c2)
4242   if (N0C && N1C)
4243     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4244   // fold (sra 0, x) -> 0
4245   if (N0C && N0C->isNullValue())
4246     return N0;
4247   // fold (sra -1, x) -> -1
4248   if (N0C && N0C->isAllOnesValue())
4249     return N0;
4250   // fold (sra x, (setge c, size(x))) -> undef
4251   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4252     return DAG.getUNDEF(VT);
4253   // fold (sra x, 0) -> x
4254   if (N1C && N1C->isNullValue())
4255     return N0;
4256   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4257   // sext_inreg.
4258   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4259     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4260     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4261     if (VT.isVector())
4262       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4263                                ExtVT, VT.getVectorNumElements());
4264     if ((!LegalOperations ||
4265          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4266       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4267                          N0.getOperand(0), DAG.getValueType(ExtVT));
4268   }
4269
4270   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4271   if (N1C && N0.getOpcode() == ISD::SRA) {
4272     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4273       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4274       if (Sum >= OpSizeInBits)
4275         Sum = OpSizeInBits - 1;
4276       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4277                          DAG.getConstant(Sum, N1.getValueType()));
4278     }
4279   }
4280
4281   // fold (sra (shl X, m), (sub result_size, n))
4282   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4283   // result_size - n != m.
4284   // If truncate is free for the target sext(shl) is likely to result in better
4285   // code.
4286   if (N0.getOpcode() == ISD::SHL && N1C) {
4287     // Get the two constanst of the shifts, CN0 = m, CN = n.
4288     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4289     if (N01C) {
4290       LLVMContext &Ctx = *DAG.getContext();
4291       // Determine what the truncate's result bitsize and type would be.
4292       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4293
4294       if (VT.isVector())
4295         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4296
4297       // Determine the residual right-shift amount.
4298       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4299
4300       // If the shift is not a no-op (in which case this should be just a sign
4301       // extend already), the truncated to type is legal, sign_extend is legal
4302       // on that type, and the truncate to that type is both legal and free,
4303       // perform the transform.
4304       if ((ShiftAmt > 0) &&
4305           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4306           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4307           TLI.isTruncateFree(VT, TruncVT)) {
4308
4309           SDValue Amt = DAG.getConstant(ShiftAmt,
4310               getShiftAmountTy(N0.getOperand(0).getValueType()));
4311           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4312                                       N0.getOperand(0), Amt);
4313           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4314                                       Shift);
4315           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4316                              N->getValueType(0), Trunc);
4317       }
4318     }
4319   }
4320
4321   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4322   if (N1.getOpcode() == ISD::TRUNCATE &&
4323       N1.getOperand(0).getOpcode() == ISD::AND) {
4324     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4325     if (NewOp1.getNode())
4326       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4327   }
4328
4329   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4330   //      if c1 is equal to the number of bits the trunc removes
4331   if (N0.getOpcode() == ISD::TRUNCATE &&
4332       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4333        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4334       N0.getOperand(0).hasOneUse() &&
4335       N0.getOperand(0).getOperand(1).hasOneUse() &&
4336       N1C) {
4337     SDValue N0Op0 = N0.getOperand(0);
4338     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4339       unsigned LargeShiftVal = LargeShift->getZExtValue();
4340       EVT LargeVT = N0Op0.getValueType();
4341
4342       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4343         SDValue Amt =
4344           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4345                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4346         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4347                                   N0Op0.getOperand(0), Amt);
4348         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4349       }
4350     }
4351   }
4352
4353   // Simplify, based on bits shifted out of the LHS.
4354   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4355     return SDValue(N, 0);
4356
4357
4358   // If the sign bit is known to be zero, switch this to a SRL.
4359   if (DAG.SignBitIsZero(N0))
4360     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4361
4362   if (N1C) {
4363     SDValue NewSRA = visitShiftByConstant(N, N1C);
4364     if (NewSRA.getNode())
4365       return NewSRA;
4366   }
4367
4368   return SDValue();
4369 }
4370
4371 SDValue DAGCombiner::visitSRL(SDNode *N) {
4372   SDValue N0 = N->getOperand(0);
4373   SDValue N1 = N->getOperand(1);
4374   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4375   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4376   EVT VT = N0.getValueType();
4377   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4378
4379   // fold vector ops
4380   if (VT.isVector()) {
4381     SDValue FoldedVOp = SimplifyVBinOp(N);
4382     if (FoldedVOp.getNode()) return FoldedVOp;
4383
4384     N1C = isConstOrConstSplat(N1);
4385   }
4386
4387   // fold (srl c1, c2) -> c1 >>u c2
4388   if (N0C && N1C)
4389     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4390   // fold (srl 0, x) -> 0
4391   if (N0C && N0C->isNullValue())
4392     return N0;
4393   // fold (srl x, c >= size(x)) -> undef
4394   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4395     return DAG.getUNDEF(VT);
4396   // fold (srl x, 0) -> x
4397   if (N1C && N1C->isNullValue())
4398     return N0;
4399   // if (srl x, c) is known to be zero, return 0
4400   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4401                                    APInt::getAllOnesValue(OpSizeInBits)))
4402     return DAG.getConstant(0, VT);
4403
4404   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4405   if (N1C && N0.getOpcode() == ISD::SRL) {
4406     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4407       uint64_t c1 = N01C->getZExtValue();
4408       uint64_t c2 = N1C->getZExtValue();
4409       if (c1 + c2 >= OpSizeInBits)
4410         return DAG.getConstant(0, VT);
4411       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4412                          DAG.getConstant(c1 + c2, N1.getValueType()));
4413     }
4414   }
4415
4416   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4417   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4418       N0.getOperand(0).getOpcode() == ISD::SRL &&
4419       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4420     uint64_t c1 =
4421       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4422     uint64_t c2 = N1C->getZExtValue();
4423     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4424     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4425     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4426     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4427     if (c1 + OpSizeInBits == InnerShiftSize) {
4428       if (c1 + c2 >= InnerShiftSize)
4429         return DAG.getConstant(0, VT);
4430       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4431                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4432                                      N0.getOperand(0)->getOperand(0),
4433                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4434     }
4435   }
4436
4437   // fold (srl (shl x, c), c) -> (and x, cst2)
4438   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4439     unsigned BitSize = N0.getScalarValueSizeInBits();
4440     if (BitSize <= 64) {
4441       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4442       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4443                          DAG.getConstant(~0ULL >> ShAmt, VT));
4444     }
4445   }
4446
4447   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4448   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4449     // Shifting in all undef bits?
4450     EVT SmallVT = N0.getOperand(0).getValueType();
4451     unsigned BitSize = SmallVT.getScalarSizeInBits();
4452     if (N1C->getZExtValue() >= BitSize)
4453       return DAG.getUNDEF(VT);
4454
4455     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4456       uint64_t ShiftAmt = N1C->getZExtValue();
4457       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4458                                        N0.getOperand(0),
4459                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4460       AddToWorklist(SmallShift.getNode());
4461       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4462       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4463                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4464                          DAG.getConstant(Mask, VT));
4465     }
4466   }
4467
4468   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4469   // bit, which is unmodified by sra.
4470   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4471     if (N0.getOpcode() == ISD::SRA)
4472       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4473   }
4474
4475   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4476   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4477       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4478     APInt KnownZero, KnownOne;
4479     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4480
4481     // If any of the input bits are KnownOne, then the input couldn't be all
4482     // zeros, thus the result of the srl will always be zero.
4483     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4484
4485     // If all of the bits input the to ctlz node are known to be zero, then
4486     // the result of the ctlz is "32" and the result of the shift is one.
4487     APInt UnknownBits = ~KnownZero;
4488     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4489
4490     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4491     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4492       // Okay, we know that only that the single bit specified by UnknownBits
4493       // could be set on input to the CTLZ node. If this bit is set, the SRL
4494       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4495       // to an SRL/XOR pair, which is likely to simplify more.
4496       unsigned ShAmt = UnknownBits.countTrailingZeros();
4497       SDValue Op = N0.getOperand(0);
4498
4499       if (ShAmt) {
4500         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4501                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4502         AddToWorklist(Op.getNode());
4503       }
4504
4505       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4506                          Op, DAG.getConstant(1, VT));
4507     }
4508   }
4509
4510   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4511   if (N1.getOpcode() == ISD::TRUNCATE &&
4512       N1.getOperand(0).getOpcode() == ISD::AND) {
4513     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4514     if (NewOp1.getNode())
4515       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4516   }
4517
4518   // fold operands of srl based on knowledge that the low bits are not
4519   // demanded.
4520   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4521     return SDValue(N, 0);
4522
4523   if (N1C) {
4524     SDValue NewSRL = visitShiftByConstant(N, N1C);
4525     if (NewSRL.getNode())
4526       return NewSRL;
4527   }
4528
4529   // Attempt to convert a srl of a load into a narrower zero-extending load.
4530   SDValue NarrowLoad = ReduceLoadWidth(N);
4531   if (NarrowLoad.getNode())
4532     return NarrowLoad;
4533
4534   // Here is a common situation. We want to optimize:
4535   //
4536   //   %a = ...
4537   //   %b = and i32 %a, 2
4538   //   %c = srl i32 %b, 1
4539   //   brcond i32 %c ...
4540   //
4541   // into
4542   //
4543   //   %a = ...
4544   //   %b = and %a, 2
4545   //   %c = setcc eq %b, 0
4546   //   brcond %c ...
4547   //
4548   // However when after the source operand of SRL is optimized into AND, the SRL
4549   // itself may not be optimized further. Look for it and add the BRCOND into
4550   // the worklist.
4551   if (N->hasOneUse()) {
4552     SDNode *Use = *N->use_begin();
4553     if (Use->getOpcode() == ISD::BRCOND)
4554       AddToWorklist(Use);
4555     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4556       // Also look pass the truncate.
4557       Use = *Use->use_begin();
4558       if (Use->getOpcode() == ISD::BRCOND)
4559         AddToWorklist(Use);
4560     }
4561   }
4562
4563   return SDValue();
4564 }
4565
4566 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4567   SDValue N0 = N->getOperand(0);
4568   EVT VT = N->getValueType(0);
4569
4570   // fold (ctlz c1) -> c2
4571   if (isa<ConstantSDNode>(N0))
4572     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4573   return SDValue();
4574 }
4575
4576 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4577   SDValue N0 = N->getOperand(0);
4578   EVT VT = N->getValueType(0);
4579
4580   // fold (ctlz_zero_undef c1) -> c2
4581   if (isa<ConstantSDNode>(N0))
4582     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4583   return SDValue();
4584 }
4585
4586 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4587   SDValue N0 = N->getOperand(0);
4588   EVT VT = N->getValueType(0);
4589
4590   // fold (cttz c1) -> c2
4591   if (isa<ConstantSDNode>(N0))
4592     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4593   return SDValue();
4594 }
4595
4596 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4597   SDValue N0 = N->getOperand(0);
4598   EVT VT = N->getValueType(0);
4599
4600   // fold (cttz_zero_undef c1) -> c2
4601   if (isa<ConstantSDNode>(N0))
4602     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4603   return SDValue();
4604 }
4605
4606 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4607   SDValue N0 = N->getOperand(0);
4608   EVT VT = N->getValueType(0);
4609
4610   // fold (ctpop c1) -> c2
4611   if (isa<ConstantSDNode>(N0))
4612     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4613   return SDValue();
4614 }
4615
4616 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4617   SDValue N0 = N->getOperand(0);
4618   SDValue N1 = N->getOperand(1);
4619   SDValue N2 = N->getOperand(2);
4620   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4621   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4622   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4623   EVT VT = N->getValueType(0);
4624   EVT VT0 = N0.getValueType();
4625
4626   // fold (select C, X, X) -> X
4627   if (N1 == N2)
4628     return N1;
4629   // fold (select true, X, Y) -> X
4630   if (N0C && !N0C->isNullValue())
4631     return N1;
4632   // fold (select false, X, Y) -> Y
4633   if (N0C && N0C->isNullValue())
4634     return N2;
4635   // fold (select C, 1, X) -> (or C, X)
4636   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4637     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4638   // fold (select C, 0, 1) -> (xor C, 1)
4639   // We can't do this reliably if integer based booleans have different contents
4640   // to floating point based booleans. This is because we can't tell whether we
4641   // have an integer-based boolean or a floating-point-based boolean unless we
4642   // can find the SETCC that produced it and inspect its operands. This is
4643   // fairly easy if C is the SETCC node, but it can potentially be
4644   // undiscoverable (or not reasonably discoverable). For example, it could be
4645   // in another basic block or it could require searching a complicated
4646   // expression.
4647   if (VT.isInteger() &&
4648       (VT0 == MVT::i1 || (VT0.isInteger() &&
4649                           TLI.getBooleanContents(false, false) ==
4650                               TLI.getBooleanContents(false, true) &&
4651                           TLI.getBooleanContents(false, false) ==
4652                               TargetLowering::ZeroOrOneBooleanContent)) &&
4653       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4654     SDValue XORNode;
4655     if (VT == VT0)
4656       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4657                          N0, DAG.getConstant(1, VT0));
4658     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4659                           N0, DAG.getConstant(1, VT0));
4660     AddToWorklist(XORNode.getNode());
4661     if (VT.bitsGT(VT0))
4662       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4663     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4664   }
4665   // fold (select C, 0, X) -> (and (not C), X)
4666   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4667     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4668     AddToWorklist(NOTNode.getNode());
4669     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4670   }
4671   // fold (select C, X, 1) -> (or (not C), X)
4672   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4673     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4674     AddToWorklist(NOTNode.getNode());
4675     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4676   }
4677   // fold (select C, X, 0) -> (and C, X)
4678   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4679     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4680   // fold (select X, X, Y) -> (or X, Y)
4681   // fold (select X, 1, Y) -> (or X, Y)
4682   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4683     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4684   // fold (select X, Y, X) -> (and X, Y)
4685   // fold (select X, Y, 0) -> (and X, Y)
4686   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4687     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4688
4689   // If we can fold this based on the true/false value, do so.
4690   if (SimplifySelectOps(N, N1, N2))
4691     return SDValue(N, 0);  // Don't revisit N.
4692
4693   // fold selects based on a setcc into other things, such as min/max/abs
4694   if (N0.getOpcode() == ISD::SETCC) {
4695     if ((!LegalOperations &&
4696          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4697         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4698       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4699                          N0.getOperand(0), N0.getOperand(1),
4700                          N1, N2, N0.getOperand(2));
4701     return SimplifySelect(SDLoc(N), N0, N1, N2);
4702   }
4703
4704   return SDValue();
4705 }
4706
4707 static
4708 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4709   SDLoc DL(N);
4710   EVT LoVT, HiVT;
4711   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4712
4713   // Split the inputs.
4714   SDValue Lo, Hi, LL, LH, RL, RH;
4715   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4716   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4717
4718   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4719   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4720
4721   return std::make_pair(Lo, Hi);
4722 }
4723
4724 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4725 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4726 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4727   SDLoc dl(N);
4728   SDValue Cond = N->getOperand(0);
4729   SDValue LHS = N->getOperand(1);
4730   SDValue RHS = N->getOperand(2);
4731   EVT VT = N->getValueType(0);
4732   int NumElems = VT.getVectorNumElements();
4733   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4734          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4735          Cond.getOpcode() == ISD::BUILD_VECTOR);
4736
4737   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4738   // binary ones here.
4739   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4740     return SDValue();
4741
4742   // We're sure we have an even number of elements due to the
4743   // concat_vectors we have as arguments to vselect.
4744   // Skip BV elements until we find one that's not an UNDEF
4745   // After we find an UNDEF element, keep looping until we get to half the
4746   // length of the BV and see if all the non-undef nodes are the same.
4747   ConstantSDNode *BottomHalf = nullptr;
4748   for (int i = 0; i < NumElems / 2; ++i) {
4749     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4750       continue;
4751
4752     if (BottomHalf == nullptr)
4753       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4754     else if (Cond->getOperand(i).getNode() != BottomHalf)
4755       return SDValue();
4756   }
4757
4758   // Do the same for the second half of the BuildVector
4759   ConstantSDNode *TopHalf = nullptr;
4760   for (int i = NumElems / 2; i < NumElems; ++i) {
4761     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4762       continue;
4763
4764     if (TopHalf == nullptr)
4765       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4766     else if (Cond->getOperand(i).getNode() != TopHalf)
4767       return SDValue();
4768   }
4769
4770   assert(TopHalf && BottomHalf &&
4771          "One half of the selector was all UNDEFs and the other was all the "
4772          "same value. This should have been addressed before this function.");
4773   return DAG.getNode(
4774       ISD::CONCAT_VECTORS, dl, VT,
4775       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4776       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4777 }
4778
4779 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4780
4781   if (Level >= AfterLegalizeTypes)
4782     return SDValue();
4783
4784   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4785   SDValue Mask = MST->getMask();
4786   SDValue Data  = MST->getData();
4787   SDLoc DL(N);
4788
4789   // If the MSTORE data type requires splitting and the mask is provided by a
4790   // SETCC, then split both nodes and its operands before legalization. This
4791   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4792   // and enables future optimizations (e.g. min/max pattern matching on X86).
4793   if (Mask.getOpcode() == ISD::SETCC) {
4794
4795     // Check if any splitting is required.
4796     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4797         TargetLowering::TypeSplitVector)
4798       return SDValue();
4799
4800     SDValue MaskLo, MaskHi, Lo, Hi;
4801     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4802
4803     EVT LoVT, HiVT;
4804     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4805
4806     SDValue Chain = MST->getChain();
4807     SDValue Ptr   = MST->getBasePtr();
4808
4809     EVT MemoryVT = MST->getMemoryVT();
4810     unsigned Alignment = MST->getOriginalAlignment();
4811
4812     // if Alignment is equal to the vector size,
4813     // take the half of it for the second part
4814     unsigned SecondHalfAlignment =
4815       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4816          Alignment/2 : Alignment;
4817
4818     EVT LoMemVT, HiMemVT;
4819     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4820
4821     SDValue DataLo, DataHi;
4822     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4823
4824     MachineMemOperand *MMO = DAG.getMachineFunction().
4825       getMachineMemOperand(MST->getPointerInfo(), 
4826                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4827                            Alignment, MST->getAAInfo(), MST->getRanges());
4828
4829     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4830
4831     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4832     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4833                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4834
4835     MMO = DAG.getMachineFunction().
4836       getMachineMemOperand(MST->getPointerInfo(), 
4837                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4838                            SecondHalfAlignment, MST->getAAInfo(),
4839                            MST->getRanges());
4840
4841     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4842
4843     AddToWorklist(Lo.getNode());
4844     AddToWorklist(Hi.getNode());
4845
4846     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4847   }
4848   return SDValue();
4849 }
4850
4851 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4852
4853   if (Level >= AfterLegalizeTypes)
4854     return SDValue();
4855
4856   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4857   SDValue Mask = MLD->getMask();
4858   SDLoc DL(N);
4859
4860   // If the MLOAD result requires splitting and the mask is provided by a
4861   // SETCC, then split both nodes and its operands before legalization. This
4862   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4863   // and enables future optimizations (e.g. min/max pattern matching on X86).
4864
4865   if (Mask.getOpcode() == ISD::SETCC) {
4866     EVT VT = N->getValueType(0);
4867
4868     // Check if any splitting is required.
4869     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4870         TargetLowering::TypeSplitVector)
4871       return SDValue();
4872
4873     SDValue MaskLo, MaskHi, Lo, Hi;
4874     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4875
4876     SDValue Src0 = MLD->getSrc0();
4877     SDValue Src0Lo, Src0Hi;
4878     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4879
4880     EVT LoVT, HiVT;
4881     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4882
4883     SDValue Chain = MLD->getChain();
4884     SDValue Ptr   = MLD->getBasePtr();
4885     EVT MemoryVT = MLD->getMemoryVT();
4886     unsigned Alignment = MLD->getOriginalAlignment();
4887
4888     // if Alignment is equal to the vector size,
4889     // take the half of it for the second part
4890     unsigned SecondHalfAlignment =
4891       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4892          Alignment/2 : Alignment;
4893
4894     EVT LoMemVT, HiMemVT;
4895     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4896
4897     MachineMemOperand *MMO = DAG.getMachineFunction().
4898     getMachineMemOperand(MLD->getPointerInfo(), 
4899                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4900                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4901
4902     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4903
4904     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4905     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4906                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4907
4908     MMO = DAG.getMachineFunction().
4909     getMachineMemOperand(MLD->getPointerInfo(), 
4910                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4911                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4912
4913     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4914
4915     AddToWorklist(Lo.getNode());
4916     AddToWorklist(Hi.getNode());
4917
4918     // Build a factor node to remember that this load is independent of the
4919     // other one.
4920     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4921                         Hi.getValue(1));
4922
4923     // Legalized the chain result - switch anything that used the old chain to
4924     // use the new one.
4925     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4926
4927     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4928
4929     SDValue RetOps[] = { LoadRes, Chain };
4930     return DAG.getMergeValues(RetOps, DL);
4931   }
4932   return SDValue();
4933 }
4934
4935 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4936   SDValue N0 = N->getOperand(0);
4937   SDValue N1 = N->getOperand(1);
4938   SDValue N2 = N->getOperand(2);
4939   SDLoc DL(N);
4940
4941   // Canonicalize integer abs.
4942   // vselect (setg[te] X,  0),  X, -X ->
4943   // vselect (setgt    X, -1),  X, -X ->
4944   // vselect (setl[te] X,  0), -X,  X ->
4945   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4946   if (N0.getOpcode() == ISD::SETCC) {
4947     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4948     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4949     bool isAbs = false;
4950     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4951
4952     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4953          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4954         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4955       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4956     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4957              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4958       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4959
4960     if (isAbs) {
4961       EVT VT = LHS.getValueType();
4962       SDValue Shift = DAG.getNode(
4963           ISD::SRA, DL, VT, LHS,
4964           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4965       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4966       AddToWorklist(Shift.getNode());
4967       AddToWorklist(Add.getNode());
4968       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4969     }
4970   }
4971
4972   // If the VSELECT result requires splitting and the mask is provided by a
4973   // SETCC, then split both nodes and its operands before legalization. This
4974   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4975   // and enables future optimizations (e.g. min/max pattern matching on X86).
4976   if (N0.getOpcode() == ISD::SETCC) {
4977     EVT VT = N->getValueType(0);
4978
4979     // Check if any splitting is required.
4980     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4981         TargetLowering::TypeSplitVector)
4982       return SDValue();
4983
4984     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4985     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4986     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4987     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4988
4989     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4990     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4991
4992     // Add the new VSELECT nodes to the work list in case they need to be split
4993     // again.
4994     AddToWorklist(Lo.getNode());
4995     AddToWorklist(Hi.getNode());
4996
4997     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4998   }
4999
5000   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5001   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5002     return N1;
5003   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5004   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5005     return N2;
5006
5007   // The ConvertSelectToConcatVector function is assuming both the above
5008   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5009   // and addressed.
5010   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5011       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5012       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5013     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5014     if (CV.getNode())
5015       return CV;
5016   }
5017
5018   return SDValue();
5019 }
5020
5021 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5022   SDValue N0 = N->getOperand(0);
5023   SDValue N1 = N->getOperand(1);
5024   SDValue N2 = N->getOperand(2);
5025   SDValue N3 = N->getOperand(3);
5026   SDValue N4 = N->getOperand(4);
5027   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5028
5029   // fold select_cc lhs, rhs, x, x, cc -> x
5030   if (N2 == N3)
5031     return N2;
5032
5033   // Determine if the condition we're dealing with is constant
5034   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5035                               N0, N1, CC, SDLoc(N), false);
5036   if (SCC.getNode()) {
5037     AddToWorklist(SCC.getNode());
5038
5039     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5040       if (!SCCC->isNullValue())
5041         return N2;    // cond always true -> true val
5042       else
5043         return N3;    // cond always false -> false val
5044     }
5045
5046     // Fold to a simpler select_cc
5047     if (SCC.getOpcode() == ISD::SETCC)
5048       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5049                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5050                          SCC.getOperand(2));
5051   }
5052
5053   // If we can fold this based on the true/false value, do so.
5054   if (SimplifySelectOps(N, N2, N3))
5055     return SDValue(N, 0);  // Don't revisit N.
5056
5057   // fold select_cc into other things, such as min/max/abs
5058   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5059 }
5060
5061 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5062   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5063                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5064                        SDLoc(N));
5065 }
5066
5067 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5068 // dag node into a ConstantSDNode or a build_vector of constants.
5069 // This function is called by the DAGCombiner when visiting sext/zext/aext
5070 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5071 // Vector extends are not folded if operations are legal; this is to
5072 // avoid introducing illegal build_vector dag nodes.
5073 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5074                                          SelectionDAG &DAG, bool LegalTypes,
5075                                          bool LegalOperations) {
5076   unsigned Opcode = N->getOpcode();
5077   SDValue N0 = N->getOperand(0);
5078   EVT VT = N->getValueType(0);
5079
5080   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5081          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5082
5083   // fold (sext c1) -> c1
5084   // fold (zext c1) -> c1
5085   // fold (aext c1) -> c1
5086   if (isa<ConstantSDNode>(N0))
5087     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5088
5089   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5090   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5091   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5092   EVT SVT = VT.getScalarType();
5093   if (!(VT.isVector() &&
5094       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5095       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5096     return nullptr;
5097
5098   // We can fold this node into a build_vector.
5099   unsigned VTBits = SVT.getSizeInBits();
5100   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5101   unsigned ShAmt = VTBits - EVTBits;
5102   SmallVector<SDValue, 8> Elts;
5103   unsigned NumElts = N0->getNumOperands();
5104   SDLoc DL(N);
5105
5106   for (unsigned i=0; i != NumElts; ++i) {
5107     SDValue Op = N0->getOperand(i);
5108     if (Op->getOpcode() == ISD::UNDEF) {
5109       Elts.push_back(DAG.getUNDEF(SVT));
5110       continue;
5111     }
5112
5113     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5114     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5115     if (Opcode == ISD::SIGN_EXTEND)
5116       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5117                                      SVT));
5118     else
5119       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5120                                      SVT));
5121   }
5122
5123   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5124 }
5125
5126 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5127 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5128 // transformation. Returns true if extension are possible and the above
5129 // mentioned transformation is profitable.
5130 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5131                                     unsigned ExtOpc,
5132                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5133                                     const TargetLowering &TLI) {
5134   bool HasCopyToRegUses = false;
5135   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5136   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5137                             UE = N0.getNode()->use_end();
5138        UI != UE; ++UI) {
5139     SDNode *User = *UI;
5140     if (User == N)
5141       continue;
5142     if (UI.getUse().getResNo() != N0.getResNo())
5143       continue;
5144     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5145     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5146       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5147       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5148         // Sign bits will be lost after a zext.
5149         return false;
5150       bool Add = false;
5151       for (unsigned i = 0; i != 2; ++i) {
5152         SDValue UseOp = User->getOperand(i);
5153         if (UseOp == N0)
5154           continue;
5155         if (!isa<ConstantSDNode>(UseOp))
5156           return false;
5157         Add = true;
5158       }
5159       if (Add)
5160         ExtendNodes.push_back(User);
5161       continue;
5162     }
5163     // If truncates aren't free and there are users we can't
5164     // extend, it isn't worthwhile.
5165     if (!isTruncFree)
5166       return false;
5167     // Remember if this value is live-out.
5168     if (User->getOpcode() == ISD::CopyToReg)
5169       HasCopyToRegUses = true;
5170   }
5171
5172   if (HasCopyToRegUses) {
5173     bool BothLiveOut = false;
5174     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5175          UI != UE; ++UI) {
5176       SDUse &Use = UI.getUse();
5177       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5178         BothLiveOut = true;
5179         break;
5180       }
5181     }
5182     if (BothLiveOut)
5183       // Both unextended and extended values are live out. There had better be
5184       // a good reason for the transformation.
5185       return ExtendNodes.size();
5186   }
5187   return true;
5188 }
5189
5190 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5191                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5192                                   ISD::NodeType ExtType) {
5193   // Extend SetCC uses if necessary.
5194   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5195     SDNode *SetCC = SetCCs[i];
5196     SmallVector<SDValue, 4> Ops;
5197
5198     for (unsigned j = 0; j != 2; ++j) {
5199       SDValue SOp = SetCC->getOperand(j);
5200       if (SOp == Trunc)
5201         Ops.push_back(ExtLoad);
5202       else
5203         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5204     }
5205
5206     Ops.push_back(SetCC->getOperand(2));
5207     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5208   }
5209 }
5210
5211 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5212   SDValue N0 = N->getOperand(0);
5213   EVT VT = N->getValueType(0);
5214
5215   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5216                                               LegalOperations))
5217     return SDValue(Res, 0);
5218
5219   // fold (sext (sext x)) -> (sext x)
5220   // fold (sext (aext x)) -> (sext x)
5221   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5222     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5223                        N0.getOperand(0));
5224
5225   if (N0.getOpcode() == ISD::TRUNCATE) {
5226     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5227     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5228     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5229     if (NarrowLoad.getNode()) {
5230       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5231       if (NarrowLoad.getNode() != N0.getNode()) {
5232         CombineTo(N0.getNode(), NarrowLoad);
5233         // CombineTo deleted the truncate, if needed, but not what's under it.
5234         AddToWorklist(oye);
5235       }
5236       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5237     }
5238
5239     // See if the value being truncated is already sign extended.  If so, just
5240     // eliminate the trunc/sext pair.
5241     SDValue Op = N0.getOperand(0);
5242     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5243     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5244     unsigned DestBits = VT.getScalarType().getSizeInBits();
5245     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5246
5247     if (OpBits == DestBits) {
5248       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5249       // bits, it is already ready.
5250       if (NumSignBits > DestBits-MidBits)
5251         return Op;
5252     } else if (OpBits < DestBits) {
5253       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5254       // bits, just sext from i32.
5255       if (NumSignBits > OpBits-MidBits)
5256         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5257     } else {
5258       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5259       // bits, just truncate to i32.
5260       if (NumSignBits > OpBits-MidBits)
5261         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5262     }
5263
5264     // fold (sext (truncate x)) -> (sextinreg x).
5265     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5266                                                  N0.getValueType())) {
5267       if (OpBits < DestBits)
5268         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5269       else if (OpBits > DestBits)
5270         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5271       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5272                          DAG.getValueType(N0.getValueType()));
5273     }
5274   }
5275
5276   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5277   // None of the supported targets knows how to perform load and sign extend
5278   // on vectors in one instruction.  We only perform this transformation on
5279   // scalars.
5280   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5281       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5282       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5283        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5284     bool DoXform = true;
5285     SmallVector<SDNode*, 4> SetCCs;
5286     if (!N0.hasOneUse())
5287       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5288     if (DoXform) {
5289       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5290       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5291                                        LN0->getChain(),
5292                                        LN0->getBasePtr(), N0.getValueType(),
5293                                        LN0->getMemOperand());
5294       CombineTo(N, ExtLoad);
5295       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5296                                   N0.getValueType(), ExtLoad);
5297       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5298       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5299                       ISD::SIGN_EXTEND);
5300       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5301     }
5302   }
5303
5304   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5305   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5306   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5307       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5308     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5309     EVT MemVT = LN0->getMemoryVT();
5310     if ((!LegalOperations && !LN0->isVolatile()) ||
5311         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5312       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5313                                        LN0->getChain(),
5314                                        LN0->getBasePtr(), MemVT,
5315                                        LN0->getMemOperand());
5316       CombineTo(N, ExtLoad);
5317       CombineTo(N0.getNode(),
5318                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5319                             N0.getValueType(), ExtLoad),
5320                 ExtLoad.getValue(1));
5321       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5322     }
5323   }
5324
5325   // fold (sext (and/or/xor (load x), cst)) ->
5326   //      (and/or/xor (sextload x), (sext cst))
5327   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5328        N0.getOpcode() == ISD::XOR) &&
5329       isa<LoadSDNode>(N0.getOperand(0)) &&
5330       N0.getOperand(1).getOpcode() == ISD::Constant &&
5331       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5332       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5333     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5334     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5335       bool DoXform = true;
5336       SmallVector<SDNode*, 4> SetCCs;
5337       if (!N0.hasOneUse())
5338         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5339                                           SetCCs, TLI);
5340       if (DoXform) {
5341         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5342                                          LN0->getChain(), LN0->getBasePtr(),
5343                                          LN0->getMemoryVT(),
5344                                          LN0->getMemOperand());
5345         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5346         Mask = Mask.sext(VT.getSizeInBits());
5347         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5348                                   ExtLoad, DAG.getConstant(Mask, VT));
5349         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5350                                     SDLoc(N0.getOperand(0)),
5351                                     N0.getOperand(0).getValueType(), ExtLoad);
5352         CombineTo(N, And);
5353         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5354         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5355                         ISD::SIGN_EXTEND);
5356         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5357       }
5358     }
5359   }
5360
5361   if (N0.getOpcode() == ISD::SETCC) {
5362     EVT N0VT = N0.getOperand(0).getValueType();
5363     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5364     // Only do this before legalize for now.
5365     if (VT.isVector() && !LegalOperations &&
5366         TLI.getBooleanContents(N0VT) ==
5367             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5368       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5369       // of the same size as the compared operands. Only optimize sext(setcc())
5370       // if this is the case.
5371       EVT SVT = getSetCCResultType(N0VT);
5372
5373       // We know that the # elements of the results is the same as the
5374       // # elements of the compare (and the # elements of the compare result
5375       // for that matter).  Check to see that they are the same size.  If so,
5376       // we know that the element size of the sext'd result matches the
5377       // element size of the compare operands.
5378       if (VT.getSizeInBits() == SVT.getSizeInBits())
5379         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5380                              N0.getOperand(1),
5381                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5382
5383       // If the desired elements are smaller or larger than the source
5384       // elements we can use a matching integer vector type and then
5385       // truncate/sign extend
5386       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5387       if (SVT == MatchingVectorType) {
5388         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5389                                N0.getOperand(0), N0.getOperand(1),
5390                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5391         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5392       }
5393     }
5394
5395     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5396     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5397     SDValue NegOne =
5398       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5399     SDValue SCC =
5400       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5401                        NegOne, DAG.getConstant(0, VT),
5402                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5403     if (SCC.getNode()) return SCC;
5404
5405     if (!VT.isVector()) {
5406       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5407       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5408         SDLoc DL(N);
5409         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5410         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5411                                      N0.getOperand(0), N0.getOperand(1), CC);
5412         return DAG.getSelect(DL, VT, SetCC,
5413                              NegOne, DAG.getConstant(0, VT));
5414       }
5415     }
5416   }
5417
5418   // fold (sext x) -> (zext x) if the sign bit is known zero.
5419   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5420       DAG.SignBitIsZero(N0))
5421     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5422
5423   return SDValue();
5424 }
5425
5426 // isTruncateOf - If N is a truncate of some other value, return true, record
5427 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5428 // This function computes KnownZero to avoid a duplicated call to
5429 // computeKnownBits in the caller.
5430 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5431                          APInt &KnownZero) {
5432   APInt KnownOne;
5433   if (N->getOpcode() == ISD::TRUNCATE) {
5434     Op = N->getOperand(0);
5435     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5436     return true;
5437   }
5438
5439   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5440       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5441     return false;
5442
5443   SDValue Op0 = N->getOperand(0);
5444   SDValue Op1 = N->getOperand(1);
5445   assert(Op0.getValueType() == Op1.getValueType());
5446
5447   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5448   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5449   if (COp0 && COp0->isNullValue())
5450     Op = Op1;
5451   else if (COp1 && COp1->isNullValue())
5452     Op = Op0;
5453   else
5454     return false;
5455
5456   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5457
5458   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5459     return false;
5460
5461   return true;
5462 }
5463
5464 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5465   SDValue N0 = N->getOperand(0);
5466   EVT VT = N->getValueType(0);
5467
5468   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5469                                               LegalOperations))
5470     return SDValue(Res, 0);
5471
5472   // fold (zext (zext x)) -> (zext x)
5473   // fold (zext (aext x)) -> (zext x)
5474   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5475     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5476                        N0.getOperand(0));
5477
5478   // fold (zext (truncate x)) -> (zext x) or
5479   //      (zext (truncate x)) -> (truncate x)
5480   // This is valid when the truncated bits of x are already zero.
5481   // FIXME: We should extend this to work for vectors too.
5482   SDValue Op;
5483   APInt KnownZero;
5484   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5485     APInt TruncatedBits =
5486       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5487       APInt(Op.getValueSizeInBits(), 0) :
5488       APInt::getBitsSet(Op.getValueSizeInBits(),
5489                         N0.getValueSizeInBits(),
5490                         std::min(Op.getValueSizeInBits(),
5491                                  VT.getSizeInBits()));
5492     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5493       if (VT.bitsGT(Op.getValueType()))
5494         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5495       if (VT.bitsLT(Op.getValueType()))
5496         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5497
5498       return Op;
5499     }
5500   }
5501
5502   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5503   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5504   if (N0.getOpcode() == ISD::TRUNCATE) {
5505     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5506     if (NarrowLoad.getNode()) {
5507       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5508       if (NarrowLoad.getNode() != N0.getNode()) {
5509         CombineTo(N0.getNode(), NarrowLoad);
5510         // CombineTo deleted the truncate, if needed, but not what's under it.
5511         AddToWorklist(oye);
5512       }
5513       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5514     }
5515   }
5516
5517   // fold (zext (truncate x)) -> (and x, mask)
5518   if (N0.getOpcode() == ISD::TRUNCATE &&
5519       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5520
5521     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5522     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5523     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5524     if (NarrowLoad.getNode()) {
5525       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5526       if (NarrowLoad.getNode() != N0.getNode()) {
5527         CombineTo(N0.getNode(), NarrowLoad);
5528         // CombineTo deleted the truncate, if needed, but not what's under it.
5529         AddToWorklist(oye);
5530       }
5531       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5532     }
5533
5534     SDValue Op = N0.getOperand(0);
5535     if (Op.getValueType().bitsLT(VT)) {
5536       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5537       AddToWorklist(Op.getNode());
5538     } else if (Op.getValueType().bitsGT(VT)) {
5539       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5540       AddToWorklist(Op.getNode());
5541     }
5542     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5543                                   N0.getValueType().getScalarType());
5544   }
5545
5546   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5547   // if either of the casts is not free.
5548   if (N0.getOpcode() == ISD::AND &&
5549       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5550       N0.getOperand(1).getOpcode() == ISD::Constant &&
5551       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5552                            N0.getValueType()) ||
5553        !TLI.isZExtFree(N0.getValueType(), VT))) {
5554     SDValue X = N0.getOperand(0).getOperand(0);
5555     if (X.getValueType().bitsLT(VT)) {
5556       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5557     } else if (X.getValueType().bitsGT(VT)) {
5558       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5559     }
5560     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5561     Mask = Mask.zext(VT.getSizeInBits());
5562     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5563                        X, DAG.getConstant(Mask, VT));
5564   }
5565
5566   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5567   // None of the supported targets knows how to perform load and vector_zext
5568   // on vectors in one instruction.  We only perform this transformation on
5569   // scalars.
5570   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5571       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5572       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5573        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5574     bool DoXform = true;
5575     SmallVector<SDNode*, 4> SetCCs;
5576     if (!N0.hasOneUse())
5577       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5578     if (DoXform) {
5579       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5580       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5581                                        LN0->getChain(),
5582                                        LN0->getBasePtr(), N0.getValueType(),
5583                                        LN0->getMemOperand());
5584       CombineTo(N, ExtLoad);
5585       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5586                                   N0.getValueType(), ExtLoad);
5587       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5588
5589       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5590                       ISD::ZERO_EXTEND);
5591       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5592     }
5593   }
5594
5595   // fold (zext (and/or/xor (load x), cst)) ->
5596   //      (and/or/xor (zextload x), (zext cst))
5597   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5598        N0.getOpcode() == ISD::XOR) &&
5599       isa<LoadSDNode>(N0.getOperand(0)) &&
5600       N0.getOperand(1).getOpcode() == ISD::Constant &&
5601       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5602       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5603     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5604     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5605       bool DoXform = true;
5606       SmallVector<SDNode*, 4> SetCCs;
5607       if (!N0.hasOneUse())
5608         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5609                                           SetCCs, TLI);
5610       if (DoXform) {
5611         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5612                                          LN0->getChain(), LN0->getBasePtr(),
5613                                          LN0->getMemoryVT(),
5614                                          LN0->getMemOperand());
5615         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5616         Mask = Mask.zext(VT.getSizeInBits());
5617         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5618                                   ExtLoad, DAG.getConstant(Mask, VT));
5619         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5620                                     SDLoc(N0.getOperand(0)),
5621                                     N0.getOperand(0).getValueType(), ExtLoad);
5622         CombineTo(N, And);
5623         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5624         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5625                         ISD::ZERO_EXTEND);
5626         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5627       }
5628     }
5629   }
5630
5631   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5632   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5633   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5634       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5635     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5636     EVT MemVT = LN0->getMemoryVT();
5637     if ((!LegalOperations && !LN0->isVolatile()) ||
5638         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5639       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5640                                        LN0->getChain(),
5641                                        LN0->getBasePtr(), MemVT,
5642                                        LN0->getMemOperand());
5643       CombineTo(N, ExtLoad);
5644       CombineTo(N0.getNode(),
5645                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5646                             ExtLoad),
5647                 ExtLoad.getValue(1));
5648       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5649     }
5650   }
5651
5652   if (N0.getOpcode() == ISD::SETCC) {
5653     if (!LegalOperations && VT.isVector() &&
5654         N0.getValueType().getVectorElementType() == MVT::i1) {
5655       EVT N0VT = N0.getOperand(0).getValueType();
5656       if (getSetCCResultType(N0VT) == N0.getValueType())
5657         return SDValue();
5658
5659       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5660       // Only do this before legalize for now.
5661       EVT EltVT = VT.getVectorElementType();
5662       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5663                                     DAG.getConstant(1, EltVT));
5664       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5665         // We know that the # elements of the results is the same as the
5666         // # elements of the compare (and the # elements of the compare result
5667         // for that matter).  Check to see that they are the same size.  If so,
5668         // we know that the element size of the sext'd result matches the
5669         // element size of the compare operands.
5670         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5671                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5672                                          N0.getOperand(1),
5673                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5674                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5675                                        OneOps));
5676
5677       // If the desired elements are smaller or larger than the source
5678       // elements we can use a matching integer vector type and then
5679       // truncate/sign extend
5680       EVT MatchingElementType =
5681         EVT::getIntegerVT(*DAG.getContext(),
5682                           N0VT.getScalarType().getSizeInBits());
5683       EVT MatchingVectorType =
5684         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5685                          N0VT.getVectorNumElements());
5686       SDValue VsetCC =
5687         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5688                       N0.getOperand(1),
5689                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5690       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5691                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5692                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5693     }
5694
5695     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5696     SDValue SCC =
5697       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5698                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5699                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5700     if (SCC.getNode()) return SCC;
5701   }
5702
5703   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5704   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5705       isa<ConstantSDNode>(N0.getOperand(1)) &&
5706       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5707       N0.hasOneUse()) {
5708     SDValue ShAmt = N0.getOperand(1);
5709     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5710     if (N0.getOpcode() == ISD::SHL) {
5711       SDValue InnerZExt = N0.getOperand(0);
5712       // If the original shl may be shifting out bits, do not perform this
5713       // transformation.
5714       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5715         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5716       if (ShAmtVal > KnownZeroBits)
5717         return SDValue();
5718     }
5719
5720     SDLoc DL(N);
5721
5722     // Ensure that the shift amount is wide enough for the shifted value.
5723     if (VT.getSizeInBits() >= 256)
5724       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5725
5726     return DAG.getNode(N0.getOpcode(), DL, VT,
5727                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5728                        ShAmt);
5729   }
5730
5731   return SDValue();
5732 }
5733
5734 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5735   SDValue N0 = N->getOperand(0);
5736   EVT VT = N->getValueType(0);
5737
5738   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5739                                               LegalOperations))
5740     return SDValue(Res, 0);
5741
5742   // fold (aext (aext x)) -> (aext x)
5743   // fold (aext (zext x)) -> (zext x)
5744   // fold (aext (sext x)) -> (sext x)
5745   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5746       N0.getOpcode() == ISD::ZERO_EXTEND ||
5747       N0.getOpcode() == ISD::SIGN_EXTEND)
5748     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5749
5750   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5751   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5752   if (N0.getOpcode() == ISD::TRUNCATE) {
5753     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5754     if (NarrowLoad.getNode()) {
5755       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5756       if (NarrowLoad.getNode() != N0.getNode()) {
5757         CombineTo(N0.getNode(), NarrowLoad);
5758         // CombineTo deleted the truncate, if needed, but not what's under it.
5759         AddToWorklist(oye);
5760       }
5761       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5762     }
5763   }
5764
5765   // fold (aext (truncate x))
5766   if (N0.getOpcode() == ISD::TRUNCATE) {
5767     SDValue TruncOp = N0.getOperand(0);
5768     if (TruncOp.getValueType() == VT)
5769       return TruncOp; // x iff x size == zext size.
5770     if (TruncOp.getValueType().bitsGT(VT))
5771       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5772     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5773   }
5774
5775   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5776   // if the trunc is not free.
5777   if (N0.getOpcode() == ISD::AND &&
5778       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5779       N0.getOperand(1).getOpcode() == ISD::Constant &&
5780       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5781                           N0.getValueType())) {
5782     SDValue X = N0.getOperand(0).getOperand(0);
5783     if (X.getValueType().bitsLT(VT)) {
5784       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5785     } else if (X.getValueType().bitsGT(VT)) {
5786       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5787     }
5788     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5789     Mask = Mask.zext(VT.getSizeInBits());
5790     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5791                        X, DAG.getConstant(Mask, VT));
5792   }
5793
5794   // fold (aext (load x)) -> (aext (truncate (extload x)))
5795   // None of the supported targets knows how to perform load and any_ext
5796   // on vectors in one instruction.  We only perform this transformation on
5797   // scalars.
5798   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5799       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5800       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5801     bool DoXform = true;
5802     SmallVector<SDNode*, 4> SetCCs;
5803     if (!N0.hasOneUse())
5804       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5805     if (DoXform) {
5806       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5807       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5808                                        LN0->getChain(),
5809                                        LN0->getBasePtr(), N0.getValueType(),
5810                                        LN0->getMemOperand());
5811       CombineTo(N, ExtLoad);
5812       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5813                                   N0.getValueType(), ExtLoad);
5814       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5815       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5816                       ISD::ANY_EXTEND);
5817       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5818     }
5819   }
5820
5821   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5822   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5823   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5824   if (N0.getOpcode() == ISD::LOAD &&
5825       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826       N0.hasOneUse()) {
5827     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5828     ISD::LoadExtType ExtType = LN0->getExtensionType();
5829     EVT MemVT = LN0->getMemoryVT();
5830     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5831       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5832                                        VT, LN0->getChain(), LN0->getBasePtr(),
5833                                        MemVT, LN0->getMemOperand());
5834       CombineTo(N, ExtLoad);
5835       CombineTo(N0.getNode(),
5836                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5837                             N0.getValueType(), ExtLoad),
5838                 ExtLoad.getValue(1));
5839       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5840     }
5841   }
5842
5843   if (N0.getOpcode() == ISD::SETCC) {
5844     // For vectors:
5845     // aext(setcc) -> vsetcc
5846     // aext(setcc) -> truncate(vsetcc)
5847     // aext(setcc) -> aext(vsetcc)
5848     // Only do this before legalize for now.
5849     if (VT.isVector() && !LegalOperations) {
5850       EVT N0VT = N0.getOperand(0).getValueType();
5851         // We know that the # elements of the results is the same as the
5852         // # elements of the compare (and the # elements of the compare result
5853         // for that matter).  Check to see that they are the same size.  If so,
5854         // we know that the element size of the sext'd result matches the
5855         // element size of the compare operands.
5856       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5857         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5858                              N0.getOperand(1),
5859                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5860       // If the desired elements are smaller or larger than the source
5861       // elements we can use a matching integer vector type and then
5862       // truncate/any extend
5863       else {
5864         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5865         SDValue VsetCC =
5866           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5867                         N0.getOperand(1),
5868                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5869         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5870       }
5871     }
5872
5873     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5874     SDValue SCC =
5875       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5876                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5877                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5878     if (SCC.getNode())
5879       return SCC;
5880   }
5881
5882   return SDValue();
5883 }
5884
5885 /// See if the specified operand can be simplified with the knowledge that only
5886 /// the bits specified by Mask are used.  If so, return the simpler operand,
5887 /// otherwise return a null SDValue.
5888 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5889   switch (V.getOpcode()) {
5890   default: break;
5891   case ISD::Constant: {
5892     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5893     assert(CV && "Const value should be ConstSDNode.");
5894     const APInt &CVal = CV->getAPIntValue();
5895     APInt NewVal = CVal & Mask;
5896     if (NewVal != CVal)
5897       return DAG.getConstant(NewVal, V.getValueType());
5898     break;
5899   }
5900   case ISD::OR:
5901   case ISD::XOR:
5902     // If the LHS or RHS don't contribute bits to the or, drop them.
5903     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5904       return V.getOperand(1);
5905     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5906       return V.getOperand(0);
5907     break;
5908   case ISD::SRL:
5909     // Only look at single-use SRLs.
5910     if (!V.getNode()->hasOneUse())
5911       break;
5912     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5913       // See if we can recursively simplify the LHS.
5914       unsigned Amt = RHSC->getZExtValue();
5915
5916       // Watch out for shift count overflow though.
5917       if (Amt >= Mask.getBitWidth()) break;
5918       APInt NewMask = Mask << Amt;
5919       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5920       if (SimplifyLHS.getNode())
5921         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5922                            SimplifyLHS, V.getOperand(1));
5923     }
5924   }
5925   return SDValue();
5926 }
5927
5928 /// If the result of a wider load is shifted to right of N  bits and then
5929 /// truncated to a narrower type and where N is a multiple of number of bits of
5930 /// the narrower type, transform it to a narrower load from address + N / num of
5931 /// bits of new type. If the result is to be extended, also fold the extension
5932 /// to form a extending load.
5933 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5934   unsigned Opc = N->getOpcode();
5935
5936   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5937   SDValue N0 = N->getOperand(0);
5938   EVT VT = N->getValueType(0);
5939   EVT ExtVT = VT;
5940
5941   // This transformation isn't valid for vector loads.
5942   if (VT.isVector())
5943     return SDValue();
5944
5945   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5946   // extended to VT.
5947   if (Opc == ISD::SIGN_EXTEND_INREG) {
5948     ExtType = ISD::SEXTLOAD;
5949     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5950   } else if (Opc == ISD::SRL) {
5951     // Another special-case: SRL is basically zero-extending a narrower value.
5952     ExtType = ISD::ZEXTLOAD;
5953     N0 = SDValue(N, 0);
5954     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5955     if (!N01) return SDValue();
5956     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5957                               VT.getSizeInBits() - N01->getZExtValue());
5958   }
5959   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5960     return SDValue();
5961
5962   unsigned EVTBits = ExtVT.getSizeInBits();
5963
5964   // Do not generate loads of non-round integer types since these can
5965   // be expensive (and would be wrong if the type is not byte sized).
5966   if (!ExtVT.isRound())
5967     return SDValue();
5968
5969   unsigned ShAmt = 0;
5970   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5971     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5972       ShAmt = N01->getZExtValue();
5973       // Is the shift amount a multiple of size of VT?
5974       if ((ShAmt & (EVTBits-1)) == 0) {
5975         N0 = N0.getOperand(0);
5976         // Is the load width a multiple of size of VT?
5977         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5978           return SDValue();
5979       }
5980
5981       // At this point, we must have a load or else we can't do the transform.
5982       if (!isa<LoadSDNode>(N0)) return SDValue();
5983
5984       // Because a SRL must be assumed to *need* to zero-extend the high bits
5985       // (as opposed to anyext the high bits), we can't combine the zextload
5986       // lowering of SRL and an sextload.
5987       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5988         return SDValue();
5989
5990       // If the shift amount is larger than the input type then we're not
5991       // accessing any of the loaded bytes.  If the load was a zextload/extload
5992       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5993       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5994         return SDValue();
5995     }
5996   }
5997
5998   // If the load is shifted left (and the result isn't shifted back right),
5999   // we can fold the truncate through the shift.
6000   unsigned ShLeftAmt = 0;
6001   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6002       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6003     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6004       ShLeftAmt = N01->getZExtValue();
6005       N0 = N0.getOperand(0);
6006     }
6007   }
6008
6009   // If we haven't found a load, we can't narrow it.  Don't transform one with
6010   // multiple uses, this would require adding a new load.
6011   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6012     return SDValue();
6013
6014   // Don't change the width of a volatile load.
6015   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6016   if (LN0->isVolatile())
6017     return SDValue();
6018
6019   // Verify that we are actually reducing a load width here.
6020   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6021     return SDValue();
6022
6023   // For the transform to be legal, the load must produce only two values
6024   // (the value loaded and the chain).  Don't transform a pre-increment
6025   // load, for example, which produces an extra value.  Otherwise the
6026   // transformation is not equivalent, and the downstream logic to replace
6027   // uses gets things wrong.
6028   if (LN0->getNumValues() > 2)
6029     return SDValue();
6030
6031   // If the load that we're shrinking is an extload and we're not just
6032   // discarding the extension we can't simply shrink the load. Bail.
6033   // TODO: It would be possible to merge the extensions in some cases.
6034   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6035       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6036     return SDValue();
6037
6038   EVT PtrType = N0.getOperand(1).getValueType();
6039
6040   if (PtrType == MVT::Untyped || PtrType.isExtended())
6041     // It's not possible to generate a constant of extended or untyped type.
6042     return SDValue();
6043
6044   // For big endian targets, we need to adjust the offset to the pointer to
6045   // load the correct bytes.
6046   if (TLI.isBigEndian()) {
6047     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6048     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6049     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6050   }
6051
6052   uint64_t PtrOff = ShAmt / 8;
6053   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6054   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6055                                PtrType, LN0->getBasePtr(),
6056                                DAG.getConstant(PtrOff, PtrType));
6057   AddToWorklist(NewPtr.getNode());
6058
6059   SDValue Load;
6060   if (ExtType == ISD::NON_EXTLOAD)
6061     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6062                         LN0->getPointerInfo().getWithOffset(PtrOff),
6063                         LN0->isVolatile(), LN0->isNonTemporal(),
6064                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6065   else
6066     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6067                           LN0->getPointerInfo().getWithOffset(PtrOff),
6068                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6069                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6070
6071   // Replace the old load's chain with the new load's chain.
6072   WorklistRemover DeadNodes(*this);
6073   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6074
6075   // Shift the result left, if we've swallowed a left shift.
6076   SDValue Result = Load;
6077   if (ShLeftAmt != 0) {
6078     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6079     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6080       ShImmTy = VT;
6081     // If the shift amount is as large as the result size (but, presumably,
6082     // no larger than the source) then the useful bits of the result are
6083     // zero; we can't simply return the shortened shift, because the result
6084     // of that operation is undefined.
6085     if (ShLeftAmt >= VT.getSizeInBits())
6086       Result = DAG.getConstant(0, VT);
6087     else
6088       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6089                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6090   }
6091
6092   // Return the new loaded value.
6093   return Result;
6094 }
6095
6096 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6097   SDValue N0 = N->getOperand(0);
6098   SDValue N1 = N->getOperand(1);
6099   EVT VT = N->getValueType(0);
6100   EVT EVT = cast<VTSDNode>(N1)->getVT();
6101   unsigned VTBits = VT.getScalarType().getSizeInBits();
6102   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6103
6104   // fold (sext_in_reg c1) -> c1
6105   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6106     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6107
6108   // If the input is already sign extended, just drop the extension.
6109   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6110     return N0;
6111
6112   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6113   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6114       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6115     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6116                        N0.getOperand(0), N1);
6117
6118   // fold (sext_in_reg (sext x)) -> (sext x)
6119   // fold (sext_in_reg (aext x)) -> (sext x)
6120   // if x is small enough.
6121   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6122     SDValue N00 = N0.getOperand(0);
6123     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6124         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6125       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6126   }
6127
6128   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6129   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6130     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6131
6132   // fold operands of sext_in_reg based on knowledge that the top bits are not
6133   // demanded.
6134   if (SimplifyDemandedBits(SDValue(N, 0)))
6135     return SDValue(N, 0);
6136
6137   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6138   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6139   SDValue NarrowLoad = ReduceLoadWidth(N);
6140   if (NarrowLoad.getNode())
6141     return NarrowLoad;
6142
6143   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6144   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6145   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6146   if (N0.getOpcode() == ISD::SRL) {
6147     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6148       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6149         // We can turn this into an SRA iff the input to the SRL is already sign
6150         // extended enough.
6151         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6152         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6153           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6154                              N0.getOperand(0), N0.getOperand(1));
6155       }
6156   }
6157
6158   // fold (sext_inreg (extload x)) -> (sextload x)
6159   if (ISD::isEXTLoad(N0.getNode()) &&
6160       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6161       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6162       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6163        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6164     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6165     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6166                                      LN0->getChain(),
6167                                      LN0->getBasePtr(), EVT,
6168                                      LN0->getMemOperand());
6169     CombineTo(N, ExtLoad);
6170     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6171     AddToWorklist(ExtLoad.getNode());
6172     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6173   }
6174   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6175   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6176       N0.hasOneUse() &&
6177       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6178       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6179        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6180     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6181     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6182                                      LN0->getChain(),
6183                                      LN0->getBasePtr(), EVT,
6184                                      LN0->getMemOperand());
6185     CombineTo(N, ExtLoad);
6186     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6187     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6188   }
6189
6190   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6191   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6192     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6193                                        N0.getOperand(1), false);
6194     if (BSwap.getNode())
6195       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6196                          BSwap, N1);
6197   }
6198
6199   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6200   // into a build_vector.
6201   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6202     SmallVector<SDValue, 8> Elts;
6203     unsigned NumElts = N0->getNumOperands();
6204     unsigned ShAmt = VTBits - EVTBits;
6205
6206     for (unsigned i = 0; i != NumElts; ++i) {
6207       SDValue Op = N0->getOperand(i);
6208       if (Op->getOpcode() == ISD::UNDEF) {
6209         Elts.push_back(Op);
6210         continue;
6211       }
6212
6213       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6214       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6215       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6216                                      Op.getValueType()));
6217     }
6218
6219     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6220   }
6221
6222   return SDValue();
6223 }
6224
6225 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6226   SDValue N0 = N->getOperand(0);
6227   EVT VT = N->getValueType(0);
6228   bool isLE = TLI.isLittleEndian();
6229
6230   // noop truncate
6231   if (N0.getValueType() == N->getValueType(0))
6232     return N0;
6233   // fold (truncate c1) -> c1
6234   if (isa<ConstantSDNode>(N0))
6235     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6236   // fold (truncate (truncate x)) -> (truncate x)
6237   if (N0.getOpcode() == ISD::TRUNCATE)
6238     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6239   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6240   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6241       N0.getOpcode() == ISD::SIGN_EXTEND ||
6242       N0.getOpcode() == ISD::ANY_EXTEND) {
6243     if (N0.getOperand(0).getValueType().bitsLT(VT))
6244       // if the source is smaller than the dest, we still need an extend
6245       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6246                          N0.getOperand(0));
6247     if (N0.getOperand(0).getValueType().bitsGT(VT))
6248       // if the source is larger than the dest, than we just need the truncate
6249       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6250     // if the source and dest are the same type, we can drop both the extend
6251     // and the truncate.
6252     return N0.getOperand(0);
6253   }
6254
6255   // Fold extract-and-trunc into a narrow extract. For example:
6256   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6257   //   i32 y = TRUNCATE(i64 x)
6258   //        -- becomes --
6259   //   v16i8 b = BITCAST (v2i64 val)
6260   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6261   //
6262   // Note: We only run this optimization after type legalization (which often
6263   // creates this pattern) and before operation legalization after which
6264   // we need to be more careful about the vector instructions that we generate.
6265   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6266       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6267
6268     EVT VecTy = N0.getOperand(0).getValueType();
6269     EVT ExTy = N0.getValueType();
6270     EVT TrTy = N->getValueType(0);
6271
6272     unsigned NumElem = VecTy.getVectorNumElements();
6273     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6274
6275     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6276     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6277
6278     SDValue EltNo = N0->getOperand(1);
6279     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6280       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6281       EVT IndexTy = TLI.getVectorIdxTy();
6282       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6283
6284       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6285                               NVT, N0.getOperand(0));
6286
6287       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6288                          SDLoc(N), TrTy, V,
6289                          DAG.getConstant(Index, IndexTy));
6290     }
6291   }
6292
6293   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6294   if (N0.getOpcode() == ISD::SELECT) {
6295     EVT SrcVT = N0.getValueType();
6296     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6297         TLI.isTruncateFree(SrcVT, VT)) {
6298       SDLoc SL(N0);
6299       SDValue Cond = N0.getOperand(0);
6300       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6301       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6302       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6303     }
6304   }
6305
6306   // Fold a series of buildvector, bitcast, and truncate if possible.
6307   // For example fold
6308   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6309   //   (2xi32 (buildvector x, y)).
6310   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6311       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6312       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6313       N0.getOperand(0).hasOneUse()) {
6314
6315     SDValue BuildVect = N0.getOperand(0);
6316     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6317     EVT TruncVecEltTy = VT.getVectorElementType();
6318
6319     // Check that the element types match.
6320     if (BuildVectEltTy == TruncVecEltTy) {
6321       // Now we only need to compute the offset of the truncated elements.
6322       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6323       unsigned TruncVecNumElts = VT.getVectorNumElements();
6324       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6325
6326       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6327              "Invalid number of elements");
6328
6329       SmallVector<SDValue, 8> Opnds;
6330       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6331         Opnds.push_back(BuildVect.getOperand(i));
6332
6333       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6334     }
6335   }
6336
6337   // See if we can simplify the input to this truncate through knowledge that
6338   // only the low bits are being used.
6339   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6340   // Currently we only perform this optimization on scalars because vectors
6341   // may have different active low bits.
6342   if (!VT.isVector()) {
6343     SDValue Shorter =
6344       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6345                                                VT.getSizeInBits()));
6346     if (Shorter.getNode())
6347       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6348   }
6349   // fold (truncate (load x)) -> (smaller load x)
6350   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6351   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6352     SDValue Reduced = ReduceLoadWidth(N);
6353     if (Reduced.getNode())
6354       return Reduced;
6355     // Handle the case where the load remains an extending load even
6356     // after truncation.
6357     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6358       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6359       if (!LN0->isVolatile() &&
6360           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6361         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6362                                          VT, LN0->getChain(), LN0->getBasePtr(),
6363                                          LN0->getMemoryVT(),
6364                                          LN0->getMemOperand());
6365         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6366         return NewLoad;
6367       }
6368     }
6369   }
6370   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6371   // where ... are all 'undef'.
6372   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6373     SmallVector<EVT, 8> VTs;
6374     SDValue V;
6375     unsigned Idx = 0;
6376     unsigned NumDefs = 0;
6377
6378     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6379       SDValue X = N0.getOperand(i);
6380       if (X.getOpcode() != ISD::UNDEF) {
6381         V = X;
6382         Idx = i;
6383         NumDefs++;
6384       }
6385       // Stop if more than one members are non-undef.
6386       if (NumDefs > 1)
6387         break;
6388       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6389                                      VT.getVectorElementType(),
6390                                      X.getValueType().getVectorNumElements()));
6391     }
6392
6393     if (NumDefs == 0)
6394       return DAG.getUNDEF(VT);
6395
6396     if (NumDefs == 1) {
6397       assert(V.getNode() && "The single defined operand is empty!");
6398       SmallVector<SDValue, 8> Opnds;
6399       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6400         if (i != Idx) {
6401           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6402           continue;
6403         }
6404         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6405         AddToWorklist(NV.getNode());
6406         Opnds.push_back(NV);
6407       }
6408       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6409     }
6410   }
6411
6412   // Simplify the operands using demanded-bits information.
6413   if (!VT.isVector() &&
6414       SimplifyDemandedBits(SDValue(N, 0)))
6415     return SDValue(N, 0);
6416
6417   return SDValue();
6418 }
6419
6420 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6421   SDValue Elt = N->getOperand(i);
6422   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6423     return Elt.getNode();
6424   return Elt.getOperand(Elt.getResNo()).getNode();
6425 }
6426
6427 /// build_pair (load, load) -> load
6428 /// if load locations are consecutive.
6429 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6430   assert(N->getOpcode() == ISD::BUILD_PAIR);
6431
6432   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6433   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6434   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6435       LD1->getAddressSpace() != LD2->getAddressSpace())
6436     return SDValue();
6437   EVT LD1VT = LD1->getValueType(0);
6438
6439   if (ISD::isNON_EXTLoad(LD2) &&
6440       LD2->hasOneUse() &&
6441       // If both are volatile this would reduce the number of volatile loads.
6442       // If one is volatile it might be ok, but play conservative and bail out.
6443       !LD1->isVolatile() &&
6444       !LD2->isVolatile() &&
6445       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6446     unsigned Align = LD1->getAlignment();
6447     unsigned NewAlign = TLI.getDataLayout()->
6448       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6449
6450     if (NewAlign <= Align &&
6451         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6452       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6453                          LD1->getBasePtr(), LD1->getPointerInfo(),
6454                          false, false, false, Align);
6455   }
6456
6457   return SDValue();
6458 }
6459
6460 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6461   SDValue N0 = N->getOperand(0);
6462   EVT VT = N->getValueType(0);
6463
6464   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6465   // Only do this before legalize, since afterward the target may be depending
6466   // on the bitconvert.
6467   // First check to see if this is all constant.
6468   if (!LegalTypes &&
6469       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6470       VT.isVector()) {
6471     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6472
6473     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6474     assert(!DestEltVT.isVector() &&
6475            "Element type of vector ValueType must not be vector!");
6476     if (isSimple)
6477       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6478   }
6479
6480   // If the input is a constant, let getNode fold it.
6481   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6482     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6483     if (Res.getNode() != N) {
6484       if (!LegalOperations ||
6485           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6486         return Res;
6487
6488       // Folding it resulted in an illegal node, and it's too late to
6489       // do that. Clean up the old node and forego the transformation.
6490       // Ideally this won't happen very often, because instcombine
6491       // and the earlier dagcombine runs (where illegal nodes are
6492       // permitted) should have folded most of them already.
6493       deleteAndRecombine(Res.getNode());
6494     }
6495   }
6496
6497   // (conv (conv x, t1), t2) -> (conv x, t2)
6498   if (N0.getOpcode() == ISD::BITCAST)
6499     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6500                        N0.getOperand(0));
6501
6502   // fold (conv (load x)) -> (load (conv*)x)
6503   // If the resultant load doesn't need a higher alignment than the original!
6504   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6505       // Do not change the width of a volatile load.
6506       !cast<LoadSDNode>(N0)->isVolatile() &&
6507       // Do not remove the cast if the types differ in endian layout.
6508       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6509       TLI.hasBigEndianPartOrdering(VT) &&
6510       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6511       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6512     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6513     unsigned Align = TLI.getDataLayout()->
6514       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6515     unsigned OrigAlign = LN0->getAlignment();
6516
6517     if (Align <= OrigAlign) {
6518       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6519                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6520                                  LN0->isVolatile(), LN0->isNonTemporal(),
6521                                  LN0->isInvariant(), OrigAlign,
6522                                  LN0->getAAInfo());
6523       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6524       return Load;
6525     }
6526   }
6527
6528   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6529   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6530   // This often reduces constant pool loads.
6531   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6532        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6533       N0.getNode()->hasOneUse() && VT.isInteger() &&
6534       !VT.isVector() && !N0.getValueType().isVector()) {
6535     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6536                                   N0.getOperand(0));
6537     AddToWorklist(NewConv.getNode());
6538
6539     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6540     if (N0.getOpcode() == ISD::FNEG)
6541       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6542                          NewConv, DAG.getConstant(SignBit, VT));
6543     assert(N0.getOpcode() == ISD::FABS);
6544     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6545                        NewConv, DAG.getConstant(~SignBit, VT));
6546   }
6547
6548   // fold (bitconvert (fcopysign cst, x)) ->
6549   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6550   // Note that we don't handle (copysign x, cst) because this can always be
6551   // folded to an fneg or fabs.
6552   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6553       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6554       VT.isInteger() && !VT.isVector()) {
6555     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6556     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6557     if (isTypeLegal(IntXVT)) {
6558       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6559                               IntXVT, N0.getOperand(1));
6560       AddToWorklist(X.getNode());
6561
6562       // If X has a different width than the result/lhs, sext it or truncate it.
6563       unsigned VTWidth = VT.getSizeInBits();
6564       if (OrigXWidth < VTWidth) {
6565         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6566         AddToWorklist(X.getNode());
6567       } else if (OrigXWidth > VTWidth) {
6568         // To get the sign bit in the right place, we have to shift it right
6569         // before truncating.
6570         X = DAG.getNode(ISD::SRL, SDLoc(X),
6571                         X.getValueType(), X,
6572                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6573         AddToWorklist(X.getNode());
6574         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6575         AddToWorklist(X.getNode());
6576       }
6577
6578       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6579       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6580                       X, DAG.getConstant(SignBit, VT));
6581       AddToWorklist(X.getNode());
6582
6583       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6584                                 VT, N0.getOperand(0));
6585       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6586                         Cst, DAG.getConstant(~SignBit, VT));
6587       AddToWorklist(Cst.getNode());
6588
6589       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6590     }
6591   }
6592
6593   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6594   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6595     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6596     if (CombineLD.getNode())
6597       return CombineLD;
6598   }
6599
6600   return SDValue();
6601 }
6602
6603 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6604   EVT VT = N->getValueType(0);
6605   return CombineConsecutiveLoads(N, VT);
6606 }
6607
6608 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6609 /// operands. DstEltVT indicates the destination element value type.
6610 SDValue DAGCombiner::
6611 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6612   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6613
6614   // If this is already the right type, we're done.
6615   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6616
6617   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6618   unsigned DstBitSize = DstEltVT.getSizeInBits();
6619
6620   // If this is a conversion of N elements of one type to N elements of another
6621   // type, convert each element.  This handles FP<->INT cases.
6622   if (SrcBitSize == DstBitSize) {
6623     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6624                               BV->getValueType(0).getVectorNumElements());
6625
6626     // Due to the FP element handling below calling this routine recursively,
6627     // we can end up with a scalar-to-vector node here.
6628     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6629       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6630                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6631                                      DstEltVT, BV->getOperand(0)));
6632
6633     SmallVector<SDValue, 8> Ops;
6634     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6635       SDValue Op = BV->getOperand(i);
6636       // If the vector element type is not legal, the BUILD_VECTOR operands
6637       // are promoted and implicitly truncated.  Make that explicit here.
6638       if (Op.getValueType() != SrcEltVT)
6639         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6640       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6641                                 DstEltVT, Op));
6642       AddToWorklist(Ops.back().getNode());
6643     }
6644     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6645   }
6646
6647   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6648   // handle annoying details of growing/shrinking FP values, we convert them to
6649   // int first.
6650   if (SrcEltVT.isFloatingPoint()) {
6651     // Convert the input float vector to a int vector where the elements are the
6652     // same sizes.
6653     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6654     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6655     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6656     SrcEltVT = IntVT;
6657   }
6658
6659   // Now we know the input is an integer vector.  If the output is a FP type,
6660   // convert to integer first, then to FP of the right size.
6661   if (DstEltVT.isFloatingPoint()) {
6662     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6663     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6664     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6665
6666     // Next, convert to FP elements of the same size.
6667     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6668   }
6669
6670   // Okay, we know the src/dst types are both integers of differing types.
6671   // Handling growing first.
6672   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6673   if (SrcBitSize < DstBitSize) {
6674     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6675
6676     SmallVector<SDValue, 8> Ops;
6677     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6678          i += NumInputsPerOutput) {
6679       bool isLE = TLI.isLittleEndian();
6680       APInt NewBits = APInt(DstBitSize, 0);
6681       bool EltIsUndef = true;
6682       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6683         // Shift the previously computed bits over.
6684         NewBits <<= SrcBitSize;
6685         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6686         if (Op.getOpcode() == ISD::UNDEF) continue;
6687         EltIsUndef = false;
6688
6689         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6690                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6691       }
6692
6693       if (EltIsUndef)
6694         Ops.push_back(DAG.getUNDEF(DstEltVT));
6695       else
6696         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6697     }
6698
6699     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6700     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6701   }
6702
6703   // Finally, this must be the case where we are shrinking elements: each input
6704   // turns into multiple outputs.
6705   bool isS2V = ISD::isScalarToVector(BV);
6706   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6707   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6708                             NumOutputsPerInput*BV->getNumOperands());
6709   SmallVector<SDValue, 8> Ops;
6710
6711   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6712     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6713       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6714         Ops.push_back(DAG.getUNDEF(DstEltVT));
6715       continue;
6716     }
6717
6718     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6719                   getAPIntValue().zextOrTrunc(SrcBitSize);
6720
6721     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6722       APInt ThisVal = OpVal.trunc(DstBitSize);
6723       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6724       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6725         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6726         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6727                            Ops[0]);
6728       OpVal = OpVal.lshr(DstBitSize);
6729     }
6730
6731     // For big endian targets, swap the order of the pieces of each element.
6732     if (TLI.isBigEndian())
6733       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6734   }
6735
6736   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6737 }
6738
6739 SDValue DAGCombiner::visitFADD(SDNode *N) {
6740   SDValue N0 = N->getOperand(0);
6741   SDValue N1 = N->getOperand(1);
6742   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6743   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6744   EVT VT = N->getValueType(0);
6745   const TargetOptions &Options = DAG.getTarget().Options;
6746
6747   // fold vector ops
6748   if (VT.isVector()) {
6749     SDValue FoldedVOp = SimplifyVBinOp(N);
6750     if (FoldedVOp.getNode()) return FoldedVOp;
6751   }
6752
6753   // fold (fadd c1, c2) -> c1 + c2
6754   if (N0CFP && N1CFP)
6755     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6756
6757   // canonicalize constant to RHS
6758   if (N0CFP && !N1CFP)
6759     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6760
6761   // fold (fadd A, (fneg B)) -> (fsub A, B)
6762   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6763       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6764     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6765                        GetNegatedExpression(N1, DAG, LegalOperations));
6766
6767   // fold (fadd (fneg A), B) -> (fsub B, A)
6768   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6769       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6770     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6771                        GetNegatedExpression(N0, DAG, LegalOperations));
6772
6773   // If 'unsafe math' is enabled, fold lots of things.
6774   if (Options.UnsafeFPMath) {
6775     // No FP constant should be created after legalization as Instruction
6776     // Selection pass has a hard time dealing with FP constants.
6777     bool AllowNewConst = (Level < AfterLegalizeDAG);
6778
6779     // fold (fadd A, 0) -> A
6780     if (N1CFP && N1CFP->getValueAPF().isZero())
6781       return N0;
6782
6783     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6784     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6785         isa<ConstantFPSDNode>(N0.getOperand(1)))
6786       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6787                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6788                                      N0.getOperand(1), N1));
6789
6790     // If allowed, fold (fadd (fneg x), x) -> 0.0
6791     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6792       return DAG.getConstantFP(0.0, VT);
6793
6794     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6795     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6796       return DAG.getConstantFP(0.0, VT);
6797
6798     // We can fold chains of FADD's of the same value into multiplications.
6799     // This transform is not safe in general because we are reducing the number
6800     // of rounding steps.
6801     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6802       if (N0.getOpcode() == ISD::FMUL) {
6803         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6804         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6805
6806         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6807         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6808           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6809                                        SDValue(CFP01, 0),
6810                                        DAG.getConstantFP(1.0, VT));
6811           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6812         }
6813
6814         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6815         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6816             N1.getOperand(0) == N1.getOperand(1) &&
6817             N0.getOperand(0) == N1.getOperand(0)) {
6818           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6819                                        SDValue(CFP01, 0),
6820                                        DAG.getConstantFP(2.0, VT));
6821           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6822                              N0.getOperand(0), NewCFP);
6823         }
6824       }
6825
6826       if (N1.getOpcode() == ISD::FMUL) {
6827         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6828         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6829
6830         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6831         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6832           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6833                                        SDValue(CFP11, 0),
6834                                        DAG.getConstantFP(1.0, VT));
6835           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6836         }
6837
6838         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6839         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6840             N0.getOperand(0) == N0.getOperand(1) &&
6841             N1.getOperand(0) == N0.getOperand(0)) {
6842           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6843                                        SDValue(CFP11, 0),
6844                                        DAG.getConstantFP(2.0, VT));
6845           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6846         }
6847       }
6848
6849       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6850         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6851         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6852         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6853             (N0.getOperand(0) == N1))
6854           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6855                              N1, DAG.getConstantFP(3.0, VT));
6856       }
6857
6858       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6859         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6860         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6861         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6862             N1.getOperand(0) == N0)
6863           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6864                              N0, DAG.getConstantFP(3.0, VT));
6865       }
6866
6867       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6868       if (AllowNewConst &&
6869           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6870           N0.getOperand(0) == N0.getOperand(1) &&
6871           N1.getOperand(0) == N1.getOperand(1) &&
6872           N0.getOperand(0) == N1.getOperand(0))
6873         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6874                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6875     }
6876   } // enable-unsafe-fp-math
6877
6878   // FADD -> FMA combines:
6879   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6880       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6881       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6882
6883     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6884     if (N0.getOpcode() == ISD::FMUL &&
6885         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6886       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6887                          N0.getOperand(0), N0.getOperand(1), N1);
6888
6889     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6890     // Note: Commutes FADD operands.
6891     if (N1.getOpcode() == ISD::FMUL &&
6892         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6893       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6894                          N1.getOperand(0), N1.getOperand(1), N0);
6895   }
6896
6897   return SDValue();
6898 }
6899
6900 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6901   SDValue N0 = N->getOperand(0);
6902   SDValue N1 = N->getOperand(1);
6903   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6904   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6905   EVT VT = N->getValueType(0);
6906   SDLoc dl(N);
6907   const TargetOptions &Options = DAG.getTarget().Options;
6908
6909   // fold vector ops
6910   if (VT.isVector()) {
6911     SDValue FoldedVOp = SimplifyVBinOp(N);
6912     if (FoldedVOp.getNode()) return FoldedVOp;
6913   }
6914
6915   // fold (fsub c1, c2) -> c1-c2
6916   if (N0CFP && N1CFP)
6917     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6918
6919   // fold (fsub A, (fneg B)) -> (fadd A, B)
6920   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6921     return DAG.getNode(ISD::FADD, dl, VT, N0,
6922                        GetNegatedExpression(N1, DAG, LegalOperations));
6923
6924   // If 'unsafe math' is enabled, fold lots of things.
6925   if (Options.UnsafeFPMath) {
6926     // (fsub A, 0) -> A
6927     if (N1CFP && N1CFP->getValueAPF().isZero())
6928       return N0;
6929
6930     // (fsub 0, B) -> -B
6931     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6932       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6933         return GetNegatedExpression(N1, DAG, LegalOperations);
6934       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6935         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6936     }
6937
6938     // (fsub x, x) -> 0.0
6939     if (N0 == N1)
6940       return DAG.getConstantFP(0.0f, VT);
6941
6942     // (fsub x, (fadd x, y)) -> (fneg y)
6943     // (fsub x, (fadd y, x)) -> (fneg y)
6944     if (N1.getOpcode() == ISD::FADD) {
6945       SDValue N10 = N1->getOperand(0);
6946       SDValue N11 = N1->getOperand(1);
6947
6948       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6949         return GetNegatedExpression(N11, DAG, LegalOperations);
6950
6951       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6952         return GetNegatedExpression(N10, DAG, LegalOperations);
6953     }
6954   }
6955
6956   // FSUB -> FMA combines:
6957   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6958       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6959       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6960
6961     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6962     if (N0.getOpcode() == ISD::FMUL &&
6963         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6964       return DAG.getNode(ISD::FMA, dl, VT,
6965                          N0.getOperand(0), N0.getOperand(1),
6966                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6967
6968     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6969     // Note: Commutes FSUB operands.
6970     if (N1.getOpcode() == ISD::FMUL &&
6971         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6972       return DAG.getNode(ISD::FMA, dl, VT,
6973                          DAG.getNode(ISD::FNEG, dl, VT,
6974                          N1.getOperand(0)),
6975                          N1.getOperand(1), N0);
6976
6977     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6978     if (N0.getOpcode() == ISD::FNEG &&
6979         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6980         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6981             TLI.enableAggressiveFMAFusion(VT))) {
6982       SDValue N00 = N0.getOperand(0).getOperand(0);
6983       SDValue N01 = N0.getOperand(0).getOperand(1);
6984       return DAG.getNode(ISD::FMA, dl, VT,
6985                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6986                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6987     }
6988   }
6989
6990   return SDValue();
6991 }
6992
6993 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6994   SDValue N0 = N->getOperand(0);
6995   SDValue N1 = N->getOperand(1);
6996   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6997   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6998   EVT VT = N->getValueType(0);
6999   const TargetOptions &Options = DAG.getTarget().Options;
7000
7001   // fold vector ops
7002   if (VT.isVector()) {
7003     // This just handles C1 * C2 for vectors. Other vector folds are below.
7004     SDValue FoldedVOp = SimplifyVBinOp(N);
7005     if (FoldedVOp.getNode())
7006       return FoldedVOp;
7007     // Canonicalize vector constant to RHS.
7008     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7009         N1.getOpcode() != ISD::BUILD_VECTOR)
7010       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7011         if (BV0->isConstant())
7012           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7013   }
7014
7015   // fold (fmul c1, c2) -> c1*c2
7016   if (N0CFP && N1CFP)
7017     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7018
7019   // canonicalize constant to RHS
7020   if (N0CFP && !N1CFP)
7021     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7022
7023   // fold (fmul A, 1.0) -> A
7024   if (N1CFP && N1CFP->isExactlyValue(1.0))
7025     return N0;
7026
7027   if (Options.UnsafeFPMath) {
7028     // fold (fmul A, 0) -> 0
7029     if (N1CFP && N1CFP->getValueAPF().isZero())
7030       return N1;
7031
7032     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7033     if (N0.getOpcode() == ISD::FMUL) {
7034       // Fold scalars or any vector constants (not just splats).
7035       // This fold is done in general by InstCombine, but extra fmul insts
7036       // may have been generated during lowering.
7037       SDValue N01 = N0.getOperand(1);
7038       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7039       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7040       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7041           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7042         SDLoc SL(N);
7043         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7044         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7045       }
7046     }
7047
7048     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7049     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7050     // during an early run of DAGCombiner can prevent folding with fmuls
7051     // inserted during lowering.
7052     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7053       SDLoc SL(N);
7054       const SDValue Two = DAG.getConstantFP(2.0, VT);
7055       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7056       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7057     }
7058   }
7059
7060   // fold (fmul X, 2.0) -> (fadd X, X)
7061   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7062     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7063
7064   // fold (fmul X, -1.0) -> (fneg X)
7065   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7066     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7067       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7068
7069   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7070   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7071     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7072       // Both can be negated for free, check to see if at least one is cheaper
7073       // negated.
7074       if (LHSNeg == 2 || RHSNeg == 2)
7075         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7076                            GetNegatedExpression(N0, DAG, LegalOperations),
7077                            GetNegatedExpression(N1, DAG, LegalOperations));
7078     }
7079   }
7080
7081   return SDValue();
7082 }
7083
7084 SDValue DAGCombiner::visitFMA(SDNode *N) {
7085   SDValue N0 = N->getOperand(0);
7086   SDValue N1 = N->getOperand(1);
7087   SDValue N2 = N->getOperand(2);
7088   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7089   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7090   EVT VT = N->getValueType(0);
7091   SDLoc dl(N);
7092   const TargetOptions &Options = DAG.getTarget().Options;
7093
7094   // Constant fold FMA.
7095   if (isa<ConstantFPSDNode>(N0) &&
7096       isa<ConstantFPSDNode>(N1) &&
7097       isa<ConstantFPSDNode>(N2)) {
7098     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7099   }
7100
7101   if (Options.UnsafeFPMath) {
7102     if (N0CFP && N0CFP->isZero())
7103       return N2;
7104     if (N1CFP && N1CFP->isZero())
7105       return N2;
7106   }
7107   if (N0CFP && N0CFP->isExactlyValue(1.0))
7108     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7109   if (N1CFP && N1CFP->isExactlyValue(1.0))
7110     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7111
7112   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7113   if (N0CFP && !N1CFP)
7114     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7115
7116   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7117   if (Options.UnsafeFPMath && N1CFP &&
7118       N2.getOpcode() == ISD::FMUL &&
7119       N0 == N2.getOperand(0) &&
7120       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7121     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7122                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7123   }
7124
7125
7126   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7127   if (Options.UnsafeFPMath &&
7128       N0.getOpcode() == ISD::FMUL && N1CFP &&
7129       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7130     return DAG.getNode(ISD::FMA, dl, VT,
7131                        N0.getOperand(0),
7132                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7133                        N2);
7134   }
7135
7136   // (fma x, 1, y) -> (fadd x, y)
7137   // (fma x, -1, y) -> (fadd (fneg x), y)
7138   if (N1CFP) {
7139     if (N1CFP->isExactlyValue(1.0))
7140       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7141
7142     if (N1CFP->isExactlyValue(-1.0) &&
7143         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7144       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7145       AddToWorklist(RHSNeg.getNode());
7146       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7147     }
7148   }
7149
7150   // (fma x, c, x) -> (fmul x, (c+1))
7151   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7152     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7153                        DAG.getNode(ISD::FADD, dl, VT,
7154                                    N1, DAG.getConstantFP(1.0, VT)));
7155
7156   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7157   if (Options.UnsafeFPMath && N1CFP &&
7158       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7159     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7160                        DAG.getNode(ISD::FADD, dl, VT,
7161                                    N1, DAG.getConstantFP(-1.0, VT)));
7162
7163
7164   return SDValue();
7165 }
7166
7167 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7168   SDValue N0 = N->getOperand(0);
7169   SDValue N1 = N->getOperand(1);
7170   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7171   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7172   EVT VT = N->getValueType(0);
7173   SDLoc DL(N);
7174   const TargetOptions &Options = DAG.getTarget().Options;
7175
7176   // fold vector ops
7177   if (VT.isVector()) {
7178     SDValue FoldedVOp = SimplifyVBinOp(N);
7179     if (FoldedVOp.getNode()) return FoldedVOp;
7180   }
7181
7182   // fold (fdiv c1, c2) -> c1/c2
7183   if (N0CFP && N1CFP)
7184     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7185
7186   if (Options.UnsafeFPMath) {
7187     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7188     if (N1CFP) {
7189       // Compute the reciprocal 1.0 / c2.
7190       APFloat N1APF = N1CFP->getValueAPF();
7191       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7192       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7193       // Only do the transform if the reciprocal is a legal fp immediate that
7194       // isn't too nasty (eg NaN, denormal, ...).
7195       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7196           (!LegalOperations ||
7197            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7198            // backend)... we should handle this gracefully after Legalize.
7199            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7200            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7201            TLI.isFPImmLegal(Recip, VT)))
7202         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7203                            DAG.getConstantFP(Recip, VT));
7204     }
7205
7206     // If this FDIV is part of a reciprocal square root, it may be folded
7207     // into a target-specific square root estimate instruction.
7208     if (N1.getOpcode() == ISD::FSQRT) {
7209       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7210         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7211       }
7212     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7213                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7214       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7215         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7216         AddToWorklist(RV.getNode());
7217         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7218       }
7219     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7220                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7221       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7222         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7223         AddToWorklist(RV.getNode());
7224         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7225       }
7226     } else if (N1.getOpcode() == ISD::FMUL) {
7227       // Look through an FMUL. Even though this won't remove the FDIV directly,
7228       // it's still worthwhile to get rid of the FSQRT if possible.
7229       SDValue SqrtOp;
7230       SDValue OtherOp;
7231       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7232         SqrtOp = N1.getOperand(0);
7233         OtherOp = N1.getOperand(1);
7234       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7235         SqrtOp = N1.getOperand(1);
7236         OtherOp = N1.getOperand(0);
7237       }
7238       if (SqrtOp.getNode()) {
7239         // We found a FSQRT, so try to make this fold:
7240         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7241         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7242           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7243           AddToWorklist(RV.getNode());
7244           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7245         }
7246       }
7247     }
7248
7249     // Fold into a reciprocal estimate and multiply instead of a real divide.
7250     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7251       AddToWorklist(RV.getNode());
7252       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7253     }
7254   }
7255
7256   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7257   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7258     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7259       // Both can be negated for free, check to see if at least one is cheaper
7260       // negated.
7261       if (LHSNeg == 2 || RHSNeg == 2)
7262         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7263                            GetNegatedExpression(N0, DAG, LegalOperations),
7264                            GetNegatedExpression(N1, DAG, LegalOperations));
7265     }
7266   }
7267
7268   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7269   // reciprocal.
7270   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7271   // Notice that this is not always beneficial. One reason is different target
7272   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7273   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7274   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7275   if (Options.UnsafeFPMath) {
7276     // Skip if current node is a reciprocal.
7277     if (N0CFP && N0CFP->isExactlyValue(1.0))
7278       return SDValue();
7279
7280     SmallVector<SDNode *, 4> Users;
7281     // Find all FDIV users of the same divisor.
7282     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7283                               UE = N1.getNode()->use_end();
7284          UI != UE; ++UI) {
7285       SDNode *User = UI.getUse().getUser();
7286       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7287         Users.push_back(User);
7288     }
7289
7290     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7291       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7292       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7293
7294       // Dividend / Divisor -> Dividend * Reciprocal
7295       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7296         if ((*I)->getOperand(0) != FPOne) {
7297           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7298                                         (*I)->getOperand(0), Reciprocal);
7299           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7300         }
7301       }
7302       return SDValue();
7303     }
7304   }
7305
7306   return SDValue();
7307 }
7308
7309 SDValue DAGCombiner::visitFREM(SDNode *N) {
7310   SDValue N0 = N->getOperand(0);
7311   SDValue N1 = N->getOperand(1);
7312   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7313   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7314   EVT VT = N->getValueType(0);
7315
7316   // fold (frem c1, c2) -> fmod(c1,c2)
7317   if (N0CFP && N1CFP)
7318     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7319
7320   return SDValue();
7321 }
7322
7323 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7324   if (DAG.getTarget().Options.UnsafeFPMath) {
7325     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7326     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7327       EVT VT = RV.getValueType();
7328       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7329       AddToWorklist(RV.getNode());
7330
7331       // Unfortunately, RV is now NaN if the input was exactly 0.
7332       // Select out this case and force the answer to 0.
7333       SDValue Zero = DAG.getConstantFP(0.0, VT);
7334       SDValue ZeroCmp =
7335         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7336                      N->getOperand(0), Zero, ISD::SETEQ);
7337       AddToWorklist(ZeroCmp.getNode());
7338       AddToWorklist(RV.getNode());
7339
7340       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7341                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7342       return RV;
7343     }
7344   }
7345   return SDValue();
7346 }
7347
7348 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7349   SDValue N0 = N->getOperand(0);
7350   SDValue N1 = N->getOperand(1);
7351   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7352   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7353   EVT VT = N->getValueType(0);
7354
7355   if (N0CFP && N1CFP)  // Constant fold
7356     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7357
7358   if (N1CFP) {
7359     const APFloat& V = N1CFP->getValueAPF();
7360     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7361     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7362     if (!V.isNegative()) {
7363       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7364         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7365     } else {
7366       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7367         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7368                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7369     }
7370   }
7371
7372   // copysign(fabs(x), y) -> copysign(x, y)
7373   // copysign(fneg(x), y) -> copysign(x, y)
7374   // copysign(copysign(x,z), y) -> copysign(x, y)
7375   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7376       N0.getOpcode() == ISD::FCOPYSIGN)
7377     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7378                        N0.getOperand(0), N1);
7379
7380   // copysign(x, abs(y)) -> abs(x)
7381   if (N1.getOpcode() == ISD::FABS)
7382     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7383
7384   // copysign(x, copysign(y,z)) -> copysign(x, z)
7385   if (N1.getOpcode() == ISD::FCOPYSIGN)
7386     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7387                        N0, N1.getOperand(1));
7388
7389   // copysign(x, fp_extend(y)) -> copysign(x, y)
7390   // copysign(x, fp_round(y)) -> copysign(x, y)
7391   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7392     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7393                        N0, N1.getOperand(0));
7394
7395   return SDValue();
7396 }
7397
7398 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7399   SDValue N0 = N->getOperand(0);
7400   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7401   EVT VT = N->getValueType(0);
7402   EVT OpVT = N0.getValueType();
7403
7404   // fold (sint_to_fp c1) -> c1fp
7405   if (N0C &&
7406       // ...but only if the target supports immediate floating-point values
7407       (!LegalOperations ||
7408        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7409     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7410
7411   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7412   // but UINT_TO_FP is legal on this target, try to convert.
7413   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7414       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7415     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7416     if (DAG.SignBitIsZero(N0))
7417       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7418   }
7419
7420   // The next optimizations are desirable only if SELECT_CC can be lowered.
7421   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7422     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7423     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7424         !VT.isVector() &&
7425         (!LegalOperations ||
7426          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7427       SDValue Ops[] =
7428         { N0.getOperand(0), N0.getOperand(1),
7429           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7430           N0.getOperand(2) };
7431       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7432     }
7433
7434     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7435     //      (select_cc x, y, 1.0, 0.0,, cc)
7436     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7437         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7438         (!LegalOperations ||
7439          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7440       SDValue Ops[] =
7441         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7442           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7443           N0.getOperand(0).getOperand(2) };
7444       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7445     }
7446   }
7447
7448   return SDValue();
7449 }
7450
7451 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7452   SDValue N0 = N->getOperand(0);
7453   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7454   EVT VT = N->getValueType(0);
7455   EVT OpVT = N0.getValueType();
7456
7457   // fold (uint_to_fp c1) -> c1fp
7458   if (N0C &&
7459       // ...but only if the target supports immediate floating-point values
7460       (!LegalOperations ||
7461        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7462     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7463
7464   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7465   // but SINT_TO_FP is legal on this target, try to convert.
7466   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7467       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7468     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7469     if (DAG.SignBitIsZero(N0))
7470       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7471   }
7472
7473   // The next optimizations are desirable only if SELECT_CC can be lowered.
7474   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7475     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7476
7477     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7478         (!LegalOperations ||
7479          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7480       SDValue Ops[] =
7481         { N0.getOperand(0), N0.getOperand(1),
7482           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7483           N0.getOperand(2) };
7484       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7485     }
7486   }
7487
7488   return SDValue();
7489 }
7490
7491 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7492   SDValue N0 = N->getOperand(0);
7493   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7494   EVT VT = N->getValueType(0);
7495
7496   // fold (fp_to_sint c1fp) -> c1
7497   if (N0CFP)
7498     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7499
7500   return SDValue();
7501 }
7502
7503 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7504   SDValue N0 = N->getOperand(0);
7505   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7506   EVT VT = N->getValueType(0);
7507
7508   // fold (fp_to_uint c1fp) -> c1
7509   if (N0CFP)
7510     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7511
7512   return SDValue();
7513 }
7514
7515 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7516   SDValue N0 = N->getOperand(0);
7517   SDValue N1 = N->getOperand(1);
7518   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7519   EVT VT = N->getValueType(0);
7520
7521   // fold (fp_round c1fp) -> c1fp
7522   if (N0CFP)
7523     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7524
7525   // fold (fp_round (fp_extend x)) -> x
7526   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7527     return N0.getOperand(0);
7528
7529   // fold (fp_round (fp_round x)) -> (fp_round x)
7530   if (N0.getOpcode() == ISD::FP_ROUND) {
7531     // This is a value preserving truncation if both round's are.
7532     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7533                    N0.getNode()->getConstantOperandVal(1) == 1;
7534     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7535                        DAG.getIntPtrConstant(IsTrunc));
7536   }
7537
7538   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7539   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7540     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7541                               N0.getOperand(0), N1);
7542     AddToWorklist(Tmp.getNode());
7543     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7544                        Tmp, N0.getOperand(1));
7545   }
7546
7547   return SDValue();
7548 }
7549
7550 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7551   SDValue N0 = N->getOperand(0);
7552   EVT VT = N->getValueType(0);
7553   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7554   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7555
7556   // fold (fp_round_inreg c1fp) -> c1fp
7557   if (N0CFP && isTypeLegal(EVT)) {
7558     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7559     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7560   }
7561
7562   return SDValue();
7563 }
7564
7565 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7566   SDValue N0 = N->getOperand(0);
7567   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7568   EVT VT = N->getValueType(0);
7569
7570   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7571   if (N->hasOneUse() &&
7572       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7573     return SDValue();
7574
7575   // fold (fp_extend c1fp) -> c1fp
7576   if (N0CFP)
7577     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7578
7579   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7580   // value of X.
7581   if (N0.getOpcode() == ISD::FP_ROUND
7582       && N0.getNode()->getConstantOperandVal(1) == 1) {
7583     SDValue In = N0.getOperand(0);
7584     if (In.getValueType() == VT) return In;
7585     if (VT.bitsLT(In.getValueType()))
7586       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7587                          In, N0.getOperand(1));
7588     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7589   }
7590
7591   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7592   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7593        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7594     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7595     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7596                                      LN0->getChain(),
7597                                      LN0->getBasePtr(), N0.getValueType(),
7598                                      LN0->getMemOperand());
7599     CombineTo(N, ExtLoad);
7600     CombineTo(N0.getNode(),
7601               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7602                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7603               ExtLoad.getValue(1));
7604     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7605   }
7606
7607   return SDValue();
7608 }
7609
7610 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7611   SDValue N0 = N->getOperand(0);
7612   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7613   EVT VT = N->getValueType(0);
7614
7615   // fold (fceil c1) -> fceil(c1)
7616   if (N0CFP)
7617     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7618
7619   return SDValue();
7620 }
7621
7622 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7623   SDValue N0 = N->getOperand(0);
7624   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7625   EVT VT = N->getValueType(0);
7626
7627   // fold (ftrunc c1) -> ftrunc(c1)
7628   if (N0CFP)
7629     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7630
7631   return SDValue();
7632 }
7633
7634 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7635   SDValue N0 = N->getOperand(0);
7636   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7637   EVT VT = N->getValueType(0);
7638
7639   // fold (ffloor c1) -> ffloor(c1)
7640   if (N0CFP)
7641     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7642
7643   return SDValue();
7644 }
7645
7646 // FIXME: FNEG and FABS have a lot in common; refactor.
7647 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7648   SDValue N0 = N->getOperand(0);
7649   EVT VT = N->getValueType(0);
7650
7651   if (VT.isVector()) {
7652     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7653     if (FoldedVOp.getNode()) return FoldedVOp;
7654   }
7655
7656   // Constant fold FNEG.
7657   if (isa<ConstantFPSDNode>(N0))
7658     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7659
7660   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7661                          &DAG.getTarget().Options))
7662     return GetNegatedExpression(N0, DAG, LegalOperations);
7663
7664   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7665   // constant pool values.
7666   if (!TLI.isFNegFree(VT) &&
7667       N0.getOpcode() == ISD::BITCAST &&
7668       N0.getNode()->hasOneUse()) {
7669     SDValue Int = N0.getOperand(0);
7670     EVT IntVT = Int.getValueType();
7671     if (IntVT.isInteger() && !IntVT.isVector()) {
7672       APInt SignMask;
7673       if (N0.getValueType().isVector()) {
7674         // For a vector, get a mask such as 0x80... per scalar element
7675         // and splat it.
7676         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7677         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7678       } else {
7679         // For a scalar, just generate 0x80...
7680         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7681       }
7682       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7683                         DAG.getConstant(SignMask, IntVT));
7684       AddToWorklist(Int.getNode());
7685       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7686     }
7687   }
7688
7689   // (fneg (fmul c, x)) -> (fmul -c, x)
7690   if (N0.getOpcode() == ISD::FMUL) {
7691     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7692     if (CFP1) {
7693       APFloat CVal = CFP1->getValueAPF();
7694       CVal.changeSign();
7695       if (Level >= AfterLegalizeDAG &&
7696           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7697            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7698         return DAG.getNode(
7699             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7700             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7701     }
7702   }
7703
7704   return SDValue();
7705 }
7706
7707 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7708   SDValue N0 = N->getOperand(0);
7709   SDValue N1 = N->getOperand(1);
7710   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7711   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7712
7713   if (N0CFP && N1CFP) {
7714     const APFloat &C0 = N0CFP->getValueAPF();
7715     const APFloat &C1 = N1CFP->getValueAPF();
7716     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7717   }
7718
7719   if (N0CFP) {
7720     EVT VT = N->getValueType(0);
7721     // Canonicalize to constant on RHS.
7722     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7723   }
7724
7725   return SDValue();
7726 }
7727
7728 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7729   SDValue N0 = N->getOperand(0);
7730   SDValue N1 = N->getOperand(1);
7731   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7732   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7733
7734   if (N0CFP && N1CFP) {
7735     const APFloat &C0 = N0CFP->getValueAPF();
7736     const APFloat &C1 = N1CFP->getValueAPF();
7737     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7738   }
7739
7740   if (N0CFP) {
7741     EVT VT = N->getValueType(0);
7742     // Canonicalize to constant on RHS.
7743     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7744   }
7745
7746   return SDValue();
7747 }
7748
7749 SDValue DAGCombiner::visitFABS(SDNode *N) {
7750   SDValue N0 = N->getOperand(0);
7751   EVT VT = N->getValueType(0);
7752
7753   if (VT.isVector()) {
7754     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7755     if (FoldedVOp.getNode()) return FoldedVOp;
7756   }
7757
7758   // fold (fabs c1) -> fabs(c1)
7759   if (isa<ConstantFPSDNode>(N0))
7760     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7761
7762   // fold (fabs (fabs x)) -> (fabs x)
7763   if (N0.getOpcode() == ISD::FABS)
7764     return N->getOperand(0);
7765
7766   // fold (fabs (fneg x)) -> (fabs x)
7767   // fold (fabs (fcopysign x, y)) -> (fabs x)
7768   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7769     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7770
7771   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7772   // constant pool values.
7773   if (!TLI.isFAbsFree(VT) &&
7774       N0.getOpcode() == ISD::BITCAST &&
7775       N0.getNode()->hasOneUse()) {
7776     SDValue Int = N0.getOperand(0);
7777     EVT IntVT = Int.getValueType();
7778     if (IntVT.isInteger() && !IntVT.isVector()) {
7779       APInt SignMask;
7780       if (N0.getValueType().isVector()) {
7781         // For a vector, get a mask such as 0x7f... per scalar element
7782         // and splat it.
7783         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7784         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7785       } else {
7786         // For a scalar, just generate 0x7f...
7787         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7788       }
7789       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7790                         DAG.getConstant(SignMask, IntVT));
7791       AddToWorklist(Int.getNode());
7792       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7793     }
7794   }
7795
7796   return SDValue();
7797 }
7798
7799 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7800   SDValue Chain = N->getOperand(0);
7801   SDValue N1 = N->getOperand(1);
7802   SDValue N2 = N->getOperand(2);
7803
7804   // If N is a constant we could fold this into a fallthrough or unconditional
7805   // branch. However that doesn't happen very often in normal code, because
7806   // Instcombine/SimplifyCFG should have handled the available opportunities.
7807   // If we did this folding here, it would be necessary to update the
7808   // MachineBasicBlock CFG, which is awkward.
7809
7810   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7811   // on the target.
7812   if (N1.getOpcode() == ISD::SETCC &&
7813       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7814                                    N1.getOperand(0).getValueType())) {
7815     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7816                        Chain, N1.getOperand(2),
7817                        N1.getOperand(0), N1.getOperand(1), N2);
7818   }
7819
7820   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7821       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7822        (N1.getOperand(0).hasOneUse() &&
7823         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7824     SDNode *Trunc = nullptr;
7825     if (N1.getOpcode() == ISD::TRUNCATE) {
7826       // Look pass the truncate.
7827       Trunc = N1.getNode();
7828       N1 = N1.getOperand(0);
7829     }
7830
7831     // Match this pattern so that we can generate simpler code:
7832     //
7833     //   %a = ...
7834     //   %b = and i32 %a, 2
7835     //   %c = srl i32 %b, 1
7836     //   brcond i32 %c ...
7837     //
7838     // into
7839     //
7840     //   %a = ...
7841     //   %b = and i32 %a, 2
7842     //   %c = setcc eq %b, 0
7843     //   brcond %c ...
7844     //
7845     // This applies only when the AND constant value has one bit set and the
7846     // SRL constant is equal to the log2 of the AND constant. The back-end is
7847     // smart enough to convert the result into a TEST/JMP sequence.
7848     SDValue Op0 = N1.getOperand(0);
7849     SDValue Op1 = N1.getOperand(1);
7850
7851     if (Op0.getOpcode() == ISD::AND &&
7852         Op1.getOpcode() == ISD::Constant) {
7853       SDValue AndOp1 = Op0.getOperand(1);
7854
7855       if (AndOp1.getOpcode() == ISD::Constant) {
7856         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7857
7858         if (AndConst.isPowerOf2() &&
7859             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7860           SDValue SetCC =
7861             DAG.getSetCC(SDLoc(N),
7862                          getSetCCResultType(Op0.getValueType()),
7863                          Op0, DAG.getConstant(0, Op0.getValueType()),
7864                          ISD::SETNE);
7865
7866           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7867                                           MVT::Other, Chain, SetCC, N2);
7868           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7869           // will convert it back to (X & C1) >> C2.
7870           CombineTo(N, NewBRCond, false);
7871           // Truncate is dead.
7872           if (Trunc)
7873             deleteAndRecombine(Trunc);
7874           // Replace the uses of SRL with SETCC
7875           WorklistRemover DeadNodes(*this);
7876           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7877           deleteAndRecombine(N1.getNode());
7878           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7879         }
7880       }
7881     }
7882
7883     if (Trunc)
7884       // Restore N1 if the above transformation doesn't match.
7885       N1 = N->getOperand(1);
7886   }
7887
7888   // Transform br(xor(x, y)) -> br(x != y)
7889   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7890   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7891     SDNode *TheXor = N1.getNode();
7892     SDValue Op0 = TheXor->getOperand(0);
7893     SDValue Op1 = TheXor->getOperand(1);
7894     if (Op0.getOpcode() == Op1.getOpcode()) {
7895       // Avoid missing important xor optimizations.
7896       SDValue Tmp = visitXOR(TheXor);
7897       if (Tmp.getNode()) {
7898         if (Tmp.getNode() != TheXor) {
7899           DEBUG(dbgs() << "\nReplacing.8 ";
7900                 TheXor->dump(&DAG);
7901                 dbgs() << "\nWith: ";
7902                 Tmp.getNode()->dump(&DAG);
7903                 dbgs() << '\n');
7904           WorklistRemover DeadNodes(*this);
7905           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7906           deleteAndRecombine(TheXor);
7907           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7908                              MVT::Other, Chain, Tmp, N2);
7909         }
7910
7911         // visitXOR has changed XOR's operands or replaced the XOR completely,
7912         // bail out.
7913         return SDValue(N, 0);
7914       }
7915     }
7916
7917     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7918       bool Equal = false;
7919       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7920         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7921             Op0.getOpcode() == ISD::XOR) {
7922           TheXor = Op0.getNode();
7923           Equal = true;
7924         }
7925
7926       EVT SetCCVT = N1.getValueType();
7927       if (LegalTypes)
7928         SetCCVT = getSetCCResultType(SetCCVT);
7929       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7930                                    SetCCVT,
7931                                    Op0, Op1,
7932                                    Equal ? ISD::SETEQ : ISD::SETNE);
7933       // Replace the uses of XOR with SETCC
7934       WorklistRemover DeadNodes(*this);
7935       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7936       deleteAndRecombine(N1.getNode());
7937       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7938                          MVT::Other, Chain, SetCC, N2);
7939     }
7940   }
7941
7942   return SDValue();
7943 }
7944
7945 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7946 //
7947 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7948   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7949   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7950
7951   // If N is a constant we could fold this into a fallthrough or unconditional
7952   // branch. However that doesn't happen very often in normal code, because
7953   // Instcombine/SimplifyCFG should have handled the available opportunities.
7954   // If we did this folding here, it would be necessary to update the
7955   // MachineBasicBlock CFG, which is awkward.
7956
7957   // Use SimplifySetCC to simplify SETCC's.
7958   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7959                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7960                                false);
7961   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7962
7963   // fold to a simpler setcc
7964   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7965     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7966                        N->getOperand(0), Simp.getOperand(2),
7967                        Simp.getOperand(0), Simp.getOperand(1),
7968                        N->getOperand(4));
7969
7970   return SDValue();
7971 }
7972
7973 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7974 /// and that N may be folded in the load / store addressing mode.
7975 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7976                                     SelectionDAG &DAG,
7977                                     const TargetLowering &TLI) {
7978   EVT VT;
7979   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7980     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7981       return false;
7982     VT = Use->getValueType(0);
7983   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7984     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7985       return false;
7986     VT = ST->getValue().getValueType();
7987   } else
7988     return false;
7989
7990   TargetLowering::AddrMode AM;
7991   if (N->getOpcode() == ISD::ADD) {
7992     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7993     if (Offset)
7994       // [reg +/- imm]
7995       AM.BaseOffs = Offset->getSExtValue();
7996     else
7997       // [reg +/- reg]
7998       AM.Scale = 1;
7999   } else if (N->getOpcode() == ISD::SUB) {
8000     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8001     if (Offset)
8002       // [reg +/- imm]
8003       AM.BaseOffs = -Offset->getSExtValue();
8004     else
8005       // [reg +/- reg]
8006       AM.Scale = 1;
8007   } else
8008     return false;
8009
8010   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8011 }
8012
8013 /// Try turning a load/store into a pre-indexed load/store when the base
8014 /// pointer is an add or subtract and it has other uses besides the load/store.
8015 /// After the transformation, the new indexed load/store has effectively folded
8016 /// the add/subtract in and all of its other uses are redirected to the
8017 /// new load/store.
8018 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8019   if (Level < AfterLegalizeDAG)
8020     return false;
8021
8022   bool isLoad = true;
8023   SDValue Ptr;
8024   EVT VT;
8025   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8026     if (LD->isIndexed())
8027       return false;
8028     VT = LD->getMemoryVT();
8029     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8030         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8031       return false;
8032     Ptr = LD->getBasePtr();
8033   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8034     if (ST->isIndexed())
8035       return false;
8036     VT = ST->getMemoryVT();
8037     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8038         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8039       return false;
8040     Ptr = ST->getBasePtr();
8041     isLoad = false;
8042   } else {
8043     return false;
8044   }
8045
8046   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8047   // out.  There is no reason to make this a preinc/predec.
8048   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8049       Ptr.getNode()->hasOneUse())
8050     return false;
8051
8052   // Ask the target to do addressing mode selection.
8053   SDValue BasePtr;
8054   SDValue Offset;
8055   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8056   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8057     return false;
8058
8059   // Backends without true r+i pre-indexed forms may need to pass a
8060   // constant base with a variable offset so that constant coercion
8061   // will work with the patterns in canonical form.
8062   bool Swapped = false;
8063   if (isa<ConstantSDNode>(BasePtr)) {
8064     std::swap(BasePtr, Offset);
8065     Swapped = true;
8066   }
8067
8068   // Don't create a indexed load / store with zero offset.
8069   if (isa<ConstantSDNode>(Offset) &&
8070       cast<ConstantSDNode>(Offset)->isNullValue())
8071     return false;
8072
8073   // Try turning it into a pre-indexed load / store except when:
8074   // 1) The new base ptr is a frame index.
8075   // 2) If N is a store and the new base ptr is either the same as or is a
8076   //    predecessor of the value being stored.
8077   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8078   //    that would create a cycle.
8079   // 4) All uses are load / store ops that use it as old base ptr.
8080
8081   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8082   // (plus the implicit offset) to a register to preinc anyway.
8083   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8084     return false;
8085
8086   // Check #2.
8087   if (!isLoad) {
8088     SDValue Val = cast<StoreSDNode>(N)->getValue();
8089     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8090       return false;
8091   }
8092
8093   // If the offset is a constant, there may be other adds of constants that
8094   // can be folded with this one. We should do this to avoid having to keep
8095   // a copy of the original base pointer.
8096   SmallVector<SDNode *, 16> OtherUses;
8097   if (isa<ConstantSDNode>(Offset))
8098     for (SDNode *Use : BasePtr.getNode()->uses()) {
8099       if (Use == Ptr.getNode())
8100         continue;
8101
8102       if (Use->isPredecessorOf(N))
8103         continue;
8104
8105       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8106         OtherUses.clear();
8107         break;
8108       }
8109
8110       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8111       if (Op1.getNode() == BasePtr.getNode())
8112         std::swap(Op0, Op1);
8113       assert(Op0.getNode() == BasePtr.getNode() &&
8114              "Use of ADD/SUB but not an operand");
8115
8116       if (!isa<ConstantSDNode>(Op1)) {
8117         OtherUses.clear();
8118         break;
8119       }
8120
8121       // FIXME: In some cases, we can be smarter about this.
8122       if (Op1.getValueType() != Offset.getValueType()) {
8123         OtherUses.clear();
8124         break;
8125       }
8126
8127       OtherUses.push_back(Use);
8128     }
8129
8130   if (Swapped)
8131     std::swap(BasePtr, Offset);
8132
8133   // Now check for #3 and #4.
8134   bool RealUse = false;
8135
8136   // Caches for hasPredecessorHelper
8137   SmallPtrSet<const SDNode *, 32> Visited;
8138   SmallVector<const SDNode *, 16> Worklist;
8139
8140   for (SDNode *Use : Ptr.getNode()->uses()) {
8141     if (Use == N)
8142       continue;
8143     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8144       return false;
8145
8146     // If Ptr may be folded in addressing mode of other use, then it's
8147     // not profitable to do this transformation.
8148     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8149       RealUse = true;
8150   }
8151
8152   if (!RealUse)
8153     return false;
8154
8155   SDValue Result;
8156   if (isLoad)
8157     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8158                                 BasePtr, Offset, AM);
8159   else
8160     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8161                                  BasePtr, Offset, AM);
8162   ++PreIndexedNodes;
8163   ++NodesCombined;
8164   DEBUG(dbgs() << "\nReplacing.4 ";
8165         N->dump(&DAG);
8166         dbgs() << "\nWith: ";
8167         Result.getNode()->dump(&DAG);
8168         dbgs() << '\n');
8169   WorklistRemover DeadNodes(*this);
8170   if (isLoad) {
8171     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8172     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8173   } else {
8174     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8175   }
8176
8177   // Finally, since the node is now dead, remove it from the graph.
8178   deleteAndRecombine(N);
8179
8180   if (Swapped)
8181     std::swap(BasePtr, Offset);
8182
8183   // Replace other uses of BasePtr that can be updated to use Ptr
8184   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8185     unsigned OffsetIdx = 1;
8186     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8187       OffsetIdx = 0;
8188     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8189            BasePtr.getNode() && "Expected BasePtr operand");
8190
8191     // We need to replace ptr0 in the following expression:
8192     //   x0 * offset0 + y0 * ptr0 = t0
8193     // knowing that
8194     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8195     //
8196     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8197     // indexed load/store and the expresion that needs to be re-written.
8198     //
8199     // Therefore, we have:
8200     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8201
8202     ConstantSDNode *CN =
8203       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8204     int X0, X1, Y0, Y1;
8205     APInt Offset0 = CN->getAPIntValue();
8206     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8207
8208     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8209     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8210     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8211     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8212
8213     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8214
8215     APInt CNV = Offset0;
8216     if (X0 < 0) CNV = -CNV;
8217     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8218     else CNV = CNV - Offset1;
8219
8220     // We can now generate the new expression.
8221     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8222     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8223
8224     SDValue NewUse = DAG.getNode(Opcode,
8225                                  SDLoc(OtherUses[i]),
8226                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8227     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8228     deleteAndRecombine(OtherUses[i]);
8229   }
8230
8231   // Replace the uses of Ptr with uses of the updated base value.
8232   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8233   deleteAndRecombine(Ptr.getNode());
8234
8235   return true;
8236 }
8237
8238 /// Try to combine a load/store with a add/sub of the base pointer node into a
8239 /// post-indexed load/store. The transformation folded the add/subtract into the
8240 /// new indexed load/store effectively and all of its uses are redirected to the
8241 /// new load/store.
8242 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8243   if (Level < AfterLegalizeDAG)
8244     return false;
8245
8246   bool isLoad = true;
8247   SDValue Ptr;
8248   EVT VT;
8249   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8250     if (LD->isIndexed())
8251       return false;
8252     VT = LD->getMemoryVT();
8253     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8254         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8255       return false;
8256     Ptr = LD->getBasePtr();
8257   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8258     if (ST->isIndexed())
8259       return false;
8260     VT = ST->getMemoryVT();
8261     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8262         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8263       return false;
8264     Ptr = ST->getBasePtr();
8265     isLoad = false;
8266   } else {
8267     return false;
8268   }
8269
8270   if (Ptr.getNode()->hasOneUse())
8271     return false;
8272
8273   for (SDNode *Op : Ptr.getNode()->uses()) {
8274     if (Op == N ||
8275         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8276       continue;
8277
8278     SDValue BasePtr;
8279     SDValue Offset;
8280     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8281     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8282       // Don't create a indexed load / store with zero offset.
8283       if (isa<ConstantSDNode>(Offset) &&
8284           cast<ConstantSDNode>(Offset)->isNullValue())
8285         continue;
8286
8287       // Try turning it into a post-indexed load / store except when
8288       // 1) All uses are load / store ops that use it as base ptr (and
8289       //    it may be folded as addressing mmode).
8290       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8291       //    nor a successor of N. Otherwise, if Op is folded that would
8292       //    create a cycle.
8293
8294       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8295         continue;
8296
8297       // Check for #1.
8298       bool TryNext = false;
8299       for (SDNode *Use : BasePtr.getNode()->uses()) {
8300         if (Use == Ptr.getNode())
8301           continue;
8302
8303         // If all the uses are load / store addresses, then don't do the
8304         // transformation.
8305         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8306           bool RealUse = false;
8307           for (SDNode *UseUse : Use->uses()) {
8308             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8309               RealUse = true;
8310           }
8311
8312           if (!RealUse) {
8313             TryNext = true;
8314             break;
8315           }
8316         }
8317       }
8318
8319       if (TryNext)
8320         continue;
8321
8322       // Check for #2
8323       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8324         SDValue Result = isLoad
8325           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8326                                BasePtr, Offset, AM)
8327           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8328                                 BasePtr, Offset, AM);
8329         ++PostIndexedNodes;
8330         ++NodesCombined;
8331         DEBUG(dbgs() << "\nReplacing.5 ";
8332               N->dump(&DAG);
8333               dbgs() << "\nWith: ";
8334               Result.getNode()->dump(&DAG);
8335               dbgs() << '\n');
8336         WorklistRemover DeadNodes(*this);
8337         if (isLoad) {
8338           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8339           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8340         } else {
8341           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8342         }
8343
8344         // Finally, since the node is now dead, remove it from the graph.
8345         deleteAndRecombine(N);
8346
8347         // Replace the uses of Use with uses of the updated base value.
8348         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8349                                       Result.getValue(isLoad ? 1 : 0));
8350         deleteAndRecombine(Op);
8351         return true;
8352       }
8353     }
8354   }
8355
8356   return false;
8357 }
8358
8359 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8360 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8361   ISD::MemIndexedMode AM = LD->getAddressingMode();
8362   assert(AM != ISD::UNINDEXED);
8363   SDValue BP = LD->getOperand(1);
8364   SDValue Inc = LD->getOperand(2);
8365
8366   // Some backends use TargetConstants for load offsets, but don't expect
8367   // TargetConstants in general ADD nodes. We can convert these constants into
8368   // regular Constants (if the constant is not opaque).
8369   assert((Inc.getOpcode() != ISD::TargetConstant ||
8370           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8371          "Cannot split out indexing using opaque target constants");
8372   if (Inc.getOpcode() == ISD::TargetConstant) {
8373     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8374     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8375                           ConstInc->getValueType(0));
8376   }
8377
8378   unsigned Opc =
8379       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8380   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8381 }
8382
8383 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8384   LoadSDNode *LD  = cast<LoadSDNode>(N);
8385   SDValue Chain = LD->getChain();
8386   SDValue Ptr   = LD->getBasePtr();
8387
8388   // If load is not volatile and there are no uses of the loaded value (and
8389   // the updated indexed value in case of indexed loads), change uses of the
8390   // chain value into uses of the chain input (i.e. delete the dead load).
8391   if (!LD->isVolatile()) {
8392     if (N->getValueType(1) == MVT::Other) {
8393       // Unindexed loads.
8394       if (!N->hasAnyUseOfValue(0)) {
8395         // It's not safe to use the two value CombineTo variant here. e.g.
8396         // v1, chain2 = load chain1, loc
8397         // v2, chain3 = load chain2, loc
8398         // v3         = add v2, c
8399         // Now we replace use of chain2 with chain1.  This makes the second load
8400         // isomorphic to the one we are deleting, and thus makes this load live.
8401         DEBUG(dbgs() << "\nReplacing.6 ";
8402               N->dump(&DAG);
8403               dbgs() << "\nWith chain: ";
8404               Chain.getNode()->dump(&DAG);
8405               dbgs() << "\n");
8406         WorklistRemover DeadNodes(*this);
8407         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8408
8409         if (N->use_empty())
8410           deleteAndRecombine(N);
8411
8412         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8413       }
8414     } else {
8415       // Indexed loads.
8416       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8417
8418       // If this load has an opaque TargetConstant offset, then we cannot split
8419       // the indexing into an add/sub directly (that TargetConstant may not be
8420       // valid for a different type of node, and we cannot convert an opaque
8421       // target constant into a regular constant).
8422       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8423                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8424
8425       if (!N->hasAnyUseOfValue(0) &&
8426           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8427         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8428         SDValue Index;
8429         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8430           Index = SplitIndexingFromLoad(LD);
8431           // Try to fold the base pointer arithmetic into subsequent loads and
8432           // stores.
8433           AddUsersToWorklist(N);
8434         } else
8435           Index = DAG.getUNDEF(N->getValueType(1));
8436         DEBUG(dbgs() << "\nReplacing.7 ";
8437               N->dump(&DAG);
8438               dbgs() << "\nWith: ";
8439               Undef.getNode()->dump(&DAG);
8440               dbgs() << " and 2 other values\n");
8441         WorklistRemover DeadNodes(*this);
8442         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8443         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8444         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8445         deleteAndRecombine(N);
8446         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8447       }
8448     }
8449   }
8450
8451   // If this load is directly stored, replace the load value with the stored
8452   // value.
8453   // TODO: Handle store large -> read small portion.
8454   // TODO: Handle TRUNCSTORE/LOADEXT
8455   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8456     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8457       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8458       if (PrevST->getBasePtr() == Ptr &&
8459           PrevST->getValue().getValueType() == N->getValueType(0))
8460       return CombineTo(N, Chain.getOperand(1), Chain);
8461     }
8462   }
8463
8464   // Try to infer better alignment information than the load already has.
8465   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8466     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8467       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8468         SDValue NewLoad =
8469                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8470                               LD->getValueType(0),
8471                               Chain, Ptr, LD->getPointerInfo(),
8472                               LD->getMemoryVT(),
8473                               LD->isVolatile(), LD->isNonTemporal(),
8474                               LD->isInvariant(), Align, LD->getAAInfo());
8475         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8476       }
8477     }
8478   }
8479
8480   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8481                                                   : DAG.getSubtarget().useAA();
8482 #ifndef NDEBUG
8483   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8484       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8485     UseAA = false;
8486 #endif
8487   if (UseAA && LD->isUnindexed()) {
8488     // Walk up chain skipping non-aliasing memory nodes.
8489     SDValue BetterChain = FindBetterChain(N, Chain);
8490
8491     // If there is a better chain.
8492     if (Chain != BetterChain) {
8493       SDValue ReplLoad;
8494
8495       // Replace the chain to void dependency.
8496       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8497         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8498                                BetterChain, Ptr, LD->getMemOperand());
8499       } else {
8500         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8501                                   LD->getValueType(0),
8502                                   BetterChain, Ptr, LD->getMemoryVT(),
8503                                   LD->getMemOperand());
8504       }
8505
8506       // Create token factor to keep old chain connected.
8507       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8508                                   MVT::Other, Chain, ReplLoad.getValue(1));
8509
8510       // Make sure the new and old chains are cleaned up.
8511       AddToWorklist(Token.getNode());
8512
8513       // Replace uses with load result and token factor. Don't add users
8514       // to work list.
8515       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8516     }
8517   }
8518
8519   // Try transforming N to an indexed load.
8520   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8521     return SDValue(N, 0);
8522
8523   // Try to slice up N to more direct loads if the slices are mapped to
8524   // different register banks or pairing can take place.
8525   if (SliceUpLoad(N))
8526     return SDValue(N, 0);
8527
8528   return SDValue();
8529 }
8530
8531 namespace {
8532 /// \brief Helper structure used to slice a load in smaller loads.
8533 /// Basically a slice is obtained from the following sequence:
8534 /// Origin = load Ty1, Base
8535 /// Shift = srl Ty1 Origin, CstTy Amount
8536 /// Inst = trunc Shift to Ty2
8537 ///
8538 /// Then, it will be rewriten into:
8539 /// Slice = load SliceTy, Base + SliceOffset
8540 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8541 ///
8542 /// SliceTy is deduced from the number of bits that are actually used to
8543 /// build Inst.
8544 struct LoadedSlice {
8545   /// \brief Helper structure used to compute the cost of a slice.
8546   struct Cost {
8547     /// Are we optimizing for code size.
8548     bool ForCodeSize;
8549     /// Various cost.
8550     unsigned Loads;
8551     unsigned Truncates;
8552     unsigned CrossRegisterBanksCopies;
8553     unsigned ZExts;
8554     unsigned Shift;
8555
8556     Cost(bool ForCodeSize = false)
8557         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8558           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8559
8560     /// \brief Get the cost of one isolated slice.
8561     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8562         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8563           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8564       EVT TruncType = LS.Inst->getValueType(0);
8565       EVT LoadedType = LS.getLoadedType();
8566       if (TruncType != LoadedType &&
8567           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8568         ZExts = 1;
8569     }
8570
8571     /// \brief Account for slicing gain in the current cost.
8572     /// Slicing provide a few gains like removing a shift or a
8573     /// truncate. This method allows to grow the cost of the original
8574     /// load with the gain from this slice.
8575     void addSliceGain(const LoadedSlice &LS) {
8576       // Each slice saves a truncate.
8577       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8578       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8579                               LS.Inst->getOperand(0).getValueType()))
8580         ++Truncates;
8581       // If there is a shift amount, this slice gets rid of it.
8582       if (LS.Shift)
8583         ++Shift;
8584       // If this slice can merge a cross register bank copy, account for it.
8585       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8586         ++CrossRegisterBanksCopies;
8587     }
8588
8589     Cost &operator+=(const Cost &RHS) {
8590       Loads += RHS.Loads;
8591       Truncates += RHS.Truncates;
8592       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8593       ZExts += RHS.ZExts;
8594       Shift += RHS.Shift;
8595       return *this;
8596     }
8597
8598     bool operator==(const Cost &RHS) const {
8599       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8600              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8601              ZExts == RHS.ZExts && Shift == RHS.Shift;
8602     }
8603
8604     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8605
8606     bool operator<(const Cost &RHS) const {
8607       // Assume cross register banks copies are as expensive as loads.
8608       // FIXME: Do we want some more target hooks?
8609       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8610       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8611       // Unless we are optimizing for code size, consider the
8612       // expensive operation first.
8613       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8614         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8615       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8616              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8617     }
8618
8619     bool operator>(const Cost &RHS) const { return RHS < *this; }
8620
8621     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8622
8623     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8624   };
8625   // The last instruction that represent the slice. This should be a
8626   // truncate instruction.
8627   SDNode *Inst;
8628   // The original load instruction.
8629   LoadSDNode *Origin;
8630   // The right shift amount in bits from the original load.
8631   unsigned Shift;
8632   // The DAG from which Origin came from.
8633   // This is used to get some contextual information about legal types, etc.
8634   SelectionDAG *DAG;
8635
8636   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8637               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8638       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8639
8640   LoadedSlice(const LoadedSlice &LS)
8641       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8642
8643   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8644   /// \return Result is \p BitWidth and has used bits set to 1 and
8645   ///         not used bits set to 0.
8646   APInt getUsedBits() const {
8647     // Reproduce the trunc(lshr) sequence:
8648     // - Start from the truncated value.
8649     // - Zero extend to the desired bit width.
8650     // - Shift left.
8651     assert(Origin && "No original load to compare against.");
8652     unsigned BitWidth = Origin->getValueSizeInBits(0);
8653     assert(Inst && "This slice is not bound to an instruction");
8654     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8655            "Extracted slice is bigger than the whole type!");
8656     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8657     UsedBits.setAllBits();
8658     UsedBits = UsedBits.zext(BitWidth);
8659     UsedBits <<= Shift;
8660     return UsedBits;
8661   }
8662
8663   /// \brief Get the size of the slice to be loaded in bytes.
8664   unsigned getLoadedSize() const {
8665     unsigned SliceSize = getUsedBits().countPopulation();
8666     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8667     return SliceSize / 8;
8668   }
8669
8670   /// \brief Get the type that will be loaded for this slice.
8671   /// Note: This may not be the final type for the slice.
8672   EVT getLoadedType() const {
8673     assert(DAG && "Missing context");
8674     LLVMContext &Ctxt = *DAG->getContext();
8675     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8676   }
8677
8678   /// \brief Get the alignment of the load used for this slice.
8679   unsigned getAlignment() const {
8680     unsigned Alignment = Origin->getAlignment();
8681     unsigned Offset = getOffsetFromBase();
8682     if (Offset != 0)
8683       Alignment = MinAlign(Alignment, Alignment + Offset);
8684     return Alignment;
8685   }
8686
8687   /// \brief Check if this slice can be rewritten with legal operations.
8688   bool isLegal() const {
8689     // An invalid slice is not legal.
8690     if (!Origin || !Inst || !DAG)
8691       return false;
8692
8693     // Offsets are for indexed load only, we do not handle that.
8694     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8695       return false;
8696
8697     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8698
8699     // Check that the type is legal.
8700     EVT SliceType = getLoadedType();
8701     if (!TLI.isTypeLegal(SliceType))
8702       return false;
8703
8704     // Check that the load is legal for this type.
8705     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8706       return false;
8707
8708     // Check that the offset can be computed.
8709     // 1. Check its type.
8710     EVT PtrType = Origin->getBasePtr().getValueType();
8711     if (PtrType == MVT::Untyped || PtrType.isExtended())
8712       return false;
8713
8714     // 2. Check that it fits in the immediate.
8715     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8716       return false;
8717
8718     // 3. Check that the computation is legal.
8719     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8720       return false;
8721
8722     // Check that the zext is legal if it needs one.
8723     EVT TruncateType = Inst->getValueType(0);
8724     if (TruncateType != SliceType &&
8725         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8726       return false;
8727
8728     return true;
8729   }
8730
8731   /// \brief Get the offset in bytes of this slice in the original chunk of
8732   /// bits.
8733   /// \pre DAG != nullptr.
8734   uint64_t getOffsetFromBase() const {
8735     assert(DAG && "Missing context.");
8736     bool IsBigEndian =
8737         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8738     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8739     uint64_t Offset = Shift / 8;
8740     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8741     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8742            "The size of the original loaded type is not a multiple of a"
8743            " byte.");
8744     // If Offset is bigger than TySizeInBytes, it means we are loading all
8745     // zeros. This should have been optimized before in the process.
8746     assert(TySizeInBytes > Offset &&
8747            "Invalid shift amount for given loaded size");
8748     if (IsBigEndian)
8749       Offset = TySizeInBytes - Offset - getLoadedSize();
8750     return Offset;
8751   }
8752
8753   /// \brief Generate the sequence of instructions to load the slice
8754   /// represented by this object and redirect the uses of this slice to
8755   /// this new sequence of instructions.
8756   /// \pre this->Inst && this->Origin are valid Instructions and this
8757   /// object passed the legal check: LoadedSlice::isLegal returned true.
8758   /// \return The last instruction of the sequence used to load the slice.
8759   SDValue loadSlice() const {
8760     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8761     const SDValue &OldBaseAddr = Origin->getBasePtr();
8762     SDValue BaseAddr = OldBaseAddr;
8763     // Get the offset in that chunk of bytes w.r.t. the endianess.
8764     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8765     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8766     if (Offset) {
8767       // BaseAddr = BaseAddr + Offset.
8768       EVT ArithType = BaseAddr.getValueType();
8769       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8770                               DAG->getConstant(Offset, ArithType));
8771     }
8772
8773     // Create the type of the loaded slice according to its size.
8774     EVT SliceType = getLoadedType();
8775
8776     // Create the load for the slice.
8777     SDValue LastInst = DAG->getLoad(
8778         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8779         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8780         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8781     // If the final type is not the same as the loaded type, this means that
8782     // we have to pad with zero. Create a zero extend for that.
8783     EVT FinalType = Inst->getValueType(0);
8784     if (SliceType != FinalType)
8785       LastInst =
8786           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8787     return LastInst;
8788   }
8789
8790   /// \brief Check if this slice can be merged with an expensive cross register
8791   /// bank copy. E.g.,
8792   /// i = load i32
8793   /// f = bitcast i32 i to float
8794   bool canMergeExpensiveCrossRegisterBankCopy() const {
8795     if (!Inst || !Inst->hasOneUse())
8796       return false;
8797     SDNode *Use = *Inst->use_begin();
8798     if (Use->getOpcode() != ISD::BITCAST)
8799       return false;
8800     assert(DAG && "Missing context");
8801     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8802     EVT ResVT = Use->getValueType(0);
8803     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8804     const TargetRegisterClass *ArgRC =
8805         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8806     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8807       return false;
8808
8809     // At this point, we know that we perform a cross-register-bank copy.
8810     // Check if it is expensive.
8811     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8812     // Assume bitcasts are cheap, unless both register classes do not
8813     // explicitly share a common sub class.
8814     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8815       return false;
8816
8817     // Check if it will be merged with the load.
8818     // 1. Check the alignment constraint.
8819     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8820         ResVT.getTypeForEVT(*DAG->getContext()));
8821
8822     if (RequiredAlignment > getAlignment())
8823       return false;
8824
8825     // 2. Check that the load is a legal operation for that type.
8826     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8827       return false;
8828
8829     // 3. Check that we do not have a zext in the way.
8830     if (Inst->getValueType(0) != getLoadedType())
8831       return false;
8832
8833     return true;
8834   }
8835 };
8836 }
8837
8838 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8839 /// \p UsedBits looks like 0..0 1..1 0..0.
8840 static bool areUsedBitsDense(const APInt &UsedBits) {
8841   // If all the bits are one, this is dense!
8842   if (UsedBits.isAllOnesValue())
8843     return true;
8844
8845   // Get rid of the unused bits on the right.
8846   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8847   // Get rid of the unused bits on the left.
8848   if (NarrowedUsedBits.countLeadingZeros())
8849     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8850   // Check that the chunk of bits is completely used.
8851   return NarrowedUsedBits.isAllOnesValue();
8852 }
8853
8854 /// \brief Check whether or not \p First and \p Second are next to each other
8855 /// in memory. This means that there is no hole between the bits loaded
8856 /// by \p First and the bits loaded by \p Second.
8857 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8858                                      const LoadedSlice &Second) {
8859   assert(First.Origin == Second.Origin && First.Origin &&
8860          "Unable to match different memory origins.");
8861   APInt UsedBits = First.getUsedBits();
8862   assert((UsedBits & Second.getUsedBits()) == 0 &&
8863          "Slices are not supposed to overlap.");
8864   UsedBits |= Second.getUsedBits();
8865   return areUsedBitsDense(UsedBits);
8866 }
8867
8868 /// \brief Adjust the \p GlobalLSCost according to the target
8869 /// paring capabilities and the layout of the slices.
8870 /// \pre \p GlobalLSCost should account for at least as many loads as
8871 /// there is in the slices in \p LoadedSlices.
8872 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8873                                  LoadedSlice::Cost &GlobalLSCost) {
8874   unsigned NumberOfSlices = LoadedSlices.size();
8875   // If there is less than 2 elements, no pairing is possible.
8876   if (NumberOfSlices < 2)
8877     return;
8878
8879   // Sort the slices so that elements that are likely to be next to each
8880   // other in memory are next to each other in the list.
8881   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8882             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8883     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8884     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8885   });
8886   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8887   // First (resp. Second) is the first (resp. Second) potentially candidate
8888   // to be placed in a paired load.
8889   const LoadedSlice *First = nullptr;
8890   const LoadedSlice *Second = nullptr;
8891   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8892                 // Set the beginning of the pair.
8893                                                            First = Second) {
8894
8895     Second = &LoadedSlices[CurrSlice];
8896
8897     // If First is NULL, it means we start a new pair.
8898     // Get to the next slice.
8899     if (!First)
8900       continue;
8901
8902     EVT LoadedType = First->getLoadedType();
8903
8904     // If the types of the slices are different, we cannot pair them.
8905     if (LoadedType != Second->getLoadedType())
8906       continue;
8907
8908     // Check if the target supplies paired loads for this type.
8909     unsigned RequiredAlignment = 0;
8910     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8911       // move to the next pair, this type is hopeless.
8912       Second = nullptr;
8913       continue;
8914     }
8915     // Check if we meet the alignment requirement.
8916     if (RequiredAlignment > First->getAlignment())
8917       continue;
8918
8919     // Check that both loads are next to each other in memory.
8920     if (!areSlicesNextToEachOther(*First, *Second))
8921       continue;
8922
8923     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8924     --GlobalLSCost.Loads;
8925     // Move to the next pair.
8926     Second = nullptr;
8927   }
8928 }
8929
8930 /// \brief Check the profitability of all involved LoadedSlice.
8931 /// Currently, it is considered profitable if there is exactly two
8932 /// involved slices (1) which are (2) next to each other in memory, and
8933 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8934 ///
8935 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8936 /// the elements themselves.
8937 ///
8938 /// FIXME: When the cost model will be mature enough, we can relax
8939 /// constraints (1) and (2).
8940 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8941                                 const APInt &UsedBits, bool ForCodeSize) {
8942   unsigned NumberOfSlices = LoadedSlices.size();
8943   if (StressLoadSlicing)
8944     return NumberOfSlices > 1;
8945
8946   // Check (1).
8947   if (NumberOfSlices != 2)
8948     return false;
8949
8950   // Check (2).
8951   if (!areUsedBitsDense(UsedBits))
8952     return false;
8953
8954   // Check (3).
8955   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8956   // The original code has one big load.
8957   OrigCost.Loads = 1;
8958   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8959     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8960     // Accumulate the cost of all the slices.
8961     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8962     GlobalSlicingCost += SliceCost;
8963
8964     // Account as cost in the original configuration the gain obtained
8965     // with the current slices.
8966     OrigCost.addSliceGain(LS);
8967   }
8968
8969   // If the target supports paired load, adjust the cost accordingly.
8970   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8971   return OrigCost > GlobalSlicingCost;
8972 }
8973
8974 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8975 /// operations, split it in the various pieces being extracted.
8976 ///
8977 /// This sort of thing is introduced by SROA.
8978 /// This slicing takes care not to insert overlapping loads.
8979 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8980 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8981   if (Level < AfterLegalizeDAG)
8982     return false;
8983
8984   LoadSDNode *LD = cast<LoadSDNode>(N);
8985   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8986       !LD->getValueType(0).isInteger())
8987     return false;
8988
8989   // Keep track of already used bits to detect overlapping values.
8990   // In that case, we will just abort the transformation.
8991   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8992
8993   SmallVector<LoadedSlice, 4> LoadedSlices;
8994
8995   // Check if this load is used as several smaller chunks of bits.
8996   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8997   // of computation for each trunc.
8998   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8999        UI != UIEnd; ++UI) {
9000     // Skip the uses of the chain.
9001     if (UI.getUse().getResNo() != 0)
9002       continue;
9003
9004     SDNode *User = *UI;
9005     unsigned Shift = 0;
9006
9007     // Check if this is a trunc(lshr).
9008     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9009         isa<ConstantSDNode>(User->getOperand(1))) {
9010       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9011       User = *User->use_begin();
9012     }
9013
9014     // At this point, User is a Truncate, iff we encountered, trunc or
9015     // trunc(lshr).
9016     if (User->getOpcode() != ISD::TRUNCATE)
9017       return false;
9018
9019     // The width of the type must be a power of 2 and greater than 8-bits.
9020     // Otherwise the load cannot be represented in LLVM IR.
9021     // Moreover, if we shifted with a non-8-bits multiple, the slice
9022     // will be across several bytes. We do not support that.
9023     unsigned Width = User->getValueSizeInBits(0);
9024     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9025       return 0;
9026
9027     // Build the slice for this chain of computations.
9028     LoadedSlice LS(User, LD, Shift, &DAG);
9029     APInt CurrentUsedBits = LS.getUsedBits();
9030
9031     // Check if this slice overlaps with another.
9032     if ((CurrentUsedBits & UsedBits) != 0)
9033       return false;
9034     // Update the bits used globally.
9035     UsedBits |= CurrentUsedBits;
9036
9037     // Check if the new slice would be legal.
9038     if (!LS.isLegal())
9039       return false;
9040
9041     // Record the slice.
9042     LoadedSlices.push_back(LS);
9043   }
9044
9045   // Abort slicing if it does not seem to be profitable.
9046   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9047     return false;
9048
9049   ++SlicedLoads;
9050
9051   // Rewrite each chain to use an independent load.
9052   // By construction, each chain can be represented by a unique load.
9053
9054   // Prepare the argument for the new token factor for all the slices.
9055   SmallVector<SDValue, 8> ArgChains;
9056   for (SmallVectorImpl<LoadedSlice>::const_iterator
9057            LSIt = LoadedSlices.begin(),
9058            LSItEnd = LoadedSlices.end();
9059        LSIt != LSItEnd; ++LSIt) {
9060     SDValue SliceInst = LSIt->loadSlice();
9061     CombineTo(LSIt->Inst, SliceInst, true);
9062     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9063       SliceInst = SliceInst.getOperand(0);
9064     assert(SliceInst->getOpcode() == ISD::LOAD &&
9065            "It takes more than a zext to get to the loaded slice!!");
9066     ArgChains.push_back(SliceInst.getValue(1));
9067   }
9068
9069   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9070                               ArgChains);
9071   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9072   return true;
9073 }
9074
9075 /// Check to see if V is (and load (ptr), imm), where the load is having
9076 /// specific bytes cleared out.  If so, return the byte size being masked out
9077 /// and the shift amount.
9078 static std::pair<unsigned, unsigned>
9079 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9080   std::pair<unsigned, unsigned> Result(0, 0);
9081
9082   // Check for the structure we're looking for.
9083   if (V->getOpcode() != ISD::AND ||
9084       !isa<ConstantSDNode>(V->getOperand(1)) ||
9085       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9086     return Result;
9087
9088   // Check the chain and pointer.
9089   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9090   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9091
9092   // The store should be chained directly to the load or be an operand of a
9093   // tokenfactor.
9094   if (LD == Chain.getNode())
9095     ; // ok.
9096   else if (Chain->getOpcode() != ISD::TokenFactor)
9097     return Result; // Fail.
9098   else {
9099     bool isOk = false;
9100     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9101       if (Chain->getOperand(i).getNode() == LD) {
9102         isOk = true;
9103         break;
9104       }
9105     if (!isOk) return Result;
9106   }
9107
9108   // This only handles simple types.
9109   if (V.getValueType() != MVT::i16 &&
9110       V.getValueType() != MVT::i32 &&
9111       V.getValueType() != MVT::i64)
9112     return Result;
9113
9114   // Check the constant mask.  Invert it so that the bits being masked out are
9115   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9116   // follow the sign bit for uniformity.
9117   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9118   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9119   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9120   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9121   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9122   if (NotMaskLZ == 64) return Result;  // All zero mask.
9123
9124   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9125   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9126     return Result;
9127
9128   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9129   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9130     NotMaskLZ -= 64-V.getValueSizeInBits();
9131
9132   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9133   switch (MaskedBytes) {
9134   case 1:
9135   case 2:
9136   case 4: break;
9137   default: return Result; // All one mask, or 5-byte mask.
9138   }
9139
9140   // Verify that the first bit starts at a multiple of mask so that the access
9141   // is aligned the same as the access width.
9142   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9143
9144   Result.first = MaskedBytes;
9145   Result.second = NotMaskTZ/8;
9146   return Result;
9147 }
9148
9149
9150 /// Check to see if IVal is something that provides a value as specified by
9151 /// MaskInfo. If so, replace the specified store with a narrower store of
9152 /// truncated IVal.
9153 static SDNode *
9154 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9155                                 SDValue IVal, StoreSDNode *St,
9156                                 DAGCombiner *DC) {
9157   unsigned NumBytes = MaskInfo.first;
9158   unsigned ByteShift = MaskInfo.second;
9159   SelectionDAG &DAG = DC->getDAG();
9160
9161   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9162   // that uses this.  If not, this is not a replacement.
9163   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9164                                   ByteShift*8, (ByteShift+NumBytes)*8);
9165   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9166
9167   // Check that it is legal on the target to do this.  It is legal if the new
9168   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9169   // legalization.
9170   MVT VT = MVT::getIntegerVT(NumBytes*8);
9171   if (!DC->isTypeLegal(VT))
9172     return nullptr;
9173
9174   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9175   // shifted by ByteShift and truncated down to NumBytes.
9176   if (ByteShift)
9177     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9178                        DAG.getConstant(ByteShift*8,
9179                                     DC->getShiftAmountTy(IVal.getValueType())));
9180
9181   // Figure out the offset for the store and the alignment of the access.
9182   unsigned StOffset;
9183   unsigned NewAlign = St->getAlignment();
9184
9185   if (DAG.getTargetLoweringInfo().isLittleEndian())
9186     StOffset = ByteShift;
9187   else
9188     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9189
9190   SDValue Ptr = St->getBasePtr();
9191   if (StOffset) {
9192     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9193                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9194     NewAlign = MinAlign(NewAlign, StOffset);
9195   }
9196
9197   // Truncate down to the new size.
9198   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9199
9200   ++OpsNarrowed;
9201   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9202                       St->getPointerInfo().getWithOffset(StOffset),
9203                       false, false, NewAlign).getNode();
9204 }
9205
9206
9207 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9208 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9209 /// narrowing the load and store if it would end up being a win for performance
9210 /// or code size.
9211 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9212   StoreSDNode *ST  = cast<StoreSDNode>(N);
9213   if (ST->isVolatile())
9214     return SDValue();
9215
9216   SDValue Chain = ST->getChain();
9217   SDValue Value = ST->getValue();
9218   SDValue Ptr   = ST->getBasePtr();
9219   EVT VT = Value.getValueType();
9220
9221   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9222     return SDValue();
9223
9224   unsigned Opc = Value.getOpcode();
9225
9226   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9227   // is a byte mask indicating a consecutive number of bytes, check to see if
9228   // Y is known to provide just those bytes.  If so, we try to replace the
9229   // load + replace + store sequence with a single (narrower) store, which makes
9230   // the load dead.
9231   if (Opc == ISD::OR) {
9232     std::pair<unsigned, unsigned> MaskedLoad;
9233     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9234     if (MaskedLoad.first)
9235       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9236                                                   Value.getOperand(1), ST,this))
9237         return SDValue(NewST, 0);
9238
9239     // Or is commutative, so try swapping X and Y.
9240     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9241     if (MaskedLoad.first)
9242       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9243                                                   Value.getOperand(0), ST,this))
9244         return SDValue(NewST, 0);
9245   }
9246
9247   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9248       Value.getOperand(1).getOpcode() != ISD::Constant)
9249     return SDValue();
9250
9251   SDValue N0 = Value.getOperand(0);
9252   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9253       Chain == SDValue(N0.getNode(), 1)) {
9254     LoadSDNode *LD = cast<LoadSDNode>(N0);
9255     if (LD->getBasePtr() != Ptr ||
9256         LD->getPointerInfo().getAddrSpace() !=
9257         ST->getPointerInfo().getAddrSpace())
9258       return SDValue();
9259
9260     // Find the type to narrow it the load / op / store to.
9261     SDValue N1 = Value.getOperand(1);
9262     unsigned BitWidth = N1.getValueSizeInBits();
9263     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9264     if (Opc == ISD::AND)
9265       Imm ^= APInt::getAllOnesValue(BitWidth);
9266     if (Imm == 0 || Imm.isAllOnesValue())
9267       return SDValue();
9268     unsigned ShAmt = Imm.countTrailingZeros();
9269     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9270     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9271     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9272     while (NewBW < BitWidth &&
9273            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9274              TLI.isNarrowingProfitable(VT, NewVT))) {
9275       NewBW = NextPowerOf2(NewBW);
9276       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9277     }
9278     if (NewBW >= BitWidth)
9279       return SDValue();
9280
9281     // If the lsb changed does not start at the type bitwidth boundary,
9282     // start at the previous one.
9283     if (ShAmt % NewBW)
9284       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9285     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9286                                    std::min(BitWidth, ShAmt + NewBW));
9287     if ((Imm & Mask) == Imm) {
9288       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9289       if (Opc == ISD::AND)
9290         NewImm ^= APInt::getAllOnesValue(NewBW);
9291       uint64_t PtrOff = ShAmt / 8;
9292       // For big endian targets, we need to adjust the offset to the pointer to
9293       // load the correct bytes.
9294       if (TLI.isBigEndian())
9295         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9296
9297       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9298       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9299       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9300         return SDValue();
9301
9302       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9303                                    Ptr.getValueType(), Ptr,
9304                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9305       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9306                                   LD->getChain(), NewPtr,
9307                                   LD->getPointerInfo().getWithOffset(PtrOff),
9308                                   LD->isVolatile(), LD->isNonTemporal(),
9309                                   LD->isInvariant(), NewAlign,
9310                                   LD->getAAInfo());
9311       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9312                                    DAG.getConstant(NewImm, NewVT));
9313       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9314                                    NewVal, NewPtr,
9315                                    ST->getPointerInfo().getWithOffset(PtrOff),
9316                                    false, false, NewAlign);
9317
9318       AddToWorklist(NewPtr.getNode());
9319       AddToWorklist(NewLD.getNode());
9320       AddToWorklist(NewVal.getNode());
9321       WorklistRemover DeadNodes(*this);
9322       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9323       ++OpsNarrowed;
9324       return NewST;
9325     }
9326   }
9327
9328   return SDValue();
9329 }
9330
9331 /// For a given floating point load / store pair, if the load value isn't used
9332 /// by any other operations, then consider transforming the pair to integer
9333 /// load / store operations if the target deems the transformation profitable.
9334 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9335   StoreSDNode *ST  = cast<StoreSDNode>(N);
9336   SDValue Chain = ST->getChain();
9337   SDValue Value = ST->getValue();
9338   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9339       Value.hasOneUse() &&
9340       Chain == SDValue(Value.getNode(), 1)) {
9341     LoadSDNode *LD = cast<LoadSDNode>(Value);
9342     EVT VT = LD->getMemoryVT();
9343     if (!VT.isFloatingPoint() ||
9344         VT != ST->getMemoryVT() ||
9345         LD->isNonTemporal() ||
9346         ST->isNonTemporal() ||
9347         LD->getPointerInfo().getAddrSpace() != 0 ||
9348         ST->getPointerInfo().getAddrSpace() != 0)
9349       return SDValue();
9350
9351     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9352     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9353         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9354         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9355         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9356       return SDValue();
9357
9358     unsigned LDAlign = LD->getAlignment();
9359     unsigned STAlign = ST->getAlignment();
9360     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9361     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9362     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9363       return SDValue();
9364
9365     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9366                                 LD->getChain(), LD->getBasePtr(),
9367                                 LD->getPointerInfo(),
9368                                 false, false, false, LDAlign);
9369
9370     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9371                                  NewLD, ST->getBasePtr(),
9372                                  ST->getPointerInfo(),
9373                                  false, false, STAlign);
9374
9375     AddToWorklist(NewLD.getNode());
9376     AddToWorklist(NewST.getNode());
9377     WorklistRemover DeadNodes(*this);
9378     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9379     ++LdStFP2Int;
9380     return NewST;
9381   }
9382
9383   return SDValue();
9384 }
9385
9386 /// Helper struct to parse and store a memory address as base + index + offset.
9387 /// We ignore sign extensions when it is safe to do so.
9388 /// The following two expressions are not equivalent. To differentiate we need
9389 /// to store whether there was a sign extension involved in the index
9390 /// computation.
9391 ///  (load (i64 add (i64 copyfromreg %c)
9392 ///                 (i64 signextend (add (i8 load %index)
9393 ///                                      (i8 1))))
9394 /// vs
9395 ///
9396 /// (load (i64 add (i64 copyfromreg %c)
9397 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9398 ///                                         (i32 1)))))
9399 struct BaseIndexOffset {
9400   SDValue Base;
9401   SDValue Index;
9402   int64_t Offset;
9403   bool IsIndexSignExt;
9404
9405   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9406
9407   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9408                   bool IsIndexSignExt) :
9409     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9410
9411   bool equalBaseIndex(const BaseIndexOffset &Other) {
9412     return Other.Base == Base && Other.Index == Index &&
9413       Other.IsIndexSignExt == IsIndexSignExt;
9414   }
9415
9416   /// Parses tree in Ptr for base, index, offset addresses.
9417   static BaseIndexOffset match(SDValue Ptr) {
9418     bool IsIndexSignExt = false;
9419
9420     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9421     // instruction, then it could be just the BASE or everything else we don't
9422     // know how to handle. Just use Ptr as BASE and give up.
9423     if (Ptr->getOpcode() != ISD::ADD)
9424       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9425
9426     // We know that we have at least an ADD instruction. Try to pattern match
9427     // the simple case of BASE + OFFSET.
9428     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9429       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9430       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9431                               IsIndexSignExt);
9432     }
9433
9434     // Inside a loop the current BASE pointer is calculated using an ADD and a
9435     // MUL instruction. In this case Ptr is the actual BASE pointer.
9436     // (i64 add (i64 %array_ptr)
9437     //          (i64 mul (i64 %induction_var)
9438     //                   (i64 %element_size)))
9439     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9440       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9441
9442     // Look at Base + Index + Offset cases.
9443     SDValue Base = Ptr->getOperand(0);
9444     SDValue IndexOffset = Ptr->getOperand(1);
9445
9446     // Skip signextends.
9447     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9448       IndexOffset = IndexOffset->getOperand(0);
9449       IsIndexSignExt = true;
9450     }
9451
9452     // Either the case of Base + Index (no offset) or something else.
9453     if (IndexOffset->getOpcode() != ISD::ADD)
9454       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9455
9456     // Now we have the case of Base + Index + offset.
9457     SDValue Index = IndexOffset->getOperand(0);
9458     SDValue Offset = IndexOffset->getOperand(1);
9459
9460     if (!isa<ConstantSDNode>(Offset))
9461       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9462
9463     // Ignore signextends.
9464     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9465       Index = Index->getOperand(0);
9466       IsIndexSignExt = true;
9467     } else IsIndexSignExt = false;
9468
9469     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9470     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9471   }
9472 };
9473
9474 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9475 /// is located in a sequence of memory operations connected by a chain.
9476 struct MemOpLink {
9477   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9478     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9479   // Ptr to the mem node.
9480   LSBaseSDNode *MemNode;
9481   // Offset from the base ptr.
9482   int64_t OffsetFromBase;
9483   // What is the sequence number of this mem node.
9484   // Lowest mem operand in the DAG starts at zero.
9485   unsigned SequenceNum;
9486 };
9487
9488 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9489   EVT MemVT = St->getMemoryVT();
9490   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9491   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9492     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9493
9494   // Don't merge vectors into wider inputs.
9495   if (MemVT.isVector() || !MemVT.isSimple())
9496     return false;
9497
9498   // Perform an early exit check. Do not bother looking at stored values that
9499   // are not constants or loads.
9500   SDValue StoredVal = St->getValue();
9501   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9502   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9503       !IsLoadSrc)
9504     return false;
9505
9506   // Only look at ends of store sequences.
9507   SDValue Chain = SDValue(St, 0);
9508   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9509     return false;
9510
9511   // This holds the base pointer, index, and the offset in bytes from the base
9512   // pointer.
9513   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9514
9515   // We must have a base and an offset.
9516   if (!BasePtr.Base.getNode())
9517     return false;
9518
9519   // Do not handle stores to undef base pointers.
9520   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9521     return false;
9522
9523   // Save the LoadSDNodes that we find in the chain.
9524   // We need to make sure that these nodes do not interfere with
9525   // any of the store nodes.
9526   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9527
9528   // Save the StoreSDNodes that we find in the chain.
9529   SmallVector<MemOpLink, 8> StoreNodes;
9530
9531   // Walk up the chain and look for nodes with offsets from the same
9532   // base pointer. Stop when reaching an instruction with a different kind
9533   // or instruction which has a different base pointer.
9534   unsigned Seq = 0;
9535   StoreSDNode *Index = St;
9536   while (Index) {
9537     // If the chain has more than one use, then we can't reorder the mem ops.
9538     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9539       break;
9540
9541     // Find the base pointer and offset for this memory node.
9542     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9543
9544     // Check that the base pointer is the same as the original one.
9545     if (!Ptr.equalBaseIndex(BasePtr))
9546       break;
9547
9548     // Check that the alignment is the same.
9549     if (Index->getAlignment() != St->getAlignment())
9550       break;
9551
9552     // The memory operands must not be volatile.
9553     if (Index->isVolatile() || Index->isIndexed())
9554       break;
9555
9556     // No truncation.
9557     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9558       if (St->isTruncatingStore())
9559         break;
9560
9561     // The stored memory type must be the same.
9562     if (Index->getMemoryVT() != MemVT)
9563       break;
9564
9565     // We do not allow unaligned stores because we want to prevent overriding
9566     // stores.
9567     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9568       break;
9569
9570     // We found a potential memory operand to merge.
9571     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9572
9573     // Find the next memory operand in the chain. If the next operand in the
9574     // chain is a store then move up and continue the scan with the next
9575     // memory operand. If the next operand is a load save it and use alias
9576     // information to check if it interferes with anything.
9577     SDNode *NextInChain = Index->getChain().getNode();
9578     while (1) {
9579       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9580         // We found a store node. Use it for the next iteration.
9581         Index = STn;
9582         break;
9583       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9584         if (Ldn->isVolatile()) {
9585           Index = nullptr;
9586           break;
9587         }
9588
9589         // Save the load node for later. Continue the scan.
9590         AliasLoadNodes.push_back(Ldn);
9591         NextInChain = Ldn->getChain().getNode();
9592         continue;
9593       } else {
9594         Index = nullptr;
9595         break;
9596       }
9597     }
9598   }
9599
9600   // Check if there is anything to merge.
9601   if (StoreNodes.size() < 2)
9602     return false;
9603
9604   // Sort the memory operands according to their distance from the base pointer.
9605   std::sort(StoreNodes.begin(), StoreNodes.end(),
9606             [](MemOpLink LHS, MemOpLink RHS) {
9607     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9608            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9609             LHS.SequenceNum > RHS.SequenceNum);
9610   });
9611
9612   // Scan the memory operations on the chain and find the first non-consecutive
9613   // store memory address.
9614   unsigned LastConsecutiveStore = 0;
9615   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9616   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9617
9618     // Check that the addresses are consecutive starting from the second
9619     // element in the list of stores.
9620     if (i > 0) {
9621       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9622       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9623         break;
9624     }
9625
9626     bool Alias = false;
9627     // Check if this store interferes with any of the loads that we found.
9628     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9629       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9630         Alias = true;
9631         break;
9632       }
9633     // We found a load that alias with this store. Stop the sequence.
9634     if (Alias)
9635       break;
9636
9637     // Mark this node as useful.
9638     LastConsecutiveStore = i;
9639   }
9640
9641   // The node with the lowest store address.
9642   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9643
9644   // Store the constants into memory as one consecutive store.
9645   if (!IsLoadSrc) {
9646     unsigned LastLegalType = 0;
9647     unsigned LastLegalVectorType = 0;
9648     bool NonZero = false;
9649     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9650       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9651       SDValue StoredVal = St->getValue();
9652
9653       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9654         NonZero |= !C->isNullValue();
9655       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9656         NonZero |= !C->getConstantFPValue()->isNullValue();
9657       } else {
9658         // Non-constant.
9659         break;
9660       }
9661
9662       // Find a legal type for the constant store.
9663       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9664       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9665       if (TLI.isTypeLegal(StoreTy))
9666         LastLegalType = i+1;
9667       // Or check whether a truncstore is legal.
9668       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9669                TargetLowering::TypePromoteInteger) {
9670         EVT LegalizedStoredValueTy =
9671           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9672         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9673           LastLegalType = i+1;
9674       }
9675
9676       // Find a legal type for the vector store.
9677       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9678       if (TLI.isTypeLegal(Ty))
9679         LastLegalVectorType = i + 1;
9680     }
9681
9682     // We only use vectors if the constant is known to be zero and the
9683     // function is not marked with the noimplicitfloat attribute.
9684     if (NonZero || NoVectors)
9685       LastLegalVectorType = 0;
9686
9687     // Check if we found a legal integer type to store.
9688     if (LastLegalType == 0 && LastLegalVectorType == 0)
9689       return false;
9690
9691     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9692     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9693
9694     // Make sure we have something to merge.
9695     if (NumElem < 2)
9696       return false;
9697
9698     unsigned EarliestNodeUsed = 0;
9699     for (unsigned i=0; i < NumElem; ++i) {
9700       // Find a chain for the new wide-store operand. Notice that some
9701       // of the store nodes that we found may not be selected for inclusion
9702       // in the wide store. The chain we use needs to be the chain of the
9703       // earliest store node which is *used* and replaced by the wide store.
9704       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9705         EarliestNodeUsed = i;
9706     }
9707
9708     // The earliest Node in the DAG.
9709     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9710     SDLoc DL(StoreNodes[0].MemNode);
9711
9712     SDValue StoredVal;
9713     if (UseVector) {
9714       // Find a legal type for the vector store.
9715       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9716       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9717       StoredVal = DAG.getConstant(0, Ty);
9718     } else {
9719       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9720       APInt StoreInt(StoreBW, 0);
9721
9722       // Construct a single integer constant which is made of the smaller
9723       // constant inputs.
9724       bool IsLE = TLI.isLittleEndian();
9725       for (unsigned i = 0; i < NumElem ; ++i) {
9726         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9727         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9728         SDValue Val = St->getValue();
9729         StoreInt<<=ElementSizeBytes*8;
9730         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9731           StoreInt|=C->getAPIntValue().zext(StoreBW);
9732         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9733           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9734         } else {
9735           assert(false && "Invalid constant element type");
9736         }
9737       }
9738
9739       // Create the new Load and Store operations.
9740       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9741       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9742     }
9743
9744     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9745                                     FirstInChain->getBasePtr(),
9746                                     FirstInChain->getPointerInfo(),
9747                                     false, false,
9748                                     FirstInChain->getAlignment());
9749
9750     // Replace the first store with the new store
9751     CombineTo(EarliestOp, NewStore);
9752     // Erase all other stores.
9753     for (unsigned i = 0; i < NumElem ; ++i) {
9754       if (StoreNodes[i].MemNode == EarliestOp)
9755         continue;
9756       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9757       // ReplaceAllUsesWith will replace all uses that existed when it was
9758       // called, but graph optimizations may cause new ones to appear. For
9759       // example, the case in pr14333 looks like
9760       //
9761       //  St's chain -> St -> another store -> X
9762       //
9763       // And the only difference from St to the other store is the chain.
9764       // When we change it's chain to be St's chain they become identical,
9765       // get CSEed and the net result is that X is now a use of St.
9766       // Since we know that St is redundant, just iterate.
9767       while (!St->use_empty())
9768         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9769       deleteAndRecombine(St);
9770     }
9771
9772     return true;
9773   }
9774
9775   // Below we handle the case of multiple consecutive stores that
9776   // come from multiple consecutive loads. We merge them into a single
9777   // wide load and a single wide store.
9778
9779   // Look for load nodes which are used by the stored values.
9780   SmallVector<MemOpLink, 8> LoadNodes;
9781
9782   // Find acceptable loads. Loads need to have the same chain (token factor),
9783   // must not be zext, volatile, indexed, and they must be consecutive.
9784   BaseIndexOffset LdBasePtr;
9785   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9786     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9787     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9788     if (!Ld) break;
9789
9790     // Loads must only have one use.
9791     if (!Ld->hasNUsesOfValue(1, 0))
9792       break;
9793
9794     // Check that the alignment is the same as the stores.
9795     if (Ld->getAlignment() != St->getAlignment())
9796       break;
9797
9798     // The memory operands must not be volatile.
9799     if (Ld->isVolatile() || Ld->isIndexed())
9800       break;
9801
9802     // We do not accept ext loads.
9803     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9804       break;
9805
9806     // The stored memory type must be the same.
9807     if (Ld->getMemoryVT() != MemVT)
9808       break;
9809
9810     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9811     // If this is not the first ptr that we check.
9812     if (LdBasePtr.Base.getNode()) {
9813       // The base ptr must be the same.
9814       if (!LdPtr.equalBaseIndex(LdBasePtr))
9815         break;
9816     } else {
9817       // Check that all other base pointers are the same as this one.
9818       LdBasePtr = LdPtr;
9819     }
9820
9821     // We found a potential memory operand to merge.
9822     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9823   }
9824
9825   if (LoadNodes.size() < 2)
9826     return false;
9827
9828   // If we have load/store pair instructions and we only have two values,
9829   // don't bother.
9830   unsigned RequiredAlignment;
9831   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9832       St->getAlignment() >= RequiredAlignment)
9833     return false;
9834
9835   // Scan the memory operations on the chain and find the first non-consecutive
9836   // load memory address. These variables hold the index in the store node
9837   // array.
9838   unsigned LastConsecutiveLoad = 0;
9839   // This variable refers to the size and not index in the array.
9840   unsigned LastLegalVectorType = 0;
9841   unsigned LastLegalIntegerType = 0;
9842   StartAddress = LoadNodes[0].OffsetFromBase;
9843   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9844   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9845     // All loads much share the same chain.
9846     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9847       break;
9848
9849     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9850     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9851       break;
9852     LastConsecutiveLoad = i;
9853
9854     // Find a legal type for the vector store.
9855     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9856     if (TLI.isTypeLegal(StoreTy))
9857       LastLegalVectorType = i + 1;
9858
9859     // Find a legal type for the integer store.
9860     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9861     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9862     if (TLI.isTypeLegal(StoreTy))
9863       LastLegalIntegerType = i + 1;
9864     // Or check whether a truncstore and extload is legal.
9865     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9866              TargetLowering::TypePromoteInteger) {
9867       EVT LegalizedStoredValueTy =
9868         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9869       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9870           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9871           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9872           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9873         LastLegalIntegerType = i+1;
9874     }
9875   }
9876
9877   // Only use vector types if the vector type is larger than the integer type.
9878   // If they are the same, use integers.
9879   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9880   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9881
9882   // We add +1 here because the LastXXX variables refer to location while
9883   // the NumElem refers to array/index size.
9884   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9885   NumElem = std::min(LastLegalType, NumElem);
9886
9887   if (NumElem < 2)
9888     return false;
9889
9890   // The earliest Node in the DAG.
9891   unsigned EarliestNodeUsed = 0;
9892   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9893   for (unsigned i=1; i<NumElem; ++i) {
9894     // Find a chain for the new wide-store operand. Notice that some
9895     // of the store nodes that we found may not be selected for inclusion
9896     // in the wide store. The chain we use needs to be the chain of the
9897     // earliest store node which is *used* and replaced by the wide store.
9898     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9899       EarliestNodeUsed = i;
9900   }
9901
9902   // Find if it is better to use vectors or integers to load and store
9903   // to memory.
9904   EVT JointMemOpVT;
9905   if (UseVectorTy) {
9906     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9907   } else {
9908     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9909     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9910   }
9911
9912   SDLoc LoadDL(LoadNodes[0].MemNode);
9913   SDLoc StoreDL(StoreNodes[0].MemNode);
9914
9915   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9916   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9917                                 FirstLoad->getChain(),
9918                                 FirstLoad->getBasePtr(),
9919                                 FirstLoad->getPointerInfo(),
9920                                 false, false, false,
9921                                 FirstLoad->getAlignment());
9922
9923   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9924                                   FirstInChain->getBasePtr(),
9925                                   FirstInChain->getPointerInfo(), false, false,
9926                                   FirstInChain->getAlignment());
9927
9928   // Replace one of the loads with the new load.
9929   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9930   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9931                                 SDValue(NewLoad.getNode(), 1));
9932
9933   // Remove the rest of the load chains.
9934   for (unsigned i = 1; i < NumElem ; ++i) {
9935     // Replace all chain users of the old load nodes with the chain of the new
9936     // load node.
9937     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9938     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9939   }
9940
9941   // Replace the first store with the new store.
9942   CombineTo(EarliestOp, NewStore);
9943   // Erase all other stores.
9944   for (unsigned i = 0; i < NumElem ; ++i) {
9945     // Remove all Store nodes.
9946     if (StoreNodes[i].MemNode == EarliestOp)
9947       continue;
9948     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9949     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9950     deleteAndRecombine(St);
9951   }
9952
9953   return true;
9954 }
9955
9956 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9957   StoreSDNode *ST  = cast<StoreSDNode>(N);
9958   SDValue Chain = ST->getChain();
9959   SDValue Value = ST->getValue();
9960   SDValue Ptr   = ST->getBasePtr();
9961
9962   // If this is a store of a bit convert, store the input value if the
9963   // resultant store does not need a higher alignment than the original.
9964   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9965       ST->isUnindexed()) {
9966     unsigned OrigAlign = ST->getAlignment();
9967     EVT SVT = Value.getOperand(0).getValueType();
9968     unsigned Align = TLI.getDataLayout()->
9969       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9970     if (Align <= OrigAlign &&
9971         ((!LegalOperations && !ST->isVolatile()) ||
9972          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9973       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9974                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9975                           ST->isNonTemporal(), OrigAlign,
9976                           ST->getAAInfo());
9977   }
9978
9979   // Turn 'store undef, Ptr' -> nothing.
9980   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9981     return Chain;
9982
9983   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9984   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9985     // NOTE: If the original store is volatile, this transform must not increase
9986     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9987     // processor operation but an i64 (which is not legal) requires two.  So the
9988     // transform should not be done in this case.
9989     if (Value.getOpcode() != ISD::TargetConstantFP) {
9990       SDValue Tmp;
9991       switch (CFP->getSimpleValueType(0).SimpleTy) {
9992       default: llvm_unreachable("Unknown FP type");
9993       case MVT::f16:    // We don't do this for these yet.
9994       case MVT::f80:
9995       case MVT::f128:
9996       case MVT::ppcf128:
9997         break;
9998       case MVT::f32:
9999         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10000             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10001           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10002                               bitcastToAPInt().getZExtValue(), MVT::i32);
10003           return DAG.getStore(Chain, SDLoc(N), Tmp,
10004                               Ptr, ST->getMemOperand());
10005         }
10006         break;
10007       case MVT::f64:
10008         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10009              !ST->isVolatile()) ||
10010             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10011           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10012                                 getZExtValue(), MVT::i64);
10013           return DAG.getStore(Chain, SDLoc(N), Tmp,
10014                               Ptr, ST->getMemOperand());
10015         }
10016
10017         if (!ST->isVolatile() &&
10018             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10019           // Many FP stores are not made apparent until after legalize, e.g. for
10020           // argument passing.  Since this is so common, custom legalize the
10021           // 64-bit integer store into two 32-bit stores.
10022           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10023           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10024           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10025           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10026
10027           unsigned Alignment = ST->getAlignment();
10028           bool isVolatile = ST->isVolatile();
10029           bool isNonTemporal = ST->isNonTemporal();
10030           AAMDNodes AAInfo = ST->getAAInfo();
10031
10032           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10033                                      Ptr, ST->getPointerInfo(),
10034                                      isVolatile, isNonTemporal,
10035                                      ST->getAlignment(), AAInfo);
10036           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10037                             DAG.getConstant(4, Ptr.getValueType()));
10038           Alignment = MinAlign(Alignment, 4U);
10039           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10040                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10041                                      isVolatile, isNonTemporal,
10042                                      Alignment, AAInfo);
10043           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10044                              St0, St1);
10045         }
10046
10047         break;
10048       }
10049     }
10050   }
10051
10052   // Try to infer better alignment information than the store already has.
10053   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10054     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10055       if (Align > ST->getAlignment())
10056         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10057                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10058                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10059                                  ST->getAAInfo());
10060     }
10061   }
10062
10063   // Try transforming a pair floating point load / store ops to integer
10064   // load / store ops.
10065   SDValue NewST = TransformFPLoadStorePair(N);
10066   if (NewST.getNode())
10067     return NewST;
10068
10069   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10070                                                   : DAG.getSubtarget().useAA();
10071 #ifndef NDEBUG
10072   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10073       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10074     UseAA = false;
10075 #endif
10076   if (UseAA && ST->isUnindexed()) {
10077     // Walk up chain skipping non-aliasing memory nodes.
10078     SDValue BetterChain = FindBetterChain(N, Chain);
10079
10080     // If there is a better chain.
10081     if (Chain != BetterChain) {
10082       SDValue ReplStore;
10083
10084       // Replace the chain to avoid dependency.
10085       if (ST->isTruncatingStore()) {
10086         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10087                                       ST->getMemoryVT(), ST->getMemOperand());
10088       } else {
10089         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10090                                  ST->getMemOperand());
10091       }
10092
10093       // Create token to keep both nodes around.
10094       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10095                                   MVT::Other, Chain, ReplStore);
10096
10097       // Make sure the new and old chains are cleaned up.
10098       AddToWorklist(Token.getNode());
10099
10100       // Don't add users to work list.
10101       return CombineTo(N, Token, false);
10102     }
10103   }
10104
10105   // Try transforming N to an indexed store.
10106   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10107     return SDValue(N, 0);
10108
10109   // FIXME: is there such a thing as a truncating indexed store?
10110   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10111       Value.getValueType().isInteger()) {
10112     // See if we can simplify the input to this truncstore with knowledge that
10113     // only the low bits are being used.  For example:
10114     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10115     SDValue Shorter =
10116       GetDemandedBits(Value,
10117                       APInt::getLowBitsSet(
10118                         Value.getValueType().getScalarType().getSizeInBits(),
10119                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10120     AddToWorklist(Value.getNode());
10121     if (Shorter.getNode())
10122       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10123                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10124
10125     // Otherwise, see if we can simplify the operation with
10126     // SimplifyDemandedBits, which only works if the value has a single use.
10127     if (SimplifyDemandedBits(Value,
10128                         APInt::getLowBitsSet(
10129                           Value.getValueType().getScalarType().getSizeInBits(),
10130                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10131       return SDValue(N, 0);
10132   }
10133
10134   // If this is a load followed by a store to the same location, then the store
10135   // is dead/noop.
10136   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10137     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10138         ST->isUnindexed() && !ST->isVolatile() &&
10139         // There can't be any side effects between the load and store, such as
10140         // a call or store.
10141         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10142       // The store is dead, remove it.
10143       return Chain;
10144     }
10145   }
10146
10147   // If this is a store followed by a store with the same value to the same
10148   // location, then the store is dead/noop.
10149   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10150     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10151         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10152         ST1->isUnindexed() && !ST1->isVolatile()) {
10153       // The store is dead, remove it.
10154       return Chain;
10155     }
10156   }
10157
10158   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10159   // truncating store.  We can do this even if this is already a truncstore.
10160   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10161       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10162       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10163                             ST->getMemoryVT())) {
10164     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10165                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10166   }
10167
10168   // Only perform this optimization before the types are legal, because we
10169   // don't want to perform this optimization on every DAGCombine invocation.
10170   if (!LegalTypes) {
10171     bool EverChanged = false;
10172
10173     do {
10174       // There can be multiple store sequences on the same chain.
10175       // Keep trying to merge store sequences until we are unable to do so
10176       // or until we merge the last store on the chain.
10177       bool Changed = MergeConsecutiveStores(ST);
10178       EverChanged |= Changed;
10179       if (!Changed) break;
10180     } while (ST->getOpcode() != ISD::DELETED_NODE);
10181
10182     if (EverChanged)
10183       return SDValue(N, 0);
10184   }
10185
10186   return ReduceLoadOpStoreWidth(N);
10187 }
10188
10189 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10190   SDValue InVec = N->getOperand(0);
10191   SDValue InVal = N->getOperand(1);
10192   SDValue EltNo = N->getOperand(2);
10193   SDLoc dl(N);
10194
10195   // If the inserted element is an UNDEF, just use the input vector.
10196   if (InVal.getOpcode() == ISD::UNDEF)
10197     return InVec;
10198
10199   EVT VT = InVec.getValueType();
10200
10201   // If we can't generate a legal BUILD_VECTOR, exit
10202   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10203     return SDValue();
10204
10205   // Check that we know which element is being inserted
10206   if (!isa<ConstantSDNode>(EltNo))
10207     return SDValue();
10208   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10209
10210   // Canonicalize insert_vector_elt dag nodes.
10211   // Example:
10212   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10213   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10214   //
10215   // Do this only if the child insert_vector node has one use; also
10216   // do this only if indices are both constants and Idx1 < Idx0.
10217   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10218       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10219     unsigned OtherElt =
10220       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10221     if (Elt < OtherElt) {
10222       // Swap nodes.
10223       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10224                                   InVec.getOperand(0), InVal, EltNo);
10225       AddToWorklist(NewOp.getNode());
10226       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10227                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10228     }
10229   }
10230
10231   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10232   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10233   // vector elements.
10234   SmallVector<SDValue, 8> Ops;
10235   // Do not combine these two vectors if the output vector will not replace
10236   // the input vector.
10237   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10238     Ops.append(InVec.getNode()->op_begin(),
10239                InVec.getNode()->op_end());
10240   } else if (InVec.getOpcode() == ISD::UNDEF) {
10241     unsigned NElts = VT.getVectorNumElements();
10242     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10243   } else {
10244     return SDValue();
10245   }
10246
10247   // Insert the element
10248   if (Elt < Ops.size()) {
10249     // All the operands of BUILD_VECTOR must have the same type;
10250     // we enforce that here.
10251     EVT OpVT = Ops[0].getValueType();
10252     if (InVal.getValueType() != OpVT)
10253       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10254                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10255                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10256     Ops[Elt] = InVal;
10257   }
10258
10259   // Return the new vector
10260   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10261 }
10262
10263 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10264     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10265   EVT ResultVT = EVE->getValueType(0);
10266   EVT VecEltVT = InVecVT.getVectorElementType();
10267   unsigned Align = OriginalLoad->getAlignment();
10268   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10269       VecEltVT.getTypeForEVT(*DAG.getContext()));
10270
10271   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10272     return SDValue();
10273
10274   Align = NewAlign;
10275
10276   SDValue NewPtr = OriginalLoad->getBasePtr();
10277   SDValue Offset;
10278   EVT PtrType = NewPtr.getValueType();
10279   MachinePointerInfo MPI;
10280   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10281     int Elt = ConstEltNo->getZExtValue();
10282     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10283     if (TLI.isBigEndian())
10284       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10285     Offset = DAG.getConstant(PtrOff, PtrType);
10286     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10287   } else {
10288     Offset = DAG.getNode(
10289         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10290         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10291     if (TLI.isBigEndian())
10292       Offset = DAG.getNode(
10293           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10294           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10295     MPI = OriginalLoad->getPointerInfo();
10296   }
10297   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10298
10299   // The replacement we need to do here is a little tricky: we need to
10300   // replace an extractelement of a load with a load.
10301   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10302   // Note that this replacement assumes that the extractvalue is the only
10303   // use of the load; that's okay because we don't want to perform this
10304   // transformation in other cases anyway.
10305   SDValue Load;
10306   SDValue Chain;
10307   if (ResultVT.bitsGT(VecEltVT)) {
10308     // If the result type of vextract is wider than the load, then issue an
10309     // extending load instead.
10310     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10311                                    ? ISD::ZEXTLOAD
10312                                    : ISD::EXTLOAD;
10313     Load = DAG.getExtLoad(
10314         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10315         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10316         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10317     Chain = Load.getValue(1);
10318   } else {
10319     Load = DAG.getLoad(
10320         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10321         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10322         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10323     Chain = Load.getValue(1);
10324     if (ResultVT.bitsLT(VecEltVT))
10325       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10326     else
10327       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10328   }
10329   WorklistRemover DeadNodes(*this);
10330   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10331   SDValue To[] = { Load, Chain };
10332   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10333   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10334   // worklist explicitly as well.
10335   AddToWorklist(Load.getNode());
10336   AddUsersToWorklist(Load.getNode()); // Add users too
10337   // Make sure to revisit this node to clean it up; it will usually be dead.
10338   AddToWorklist(EVE);
10339   ++OpsNarrowed;
10340   return SDValue(EVE, 0);
10341 }
10342
10343 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10344   // (vextract (scalar_to_vector val, 0) -> val
10345   SDValue InVec = N->getOperand(0);
10346   EVT VT = InVec.getValueType();
10347   EVT NVT = N->getValueType(0);
10348
10349   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10350     // Check if the result type doesn't match the inserted element type. A
10351     // SCALAR_TO_VECTOR may truncate the inserted element and the
10352     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10353     SDValue InOp = InVec.getOperand(0);
10354     if (InOp.getValueType() != NVT) {
10355       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10356       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10357     }
10358     return InOp;
10359   }
10360
10361   SDValue EltNo = N->getOperand(1);
10362   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10363
10364   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10365   // We only perform this optimization before the op legalization phase because
10366   // we may introduce new vector instructions which are not backed by TD
10367   // patterns. For example on AVX, extracting elements from a wide vector
10368   // without using extract_subvector. However, if we can find an underlying
10369   // scalar value, then we can always use that.
10370   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10371       && ConstEltNo) {
10372     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10373     int NumElem = VT.getVectorNumElements();
10374     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10375     // Find the new index to extract from.
10376     int OrigElt = SVOp->getMaskElt(Elt);
10377
10378     // Extracting an undef index is undef.
10379     if (OrigElt == -1)
10380       return DAG.getUNDEF(NVT);
10381
10382     // Select the right vector half to extract from.
10383     SDValue SVInVec;
10384     if (OrigElt < NumElem) {
10385       SVInVec = InVec->getOperand(0);
10386     } else {
10387       SVInVec = InVec->getOperand(1);
10388       OrigElt -= NumElem;
10389     }
10390
10391     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10392       SDValue InOp = SVInVec.getOperand(OrigElt);
10393       if (InOp.getValueType() != NVT) {
10394         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10395         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10396       }
10397
10398       return InOp;
10399     }
10400
10401     // FIXME: We should handle recursing on other vector shuffles and
10402     // scalar_to_vector here as well.
10403
10404     if (!LegalOperations) {
10405       EVT IndexTy = TLI.getVectorIdxTy();
10406       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10407                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10408     }
10409   }
10410
10411   bool BCNumEltsChanged = false;
10412   EVT ExtVT = VT.getVectorElementType();
10413   EVT LVT = ExtVT;
10414
10415   // If the result of load has to be truncated, then it's not necessarily
10416   // profitable.
10417   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10418     return SDValue();
10419
10420   if (InVec.getOpcode() == ISD::BITCAST) {
10421     // Don't duplicate a load with other uses.
10422     if (!InVec.hasOneUse())
10423       return SDValue();
10424
10425     EVT BCVT = InVec.getOperand(0).getValueType();
10426     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10427       return SDValue();
10428     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10429       BCNumEltsChanged = true;
10430     InVec = InVec.getOperand(0);
10431     ExtVT = BCVT.getVectorElementType();
10432   }
10433
10434   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10435   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10436       ISD::isNormalLoad(InVec.getNode()) &&
10437       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10438     SDValue Index = N->getOperand(1);
10439     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10440       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10441                                                            OrigLoad);
10442   }
10443
10444   // Perform only after legalization to ensure build_vector / vector_shuffle
10445   // optimizations have already been done.
10446   if (!LegalOperations) return SDValue();
10447
10448   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10449   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10450   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10451
10452   if (ConstEltNo) {
10453     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10454
10455     LoadSDNode *LN0 = nullptr;
10456     const ShuffleVectorSDNode *SVN = nullptr;
10457     if (ISD::isNormalLoad(InVec.getNode())) {
10458       LN0 = cast<LoadSDNode>(InVec);
10459     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10460                InVec.getOperand(0).getValueType() == ExtVT &&
10461                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10462       // Don't duplicate a load with other uses.
10463       if (!InVec.hasOneUse())
10464         return SDValue();
10465
10466       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10467     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10468       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10469       // =>
10470       // (load $addr+1*size)
10471
10472       // Don't duplicate a load with other uses.
10473       if (!InVec.hasOneUse())
10474         return SDValue();
10475
10476       // If the bit convert changed the number of elements, it is unsafe
10477       // to examine the mask.
10478       if (BCNumEltsChanged)
10479         return SDValue();
10480
10481       // Select the input vector, guarding against out of range extract vector.
10482       unsigned NumElems = VT.getVectorNumElements();
10483       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10484       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10485
10486       if (InVec.getOpcode() == ISD::BITCAST) {
10487         // Don't duplicate a load with other uses.
10488         if (!InVec.hasOneUse())
10489           return SDValue();
10490
10491         InVec = InVec.getOperand(0);
10492       }
10493       if (ISD::isNormalLoad(InVec.getNode())) {
10494         LN0 = cast<LoadSDNode>(InVec);
10495         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10496         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10497       }
10498     }
10499
10500     // Make sure we found a non-volatile load and the extractelement is
10501     // the only use.
10502     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10503       return SDValue();
10504
10505     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10506     if (Elt == -1)
10507       return DAG.getUNDEF(LVT);
10508
10509     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10510   }
10511
10512   return SDValue();
10513 }
10514
10515 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10516 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10517   // We perform this optimization post type-legalization because
10518   // the type-legalizer often scalarizes integer-promoted vectors.
10519   // Performing this optimization before may create bit-casts which
10520   // will be type-legalized to complex code sequences.
10521   // We perform this optimization only before the operation legalizer because we
10522   // may introduce illegal operations.
10523   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10524     return SDValue();
10525
10526   unsigned NumInScalars = N->getNumOperands();
10527   SDLoc dl(N);
10528   EVT VT = N->getValueType(0);
10529
10530   // Check to see if this is a BUILD_VECTOR of a bunch of values
10531   // which come from any_extend or zero_extend nodes. If so, we can create
10532   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10533   // optimizations. We do not handle sign-extend because we can't fill the sign
10534   // using shuffles.
10535   EVT SourceType = MVT::Other;
10536   bool AllAnyExt = true;
10537
10538   for (unsigned i = 0; i != NumInScalars; ++i) {
10539     SDValue In = N->getOperand(i);
10540     // Ignore undef inputs.
10541     if (In.getOpcode() == ISD::UNDEF) continue;
10542
10543     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10544     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10545
10546     // Abort if the element is not an extension.
10547     if (!ZeroExt && !AnyExt) {
10548       SourceType = MVT::Other;
10549       break;
10550     }
10551
10552     // The input is a ZeroExt or AnyExt. Check the original type.
10553     EVT InTy = In.getOperand(0).getValueType();
10554
10555     // Check that all of the widened source types are the same.
10556     if (SourceType == MVT::Other)
10557       // First time.
10558       SourceType = InTy;
10559     else if (InTy != SourceType) {
10560       // Multiple income types. Abort.
10561       SourceType = MVT::Other;
10562       break;
10563     }
10564
10565     // Check if all of the extends are ANY_EXTENDs.
10566     AllAnyExt &= AnyExt;
10567   }
10568
10569   // In order to have valid types, all of the inputs must be extended from the
10570   // same source type and all of the inputs must be any or zero extend.
10571   // Scalar sizes must be a power of two.
10572   EVT OutScalarTy = VT.getScalarType();
10573   bool ValidTypes = SourceType != MVT::Other &&
10574                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10575                  isPowerOf2_32(SourceType.getSizeInBits());
10576
10577   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10578   // turn into a single shuffle instruction.
10579   if (!ValidTypes)
10580     return SDValue();
10581
10582   bool isLE = TLI.isLittleEndian();
10583   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10584   assert(ElemRatio > 1 && "Invalid element size ratio");
10585   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10586                                DAG.getConstant(0, SourceType);
10587
10588   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10589   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10590
10591   // Populate the new build_vector
10592   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10593     SDValue Cast = N->getOperand(i);
10594     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10595             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10596             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10597     SDValue In;
10598     if (Cast.getOpcode() == ISD::UNDEF)
10599       In = DAG.getUNDEF(SourceType);
10600     else
10601       In = Cast->getOperand(0);
10602     unsigned Index = isLE ? (i * ElemRatio) :
10603                             (i * ElemRatio + (ElemRatio - 1));
10604
10605     assert(Index < Ops.size() && "Invalid index");
10606     Ops[Index] = In;
10607   }
10608
10609   // The type of the new BUILD_VECTOR node.
10610   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10611   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10612          "Invalid vector size");
10613   // Check if the new vector type is legal.
10614   if (!isTypeLegal(VecVT)) return SDValue();
10615
10616   // Make the new BUILD_VECTOR.
10617   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10618
10619   // The new BUILD_VECTOR node has the potential to be further optimized.
10620   AddToWorklist(BV.getNode());
10621   // Bitcast to the desired type.
10622   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10623 }
10624
10625 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10626   EVT VT = N->getValueType(0);
10627
10628   unsigned NumInScalars = N->getNumOperands();
10629   SDLoc dl(N);
10630
10631   EVT SrcVT = MVT::Other;
10632   unsigned Opcode = ISD::DELETED_NODE;
10633   unsigned NumDefs = 0;
10634
10635   for (unsigned i = 0; i != NumInScalars; ++i) {
10636     SDValue In = N->getOperand(i);
10637     unsigned Opc = In.getOpcode();
10638
10639     if (Opc == ISD::UNDEF)
10640       continue;
10641
10642     // If all scalar values are floats and converted from integers.
10643     if (Opcode == ISD::DELETED_NODE &&
10644         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10645       Opcode = Opc;
10646     }
10647
10648     if (Opc != Opcode)
10649       return SDValue();
10650
10651     EVT InVT = In.getOperand(0).getValueType();
10652
10653     // If all scalar values are typed differently, bail out. It's chosen to
10654     // simplify BUILD_VECTOR of integer types.
10655     if (SrcVT == MVT::Other)
10656       SrcVT = InVT;
10657     if (SrcVT != InVT)
10658       return SDValue();
10659     NumDefs++;
10660   }
10661
10662   // If the vector has just one element defined, it's not worth to fold it into
10663   // a vectorized one.
10664   if (NumDefs < 2)
10665     return SDValue();
10666
10667   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10668          && "Should only handle conversion from integer to float.");
10669   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10670
10671   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10672
10673   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10674     return SDValue();
10675
10676   SmallVector<SDValue, 8> Opnds;
10677   for (unsigned i = 0; i != NumInScalars; ++i) {
10678     SDValue In = N->getOperand(i);
10679
10680     if (In.getOpcode() == ISD::UNDEF)
10681       Opnds.push_back(DAG.getUNDEF(SrcVT));
10682     else
10683       Opnds.push_back(In.getOperand(0));
10684   }
10685   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10686   AddToWorklist(BV.getNode());
10687
10688   return DAG.getNode(Opcode, dl, VT, BV);
10689 }
10690
10691 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10692   unsigned NumInScalars = N->getNumOperands();
10693   SDLoc dl(N);
10694   EVT VT = N->getValueType(0);
10695
10696   // A vector built entirely of undefs is undef.
10697   if (ISD::allOperandsUndef(N))
10698     return DAG.getUNDEF(VT);
10699
10700   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10701   if (V.getNode())
10702     return V;
10703
10704   V = reduceBuildVecConvertToConvertBuildVec(N);
10705   if (V.getNode())
10706     return V;
10707
10708   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10709   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10710   // at most two distinct vectors, turn this into a shuffle node.
10711
10712   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10713   if (!isTypeLegal(VT))
10714     return SDValue();
10715
10716   // May only combine to shuffle after legalize if shuffle is legal.
10717   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10718     return SDValue();
10719
10720   SDValue VecIn1, VecIn2;
10721   bool UsesZeroVector = false;
10722   for (unsigned i = 0; i != NumInScalars; ++i) {
10723     SDValue Op = N->getOperand(i);
10724     // Ignore undef inputs.
10725     if (Op.getOpcode() == ISD::UNDEF) continue;
10726
10727     // See if we can combine this build_vector into a blend with a zero vector.
10728     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10729         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10730         (Op.getOpcode() == ISD::ConstantFP &&
10731         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10732       UsesZeroVector = true;
10733       continue;
10734     }
10735
10736     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10737     // constant index, bail out.
10738     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10739         !isa<ConstantSDNode>(Op.getOperand(1))) {
10740       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10741       break;
10742     }
10743
10744     // We allow up to two distinct input vectors.
10745     SDValue ExtractedFromVec = Op.getOperand(0);
10746     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10747       continue;
10748
10749     if (!VecIn1.getNode()) {
10750       VecIn1 = ExtractedFromVec;
10751     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10752       VecIn2 = ExtractedFromVec;
10753     } else {
10754       // Too many inputs.
10755       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10756       break;
10757     }
10758   }
10759
10760   // If everything is good, we can make a shuffle operation.
10761   if (VecIn1.getNode()) {
10762     SmallVector<int, 8> Mask;
10763     for (unsigned i = 0; i != NumInScalars; ++i) {
10764       unsigned Opcode = N->getOperand(i).getOpcode();
10765       if (Opcode == ISD::UNDEF) {
10766         Mask.push_back(-1);
10767         continue;
10768       }
10769
10770       // Operands can also be zero.
10771       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10772         assert(UsesZeroVector &&
10773                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10774                "Unexpected node found!");
10775         Mask.push_back(NumInScalars+i);
10776         continue;
10777       }
10778
10779       // If extracting from the first vector, just use the index directly.
10780       SDValue Extract = N->getOperand(i);
10781       SDValue ExtVal = Extract.getOperand(1);
10782       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10783       if (Extract.getOperand(0) == VecIn1) {
10784         if (ExtIndex > VT.getVectorNumElements())
10785           return SDValue();
10786
10787         Mask.push_back(ExtIndex);
10788         continue;
10789       }
10790
10791       // Otherwise, use InIdx + VecSize
10792       Mask.push_back(NumInScalars+ExtIndex);
10793     }
10794
10795     // Avoid introducing illegal shuffles with zero.
10796     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10797       return SDValue();
10798
10799     // We can't generate a shuffle node with mismatched input and output types.
10800     // Attempt to transform a single input vector to the correct type.
10801     if ((VT != VecIn1.getValueType())) {
10802       // We don't support shuffeling between TWO values of different types.
10803       if (VecIn2.getNode())
10804         return SDValue();
10805
10806       // We only support widening of vectors which are half the size of the
10807       // output registers. For example XMM->YMM widening on X86 with AVX.
10808       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10809         return SDValue();
10810
10811       // If the input vector type has a different base type to the output
10812       // vector type, bail out.
10813       if (VecIn1.getValueType().getVectorElementType() !=
10814           VT.getVectorElementType())
10815         return SDValue();
10816
10817       // Widen the input vector by adding undef values.
10818       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10819                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10820     }
10821
10822     if (UsesZeroVector)
10823       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10824                                 DAG.getConstantFP(0.0, VT);
10825     else
10826       // If VecIn2 is unused then change it to undef.
10827       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10828
10829     // Check that we were able to transform all incoming values to the same
10830     // type.
10831     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10832         VecIn1.getValueType() != VT)
10833           return SDValue();
10834
10835     // Return the new VECTOR_SHUFFLE node.
10836     SDValue Ops[2];
10837     Ops[0] = VecIn1;
10838     Ops[1] = VecIn2;
10839     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10840   }
10841
10842   return SDValue();
10843 }
10844
10845 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10846   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10847   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10848   // inputs come from at most two distinct vectors, turn this into a shuffle
10849   // node.
10850
10851   // If we only have one input vector, we don't need to do any concatenation.
10852   if (N->getNumOperands() == 1)
10853     return N->getOperand(0);
10854
10855   // Check if all of the operands are undefs.
10856   EVT VT = N->getValueType(0);
10857   if (ISD::allOperandsUndef(N))
10858     return DAG.getUNDEF(VT);
10859
10860   // Optimize concat_vectors where one of the vectors is undef.
10861   if (N->getNumOperands() == 2 &&
10862       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10863     SDValue In = N->getOperand(0);
10864     assert(In.getValueType().isVector() && "Must concat vectors");
10865
10866     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10867     if (In->getOpcode() == ISD::BITCAST &&
10868         !In->getOperand(0)->getValueType(0).isVector()) {
10869       SDValue Scalar = In->getOperand(0);
10870       EVT SclTy = Scalar->getValueType(0);
10871
10872       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10873         return SDValue();
10874
10875       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10876                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10877       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10878         return SDValue();
10879
10880       SDLoc dl = SDLoc(N);
10881       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10882       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10883     }
10884   }
10885
10886   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10887   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10888   if (N->getNumOperands() == 2 &&
10889       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10890       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10891     EVT VT = N->getValueType(0);
10892     SDValue N0 = N->getOperand(0);
10893     SDValue N1 = N->getOperand(1);
10894     SmallVector<SDValue, 8> Opnds;
10895     unsigned BuildVecNumElts =  N0.getNumOperands();
10896
10897     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10898     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10899     if (SclTy0.isFloatingPoint()) {
10900       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10901         Opnds.push_back(N0.getOperand(i));
10902       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10903         Opnds.push_back(N1.getOperand(i));
10904     } else {
10905       // If BUILD_VECTOR are from built from integer, they may have different
10906       // operand types. Get the smaller type and truncate all operands to it.
10907       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10908       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10909         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10910                         N0.getOperand(i)));
10911       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10912         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10913                         N1.getOperand(i)));
10914     }
10915
10916     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10917   }
10918
10919   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10920   // nodes often generate nop CONCAT_VECTOR nodes.
10921   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10922   // place the incoming vectors at the exact same location.
10923   SDValue SingleSource = SDValue();
10924   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10925
10926   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10927     SDValue Op = N->getOperand(i);
10928
10929     if (Op.getOpcode() == ISD::UNDEF)
10930       continue;
10931
10932     // Check if this is the identity extract:
10933     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10934       return SDValue();
10935
10936     // Find the single incoming vector for the extract_subvector.
10937     if (SingleSource.getNode()) {
10938       if (Op.getOperand(0) != SingleSource)
10939         return SDValue();
10940     } else {
10941       SingleSource = Op.getOperand(0);
10942
10943       // Check the source type is the same as the type of the result.
10944       // If not, this concat may extend the vector, so we can not
10945       // optimize it away.
10946       if (SingleSource.getValueType() != N->getValueType(0))
10947         return SDValue();
10948     }
10949
10950     unsigned IdentityIndex = i * PartNumElem;
10951     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10952     // The extract index must be constant.
10953     if (!CS)
10954       return SDValue();
10955
10956     // Check that we are reading from the identity index.
10957     if (CS->getZExtValue() != IdentityIndex)
10958       return SDValue();
10959   }
10960
10961   if (SingleSource.getNode())
10962     return SingleSource;
10963
10964   return SDValue();
10965 }
10966
10967 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10968   EVT NVT = N->getValueType(0);
10969   SDValue V = N->getOperand(0);
10970
10971   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10972     // Combine:
10973     //    (extract_subvec (concat V1, V2, ...), i)
10974     // Into:
10975     //    Vi if possible
10976     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10977     // type.
10978     if (V->getOperand(0).getValueType() != NVT)
10979       return SDValue();
10980     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10981     unsigned NumElems = NVT.getVectorNumElements();
10982     assert((Idx % NumElems) == 0 &&
10983            "IDX in concat is not a multiple of the result vector length.");
10984     return V->getOperand(Idx / NumElems);
10985   }
10986
10987   // Skip bitcasting
10988   if (V->getOpcode() == ISD::BITCAST)
10989     V = V.getOperand(0);
10990
10991   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10992     SDLoc dl(N);
10993     // Handle only simple case where vector being inserted and vector
10994     // being extracted are of same type, and are half size of larger vectors.
10995     EVT BigVT = V->getOperand(0).getValueType();
10996     EVT SmallVT = V->getOperand(1).getValueType();
10997     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10998       return SDValue();
10999
11000     // Only handle cases where both indexes are constants with the same type.
11001     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11002     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11003
11004     if (InsIdx && ExtIdx &&
11005         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11006         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11007       // Combine:
11008       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11009       // Into:
11010       //    indices are equal or bit offsets are equal => V1
11011       //    otherwise => (extract_subvec V1, ExtIdx)
11012       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11013           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11014         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11015       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11016                          DAG.getNode(ISD::BITCAST, dl,
11017                                      N->getOperand(0).getValueType(),
11018                                      V->getOperand(0)), N->getOperand(1));
11019     }
11020   }
11021
11022   return SDValue();
11023 }
11024
11025 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11026                                                  SDValue V, SelectionDAG &DAG) {
11027   SDLoc DL(V);
11028   EVT VT = V.getValueType();
11029
11030   switch (V.getOpcode()) {
11031   default:
11032     return V;
11033
11034   case ISD::CONCAT_VECTORS: {
11035     EVT OpVT = V->getOperand(0).getValueType();
11036     int OpSize = OpVT.getVectorNumElements();
11037     SmallBitVector OpUsedElements(OpSize, false);
11038     bool FoundSimplification = false;
11039     SmallVector<SDValue, 4> NewOps;
11040     NewOps.reserve(V->getNumOperands());
11041     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11042       SDValue Op = V->getOperand(i);
11043       bool OpUsed = false;
11044       for (int j = 0; j < OpSize; ++j)
11045         if (UsedElements[i * OpSize + j]) {
11046           OpUsedElements[j] = true;
11047           OpUsed = true;
11048         }
11049       NewOps.push_back(
11050           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11051                  : DAG.getUNDEF(OpVT));
11052       FoundSimplification |= Op == NewOps.back();
11053       OpUsedElements.reset();
11054     }
11055     if (FoundSimplification)
11056       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11057     return V;
11058   }
11059
11060   case ISD::INSERT_SUBVECTOR: {
11061     SDValue BaseV = V->getOperand(0);
11062     SDValue SubV = V->getOperand(1);
11063     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11064     if (!IdxN)
11065       return V;
11066
11067     int SubSize = SubV.getValueType().getVectorNumElements();
11068     int Idx = IdxN->getZExtValue();
11069     bool SubVectorUsed = false;
11070     SmallBitVector SubUsedElements(SubSize, false);
11071     for (int i = 0; i < SubSize; ++i)
11072       if (UsedElements[i + Idx]) {
11073         SubVectorUsed = true;
11074         SubUsedElements[i] = true;
11075         UsedElements[i + Idx] = false;
11076       }
11077
11078     // Now recurse on both the base and sub vectors.
11079     SDValue SimplifiedSubV =
11080         SubVectorUsed
11081             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11082             : DAG.getUNDEF(SubV.getValueType());
11083     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11084     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11085       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11086                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11087     return V;
11088   }
11089   }
11090 }
11091
11092 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11093                                        SDValue N1, SelectionDAG &DAG) {
11094   EVT VT = SVN->getValueType(0);
11095   int NumElts = VT.getVectorNumElements();
11096   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11097   for (int M : SVN->getMask())
11098     if (M >= 0 && M < NumElts)
11099       N0UsedElements[M] = true;
11100     else if (M >= NumElts)
11101       N1UsedElements[M - NumElts] = true;
11102
11103   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11104   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11105   if (S0 == N0 && S1 == N1)
11106     return SDValue();
11107
11108   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11109 }
11110
11111 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11112 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11113   EVT VT = N->getValueType(0);
11114   unsigned NumElts = VT.getVectorNumElements();
11115
11116   SDValue N0 = N->getOperand(0);
11117   SDValue N1 = N->getOperand(1);
11118   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11119
11120   SmallVector<SDValue, 4> Ops;
11121   EVT ConcatVT = N0.getOperand(0).getValueType();
11122   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11123   unsigned NumConcats = NumElts / NumElemsPerConcat;
11124
11125   // Look at every vector that's inserted. We're looking for exact
11126   // subvector-sized copies from a concatenated vector
11127   for (unsigned I = 0; I != NumConcats; ++I) {
11128     // Make sure we're dealing with a copy.
11129     unsigned Begin = I * NumElemsPerConcat;
11130     bool AllUndef = true, NoUndef = true;
11131     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11132       if (SVN->getMaskElt(J) >= 0)
11133         AllUndef = false;
11134       else
11135         NoUndef = false;
11136     }
11137
11138     if (NoUndef) {
11139       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11140         return SDValue();
11141
11142       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11143         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11144           return SDValue();
11145
11146       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11147       if (FirstElt < N0.getNumOperands())
11148         Ops.push_back(N0.getOperand(FirstElt));
11149       else
11150         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11151
11152     } else if (AllUndef) {
11153       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11154     } else { // Mixed with general masks and undefs, can't do optimization.
11155       return SDValue();
11156     }
11157   }
11158
11159   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11160 }
11161
11162 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11163   EVT VT = N->getValueType(0);
11164   unsigned NumElts = VT.getVectorNumElements();
11165
11166   SDValue N0 = N->getOperand(0);
11167   SDValue N1 = N->getOperand(1);
11168
11169   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11170
11171   // Canonicalize shuffle undef, undef -> undef
11172   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11173     return DAG.getUNDEF(VT);
11174
11175   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11176
11177   // Canonicalize shuffle v, v -> v, undef
11178   if (N0 == N1) {
11179     SmallVector<int, 8> NewMask;
11180     for (unsigned i = 0; i != NumElts; ++i) {
11181       int Idx = SVN->getMaskElt(i);
11182       if (Idx >= (int)NumElts) Idx -= NumElts;
11183       NewMask.push_back(Idx);
11184     }
11185     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11186                                 &NewMask[0]);
11187   }
11188
11189   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11190   if (N0.getOpcode() == ISD::UNDEF) {
11191     SmallVector<int, 8> NewMask;
11192     for (unsigned i = 0; i != NumElts; ++i) {
11193       int Idx = SVN->getMaskElt(i);
11194       if (Idx >= 0) {
11195         if (Idx >= (int)NumElts)
11196           Idx -= NumElts;
11197         else
11198           Idx = -1; // remove reference to lhs
11199       }
11200       NewMask.push_back(Idx);
11201     }
11202     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11203                                 &NewMask[0]);
11204   }
11205
11206   // Remove references to rhs if it is undef
11207   if (N1.getOpcode() == ISD::UNDEF) {
11208     bool Changed = false;
11209     SmallVector<int, 8> NewMask;
11210     for (unsigned i = 0; i != NumElts; ++i) {
11211       int Idx = SVN->getMaskElt(i);
11212       if (Idx >= (int)NumElts) {
11213         Idx = -1;
11214         Changed = true;
11215       }
11216       NewMask.push_back(Idx);
11217     }
11218     if (Changed)
11219       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11220   }
11221
11222   // If it is a splat, check if the argument vector is another splat or a
11223   // build_vector with all scalar elements the same.
11224   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11225     SDNode *V = N0.getNode();
11226
11227     // If this is a bit convert that changes the element type of the vector but
11228     // not the number of vector elements, look through it.  Be careful not to
11229     // look though conversions that change things like v4f32 to v2f64.
11230     if (V->getOpcode() == ISD::BITCAST) {
11231       SDValue ConvInput = V->getOperand(0);
11232       if (ConvInput.getValueType().isVector() &&
11233           ConvInput.getValueType().getVectorNumElements() == NumElts)
11234         V = ConvInput.getNode();
11235     }
11236
11237     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11238       assert(V->getNumOperands() == NumElts &&
11239              "BUILD_VECTOR has wrong number of operands");
11240       SDValue Base;
11241       bool AllSame = true;
11242       for (unsigned i = 0; i != NumElts; ++i) {
11243         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11244           Base = V->getOperand(i);
11245           break;
11246         }
11247       }
11248       // Splat of <u, u, u, u>, return <u, u, u, u>
11249       if (!Base.getNode())
11250         return N0;
11251       for (unsigned i = 0; i != NumElts; ++i) {
11252         if (V->getOperand(i) != Base) {
11253           AllSame = false;
11254           break;
11255         }
11256       }
11257       // Splat of <x, x, x, x>, return <x, x, x, x>
11258       if (AllSame)
11259         return N0;
11260     }
11261   }
11262
11263   // There are various patterns used to build up a vector from smaller vectors,
11264   // subvectors, or elements. Scan chains of these and replace unused insertions
11265   // or components with undef.
11266   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11267     return S;
11268
11269   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11270       Level < AfterLegalizeVectorOps &&
11271       (N1.getOpcode() == ISD::UNDEF ||
11272       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11273        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11274     SDValue V = partitionShuffleOfConcats(N, DAG);
11275
11276     if (V.getNode())
11277       return V;
11278   }
11279
11280   // Canonicalize shuffles according to rules:
11281   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11282   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11283   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11284   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11285       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11286       TLI.isTypeLegal(VT)) {
11287     // The incoming shuffle must be of the same type as the result of the
11288     // current shuffle.
11289     assert(N1->getOperand(0).getValueType() == VT &&
11290            "Shuffle types don't match");
11291
11292     SDValue SV0 = N1->getOperand(0);
11293     SDValue SV1 = N1->getOperand(1);
11294     bool HasSameOp0 = N0 == SV0;
11295     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11296     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11297       // Commute the operands of this shuffle so that next rule
11298       // will trigger.
11299       return DAG.getCommutedVectorShuffle(*SVN);
11300   }
11301
11302   // Try to fold according to rules:
11303   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11304   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11305   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11306   // Don't try to fold shuffles with illegal type.
11307   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11308       TLI.isTypeLegal(VT)) {
11309     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11310
11311     // The incoming shuffle must be of the same type as the result of the
11312     // current shuffle.
11313     assert(OtherSV->getOperand(0).getValueType() == VT &&
11314            "Shuffle types don't match");
11315
11316     SDValue SV0, SV1;
11317     SmallVector<int, 4> Mask;
11318     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11319     // operand, and SV1 as the second operand.
11320     for (unsigned i = 0; i != NumElts; ++i) {
11321       int Idx = SVN->getMaskElt(i);
11322       if (Idx < 0) {
11323         // Propagate Undef.
11324         Mask.push_back(Idx);
11325         continue;
11326       }
11327
11328       SDValue CurrentVec;
11329       if (Idx < (int)NumElts) {
11330         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11331         // shuffle mask to identify which vector is actually referenced.
11332         Idx = OtherSV->getMaskElt(Idx);
11333         if (Idx < 0) {
11334           // Propagate Undef.
11335           Mask.push_back(Idx);
11336           continue;
11337         }
11338
11339         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11340                                            : OtherSV->getOperand(1);
11341       } else {
11342         // This shuffle index references an element within N1.
11343         CurrentVec = N1;
11344       }
11345
11346       // Simple case where 'CurrentVec' is UNDEF.
11347       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11348         Mask.push_back(-1);
11349         continue;
11350       }
11351
11352       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11353       // will be the first or second operand of the combined shuffle.
11354       Idx = Idx % NumElts;
11355       if (!SV0.getNode() || SV0 == CurrentVec) {
11356         // Ok. CurrentVec is the left hand side.
11357         // Update the mask accordingly.
11358         SV0 = CurrentVec;
11359         Mask.push_back(Idx);
11360         continue;
11361       }
11362
11363       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11364       if (SV1.getNode() && SV1 != CurrentVec)
11365         return SDValue();
11366
11367       // Ok. CurrentVec is the right hand side.
11368       // Update the mask accordingly.
11369       SV1 = CurrentVec;
11370       Mask.push_back(Idx + NumElts);
11371     }
11372
11373     // Check if all indices in Mask are Undef. In case, propagate Undef.
11374     bool isUndefMask = true;
11375     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11376       isUndefMask &= Mask[i] < 0;
11377
11378     if (isUndefMask)
11379       return DAG.getUNDEF(VT);
11380
11381     if (!SV0.getNode())
11382       SV0 = DAG.getUNDEF(VT);
11383     if (!SV1.getNode())
11384       SV1 = DAG.getUNDEF(VT);
11385
11386     // Avoid introducing shuffles with illegal mask.
11387     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11388       // Compute the commuted shuffle mask and test again.
11389       for (unsigned i = 0; i != NumElts; ++i) {
11390         int idx = Mask[i];
11391         if (idx < 0)
11392           continue;
11393         else if (idx < (int)NumElts)
11394           Mask[i] = idx + NumElts;
11395         else
11396           Mask[i] = idx - NumElts;
11397       }
11398
11399       if (!TLI.isShuffleMaskLegal(Mask, VT))
11400         return SDValue();
11401  
11402       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11403       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11404       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11405       std::swap(SV0, SV1);
11406     }
11407
11408     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11409     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11410     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11411     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11412   }
11413
11414   return SDValue();
11415 }
11416
11417 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11418   SDValue N0 = N->getOperand(0);
11419   SDValue N2 = N->getOperand(2);
11420
11421   // If the input vector is a concatenation, and the insert replaces
11422   // one of the halves, we can optimize into a single concat_vectors.
11423   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11424       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11425     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11426     EVT VT = N->getValueType(0);
11427
11428     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11429     // (concat_vectors Z, Y)
11430     if (InsIdx == 0)
11431       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11432                          N->getOperand(1), N0.getOperand(1));
11433
11434     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11435     // (concat_vectors X, Z)
11436     if (InsIdx == VT.getVectorNumElements()/2)
11437       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11438                          N0.getOperand(0), N->getOperand(1));
11439   }
11440
11441   return SDValue();
11442 }
11443
11444 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11445 /// with the destination vector and a zero vector.
11446 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11447 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11448 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11449   EVT VT = N->getValueType(0);
11450   SDLoc dl(N);
11451   SDValue LHS = N->getOperand(0);
11452   SDValue RHS = N->getOperand(1);
11453   if (N->getOpcode() == ISD::AND) {
11454     if (RHS.getOpcode() == ISD::BITCAST)
11455       RHS = RHS.getOperand(0);
11456     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11457       SmallVector<int, 8> Indices;
11458       unsigned NumElts = RHS.getNumOperands();
11459       for (unsigned i = 0; i != NumElts; ++i) {
11460         SDValue Elt = RHS.getOperand(i);
11461         if (!isa<ConstantSDNode>(Elt))
11462           return SDValue();
11463
11464         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11465           Indices.push_back(i);
11466         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11467           Indices.push_back(NumElts+i);
11468         else
11469           return SDValue();
11470       }
11471
11472       // Let's see if the target supports this vector_shuffle.
11473       EVT RVT = RHS.getValueType();
11474       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11475         return SDValue();
11476
11477       // Return the new VECTOR_SHUFFLE node.
11478       EVT EltVT = RVT.getVectorElementType();
11479       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11480                                      DAG.getConstant(0, EltVT));
11481       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11482       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11483       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11484       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11485     }
11486   }
11487
11488   return SDValue();
11489 }
11490
11491 /// Visit a binary vector operation, like ADD.
11492 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11493   assert(N->getValueType(0).isVector() &&
11494          "SimplifyVBinOp only works on vectors!");
11495
11496   SDValue LHS = N->getOperand(0);
11497   SDValue RHS = N->getOperand(1);
11498   SDValue Shuffle = XformToShuffleWithZero(N);
11499   if (Shuffle.getNode()) return Shuffle;
11500
11501   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11502   // this operation.
11503   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11504       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11505     // Check if both vectors are constants. If not bail out.
11506     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11507           cast<BuildVectorSDNode>(RHS)->isConstant()))
11508       return SDValue();
11509
11510     SmallVector<SDValue, 8> Ops;
11511     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11512       SDValue LHSOp = LHS.getOperand(i);
11513       SDValue RHSOp = RHS.getOperand(i);
11514
11515       // Can't fold divide by zero.
11516       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11517           N->getOpcode() == ISD::FDIV) {
11518         if ((RHSOp.getOpcode() == ISD::Constant &&
11519              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11520             (RHSOp.getOpcode() == ISD::ConstantFP &&
11521              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11522           break;
11523       }
11524
11525       EVT VT = LHSOp.getValueType();
11526       EVT RVT = RHSOp.getValueType();
11527       if (RVT != VT) {
11528         // Integer BUILD_VECTOR operands may have types larger than the element
11529         // size (e.g., when the element type is not legal).  Prior to type
11530         // legalization, the types may not match between the two BUILD_VECTORS.
11531         // Truncate one of the operands to make them match.
11532         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11533           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11534         } else {
11535           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11536           VT = RVT;
11537         }
11538       }
11539       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11540                                    LHSOp, RHSOp);
11541       if (FoldOp.getOpcode() != ISD::UNDEF &&
11542           FoldOp.getOpcode() != ISD::Constant &&
11543           FoldOp.getOpcode() != ISD::ConstantFP)
11544         break;
11545       Ops.push_back(FoldOp);
11546       AddToWorklist(FoldOp.getNode());
11547     }
11548
11549     if (Ops.size() == LHS.getNumOperands())
11550       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11551   }
11552
11553   // Type legalization might introduce new shuffles in the DAG.
11554   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11555   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11556   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11557       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11558       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11559       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11560     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11561     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11562
11563     if (SVN0->getMask().equals(SVN1->getMask())) {
11564       EVT VT = N->getValueType(0);
11565       SDValue UndefVector = LHS.getOperand(1);
11566       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11567                                      LHS.getOperand(0), RHS.getOperand(0));
11568       AddUsersToWorklist(N);
11569       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11570                                   &SVN0->getMask()[0]);
11571     }
11572   }
11573
11574   return SDValue();
11575 }
11576
11577 /// Visit a binary vector operation, like FABS/FNEG.
11578 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11579   assert(N->getValueType(0).isVector() &&
11580          "SimplifyVUnaryOp only works on vectors!");
11581
11582   SDValue N0 = N->getOperand(0);
11583
11584   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11585     return SDValue();
11586
11587   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11588   SmallVector<SDValue, 8> Ops;
11589   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11590     SDValue Op = N0.getOperand(i);
11591     if (Op.getOpcode() != ISD::UNDEF &&
11592         Op.getOpcode() != ISD::ConstantFP)
11593       break;
11594     EVT EltVT = Op.getValueType();
11595     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11596     if (FoldOp.getOpcode() != ISD::UNDEF &&
11597         FoldOp.getOpcode() != ISD::ConstantFP)
11598       break;
11599     Ops.push_back(FoldOp);
11600     AddToWorklist(FoldOp.getNode());
11601   }
11602
11603   if (Ops.size() != N0.getNumOperands())
11604     return SDValue();
11605
11606   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11607 }
11608
11609 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11610                                     SDValue N1, SDValue N2){
11611   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11612
11613   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11614                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11615
11616   // If we got a simplified select_cc node back from SimplifySelectCC, then
11617   // break it down into a new SETCC node, and a new SELECT node, and then return
11618   // the SELECT node, since we were called with a SELECT node.
11619   if (SCC.getNode()) {
11620     // Check to see if we got a select_cc back (to turn into setcc/select).
11621     // Otherwise, just return whatever node we got back, like fabs.
11622     if (SCC.getOpcode() == ISD::SELECT_CC) {
11623       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11624                                   N0.getValueType(),
11625                                   SCC.getOperand(0), SCC.getOperand(1),
11626                                   SCC.getOperand(4));
11627       AddToWorklist(SETCC.getNode());
11628       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11629                            SCC.getOperand(2), SCC.getOperand(3));
11630     }
11631
11632     return SCC;
11633   }
11634   return SDValue();
11635 }
11636
11637 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11638 /// being selected between, see if we can simplify the select.  Callers of this
11639 /// should assume that TheSelect is deleted if this returns true.  As such, they
11640 /// should return the appropriate thing (e.g. the node) back to the top-level of
11641 /// the DAG combiner loop to avoid it being looked at.
11642 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11643                                     SDValue RHS) {
11644
11645   // Cannot simplify select with vector condition
11646   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11647
11648   // If this is a select from two identical things, try to pull the operation
11649   // through the select.
11650   if (LHS.getOpcode() != RHS.getOpcode() ||
11651       !LHS.hasOneUse() || !RHS.hasOneUse())
11652     return false;
11653
11654   // If this is a load and the token chain is identical, replace the select
11655   // of two loads with a load through a select of the address to load from.
11656   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11657   // constants have been dropped into the constant pool.
11658   if (LHS.getOpcode() == ISD::LOAD) {
11659     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11660     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11661
11662     // Token chains must be identical.
11663     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11664         // Do not let this transformation reduce the number of volatile loads.
11665         LLD->isVolatile() || RLD->isVolatile() ||
11666         // If this is an EXTLOAD, the VT's must match.
11667         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11668         // If this is an EXTLOAD, the kind of extension must match.
11669         (LLD->getExtensionType() != RLD->getExtensionType() &&
11670          // The only exception is if one of the extensions is anyext.
11671          LLD->getExtensionType() != ISD::EXTLOAD &&
11672          RLD->getExtensionType() != ISD::EXTLOAD) ||
11673         // FIXME: this discards src value information.  This is
11674         // over-conservative. It would be beneficial to be able to remember
11675         // both potential memory locations.  Since we are discarding
11676         // src value info, don't do the transformation if the memory
11677         // locations are not in the default address space.
11678         LLD->getPointerInfo().getAddrSpace() != 0 ||
11679         RLD->getPointerInfo().getAddrSpace() != 0 ||
11680         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11681                                       LLD->getBasePtr().getValueType()))
11682       return false;
11683
11684     // Check that the select condition doesn't reach either load.  If so,
11685     // folding this will induce a cycle into the DAG.  If not, this is safe to
11686     // xform, so create a select of the addresses.
11687     SDValue Addr;
11688     if (TheSelect->getOpcode() == ISD::SELECT) {
11689       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11690       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11691           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11692         return false;
11693       // The loads must not depend on one another.
11694       if (LLD->isPredecessorOf(RLD) ||
11695           RLD->isPredecessorOf(LLD))
11696         return false;
11697       Addr = DAG.getSelect(SDLoc(TheSelect),
11698                            LLD->getBasePtr().getValueType(),
11699                            TheSelect->getOperand(0), LLD->getBasePtr(),
11700                            RLD->getBasePtr());
11701     } else {  // Otherwise SELECT_CC
11702       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11703       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11704
11705       if ((LLD->hasAnyUseOfValue(1) &&
11706            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11707           (RLD->hasAnyUseOfValue(1) &&
11708            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11709         return false;
11710
11711       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11712                          LLD->getBasePtr().getValueType(),
11713                          TheSelect->getOperand(0),
11714                          TheSelect->getOperand(1),
11715                          LLD->getBasePtr(), RLD->getBasePtr(),
11716                          TheSelect->getOperand(4));
11717     }
11718
11719     SDValue Load;
11720     // It is safe to replace the two loads if they have different alignments,
11721     // but the new load must be the minimum (most restrictive) alignment of the
11722     // inputs.
11723     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11724     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11725     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11726       Load = DAG.getLoad(TheSelect->getValueType(0),
11727                          SDLoc(TheSelect),
11728                          // FIXME: Discards pointer and AA info.
11729                          LLD->getChain(), Addr, MachinePointerInfo(),
11730                          LLD->isVolatile(), LLD->isNonTemporal(),
11731                          isInvariant, Alignment);
11732     } else {
11733       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11734                             RLD->getExtensionType() : LLD->getExtensionType(),
11735                             SDLoc(TheSelect),
11736                             TheSelect->getValueType(0),
11737                             // FIXME: Discards pointer and AA info.
11738                             LLD->getChain(), Addr, MachinePointerInfo(),
11739                             LLD->getMemoryVT(), LLD->isVolatile(),
11740                             LLD->isNonTemporal(), isInvariant, Alignment);
11741     }
11742
11743     // Users of the select now use the result of the load.
11744     CombineTo(TheSelect, Load);
11745
11746     // Users of the old loads now use the new load's chain.  We know the
11747     // old-load value is dead now.
11748     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11749     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11750     return true;
11751   }
11752
11753   return false;
11754 }
11755
11756 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11757 /// where 'cond' is the comparison specified by CC.
11758 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11759                                       SDValue N2, SDValue N3,
11760                                       ISD::CondCode CC, bool NotExtCompare) {
11761   // (x ? y : y) -> y.
11762   if (N2 == N3) return N2;
11763
11764   EVT VT = N2.getValueType();
11765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11766   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11767   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11768
11769   // Determine if the condition we're dealing with is constant
11770   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11771                               N0, N1, CC, DL, false);
11772   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11773   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11774
11775   // fold select_cc true, x, y -> x
11776   if (SCCC && !SCCC->isNullValue())
11777     return N2;
11778   // fold select_cc false, x, y -> y
11779   if (SCCC && SCCC->isNullValue())
11780     return N3;
11781
11782   // Check to see if we can simplify the select into an fabs node
11783   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11784     // Allow either -0.0 or 0.0
11785     if (CFP->getValueAPF().isZero()) {
11786       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11787       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11788           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11789           N2 == N3.getOperand(0))
11790         return DAG.getNode(ISD::FABS, DL, VT, N0);
11791
11792       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11793       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11794           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11795           N2.getOperand(0) == N3)
11796         return DAG.getNode(ISD::FABS, DL, VT, N3);
11797     }
11798   }
11799
11800   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11801   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11802   // in it.  This is a win when the constant is not otherwise available because
11803   // it replaces two constant pool loads with one.  We only do this if the FP
11804   // type is known to be legal, because if it isn't, then we are before legalize
11805   // types an we want the other legalization to happen first (e.g. to avoid
11806   // messing with soft float) and if the ConstantFP is not legal, because if
11807   // it is legal, we may not need to store the FP constant in a constant pool.
11808   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11809     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11810       if (TLI.isTypeLegal(N2.getValueType()) &&
11811           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11812                TargetLowering::Legal &&
11813            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11814            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11815           // If both constants have multiple uses, then we won't need to do an
11816           // extra load, they are likely around in registers for other users.
11817           (TV->hasOneUse() || FV->hasOneUse())) {
11818         Constant *Elts[] = {
11819           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11820           const_cast<ConstantFP*>(TV->getConstantFPValue())
11821         };
11822         Type *FPTy = Elts[0]->getType();
11823         const DataLayout &TD = *TLI.getDataLayout();
11824
11825         // Create a ConstantArray of the two constants.
11826         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11827         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11828                                             TD.getPrefTypeAlignment(FPTy));
11829         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11830
11831         // Get the offsets to the 0 and 1 element of the array so that we can
11832         // select between them.
11833         SDValue Zero = DAG.getIntPtrConstant(0);
11834         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11835         SDValue One = DAG.getIntPtrConstant(EltSize);
11836
11837         SDValue Cond = DAG.getSetCC(DL,
11838                                     getSetCCResultType(N0.getValueType()),
11839                                     N0, N1, CC);
11840         AddToWorklist(Cond.getNode());
11841         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11842                                           Cond, One, Zero);
11843         AddToWorklist(CstOffset.getNode());
11844         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11845                             CstOffset);
11846         AddToWorklist(CPIdx.getNode());
11847         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11848                            MachinePointerInfo::getConstantPool(), false,
11849                            false, false, Alignment);
11850
11851       }
11852     }
11853
11854   // Check to see if we can perform the "gzip trick", transforming
11855   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11856   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11857       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11858        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11859     EVT XType = N0.getValueType();
11860     EVT AType = N2.getValueType();
11861     if (XType.bitsGE(AType)) {
11862       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11863       // single-bit constant.
11864       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11865         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11866         ShCtV = XType.getSizeInBits()-ShCtV-1;
11867         SDValue ShCt = DAG.getConstant(ShCtV,
11868                                        getShiftAmountTy(N0.getValueType()));
11869         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11870                                     XType, N0, ShCt);
11871         AddToWorklist(Shift.getNode());
11872
11873         if (XType.bitsGT(AType)) {
11874           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11875           AddToWorklist(Shift.getNode());
11876         }
11877
11878         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11879       }
11880
11881       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11882                                   XType, N0,
11883                                   DAG.getConstant(XType.getSizeInBits()-1,
11884                                          getShiftAmountTy(N0.getValueType())));
11885       AddToWorklist(Shift.getNode());
11886
11887       if (XType.bitsGT(AType)) {
11888         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11889         AddToWorklist(Shift.getNode());
11890       }
11891
11892       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11893     }
11894   }
11895
11896   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11897   // where y is has a single bit set.
11898   // A plaintext description would be, we can turn the SELECT_CC into an AND
11899   // when the condition can be materialized as an all-ones register.  Any
11900   // single bit-test can be materialized as an all-ones register with
11901   // shift-left and shift-right-arith.
11902   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11903       N0->getValueType(0) == VT &&
11904       N1C && N1C->isNullValue() &&
11905       N2C && N2C->isNullValue()) {
11906     SDValue AndLHS = N0->getOperand(0);
11907     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11908     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11909       // Shift the tested bit over the sign bit.
11910       APInt AndMask = ConstAndRHS->getAPIntValue();
11911       SDValue ShlAmt =
11912         DAG.getConstant(AndMask.countLeadingZeros(),
11913                         getShiftAmountTy(AndLHS.getValueType()));
11914       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11915
11916       // Now arithmetic right shift it all the way over, so the result is either
11917       // all-ones, or zero.
11918       SDValue ShrAmt =
11919         DAG.getConstant(AndMask.getBitWidth()-1,
11920                         getShiftAmountTy(Shl.getValueType()));
11921       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11922
11923       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11924     }
11925   }
11926
11927   // fold select C, 16, 0 -> shl C, 4
11928   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11929       TLI.getBooleanContents(N0.getValueType()) ==
11930           TargetLowering::ZeroOrOneBooleanContent) {
11931
11932     // If the caller doesn't want us to simplify this into a zext of a compare,
11933     // don't do it.
11934     if (NotExtCompare && N2C->getAPIntValue() == 1)
11935       return SDValue();
11936
11937     // Get a SetCC of the condition
11938     // NOTE: Don't create a SETCC if it's not legal on this target.
11939     if (!LegalOperations ||
11940         TLI.isOperationLegal(ISD::SETCC,
11941           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11942       SDValue Temp, SCC;
11943       // cast from setcc result type to select result type
11944       if (LegalTypes) {
11945         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11946                             N0, N1, CC);
11947         if (N2.getValueType().bitsLT(SCC.getValueType()))
11948           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11949                                         N2.getValueType());
11950         else
11951           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11952                              N2.getValueType(), SCC);
11953       } else {
11954         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11955         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11956                            N2.getValueType(), SCC);
11957       }
11958
11959       AddToWorklist(SCC.getNode());
11960       AddToWorklist(Temp.getNode());
11961
11962       if (N2C->getAPIntValue() == 1)
11963         return Temp;
11964
11965       // shl setcc result by log2 n2c
11966       return DAG.getNode(
11967           ISD::SHL, DL, N2.getValueType(), Temp,
11968           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11969                           getShiftAmountTy(Temp.getValueType())));
11970     }
11971   }
11972
11973   // Check to see if this is the equivalent of setcc
11974   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11975   // otherwise, go ahead with the folds.
11976   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11977     EVT XType = N0.getValueType();
11978     if (!LegalOperations ||
11979         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11980       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11981       if (Res.getValueType() != VT)
11982         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11983       return Res;
11984     }
11985
11986     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11987     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11988         (!LegalOperations ||
11989          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11990       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11991       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11992                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11993                                        getShiftAmountTy(Ctlz.getValueType())));
11994     }
11995     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11996     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11997       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11998                                   XType, DAG.getConstant(0, XType), N0);
11999       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12000       return DAG.getNode(ISD::SRL, DL, XType,
12001                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12002                          DAG.getConstant(XType.getSizeInBits()-1,
12003                                          getShiftAmountTy(XType)));
12004     }
12005     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12006     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12007       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12008                                  DAG.getConstant(XType.getSizeInBits()-1,
12009                                          getShiftAmountTy(N0.getValueType())));
12010       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12011     }
12012   }
12013
12014   // Check to see if this is an integer abs.
12015   // select_cc setg[te] X,  0,  X, -X ->
12016   // select_cc setgt    X, -1,  X, -X ->
12017   // select_cc setl[te] X,  0, -X,  X ->
12018   // select_cc setlt    X,  1, -X,  X ->
12019   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12020   if (N1C) {
12021     ConstantSDNode *SubC = nullptr;
12022     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12023          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12024         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12025       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12026     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12027               (N1C->isOne() && CC == ISD::SETLT)) &&
12028              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12029       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12030
12031     EVT XType = N0.getValueType();
12032     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12033       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12034                                   N0,
12035                                   DAG.getConstant(XType.getSizeInBits()-1,
12036                                          getShiftAmountTy(N0.getValueType())));
12037       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12038                                 XType, N0, Shift);
12039       AddToWorklist(Shift.getNode());
12040       AddToWorklist(Add.getNode());
12041       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12042     }
12043   }
12044
12045   return SDValue();
12046 }
12047
12048 /// This is a stub for TargetLowering::SimplifySetCC.
12049 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12050                                    SDValue N1, ISD::CondCode Cond,
12051                                    SDLoc DL, bool foldBooleans) {
12052   TargetLowering::DAGCombinerInfo
12053     DagCombineInfo(DAG, Level, false, this);
12054   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12055 }
12056
12057 /// Given an ISD::SDIV node expressing a divide by constant, return
12058 /// a DAG expression to select that will generate the same value by multiplying
12059 /// by a magic number.
12060 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12061 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12062   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12063   if (!C)
12064     return SDValue();
12065
12066   // Avoid division by zero.
12067   if (!C->getAPIntValue())
12068     return SDValue();
12069
12070   std::vector<SDNode*> Built;
12071   SDValue S =
12072       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12073
12074   for (SDNode *N : Built)
12075     AddToWorklist(N);
12076   return S;
12077 }
12078
12079 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12080 /// DAG expression that will generate the same value by right shifting.
12081 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12082   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12083   if (!C)
12084     return SDValue();
12085
12086   // Avoid division by zero.
12087   if (!C->getAPIntValue())
12088     return SDValue();
12089
12090   std::vector<SDNode *> Built;
12091   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12092
12093   for (SDNode *N : Built)
12094     AddToWorklist(N);
12095   return S;
12096 }
12097
12098 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12099 /// expression that will generate the same value by multiplying by a magic
12100 /// number.
12101 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12102 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12103   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12104   if (!C)
12105     return SDValue();
12106
12107   // Avoid division by zero.
12108   if (!C->getAPIntValue())
12109     return SDValue();
12110
12111   std::vector<SDNode*> Built;
12112   SDValue S =
12113       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12114
12115   for (SDNode *N : Built)
12116     AddToWorklist(N);
12117   return S;
12118 }
12119
12120 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12121   if (Level >= AfterLegalizeDAG)
12122     return SDValue();
12123
12124   // Expose the DAG combiner to the target combiner implementations.
12125   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12126
12127   unsigned Iterations = 0;
12128   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12129     if (Iterations) {
12130       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12131       // For the reciprocal, we need to find the zero of the function:
12132       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12133       //     =>
12134       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12135       //     does not require additional intermediate precision]
12136       EVT VT = Op.getValueType();
12137       SDLoc DL(Op);
12138       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12139
12140       AddToWorklist(Est.getNode());
12141
12142       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12143       for (unsigned i = 0; i < Iterations; ++i) {
12144         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12145         AddToWorklist(NewEst.getNode());
12146
12147         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12148         AddToWorklist(NewEst.getNode());
12149
12150         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12151         AddToWorklist(NewEst.getNode());
12152
12153         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12154         AddToWorklist(Est.getNode());
12155       }
12156     }
12157     return Est;
12158   }
12159
12160   return SDValue();
12161 }
12162
12163 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12164 /// For the reciprocal sqrt, we need to find the zero of the function:
12165 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12166 ///     =>
12167 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12168 /// As a result, we precompute A/2 prior to the iteration loop.
12169 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12170                                           unsigned Iterations) {
12171   EVT VT = Arg.getValueType();
12172   SDLoc DL(Arg);
12173   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12174
12175   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12176   // this entire sequence requires only one FP constant.
12177   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12178   AddToWorklist(HalfArg.getNode());
12179
12180   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12181   AddToWorklist(HalfArg.getNode());
12182
12183   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12184   for (unsigned i = 0; i < Iterations; ++i) {
12185     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12186     AddToWorklist(NewEst.getNode());
12187
12188     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12189     AddToWorklist(NewEst.getNode());
12190
12191     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12192     AddToWorklist(NewEst.getNode());
12193
12194     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12195     AddToWorklist(Est.getNode());
12196   }
12197   return Est;
12198 }
12199
12200 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12201 /// For the reciprocal sqrt, we need to find the zero of the function:
12202 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12203 ///     =>
12204 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12205 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12206                                           unsigned Iterations) {
12207   EVT VT = Arg.getValueType();
12208   SDLoc DL(Arg);
12209   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12210   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12211
12212   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12213   for (unsigned i = 0; i < Iterations; ++i) {
12214     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12215     AddToWorklist(HalfEst.getNode());
12216
12217     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12218     AddToWorklist(Est.getNode());
12219
12220     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12221     AddToWorklist(Est.getNode());
12222
12223     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12224     AddToWorklist(Est.getNode());
12225
12226     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12227     AddToWorklist(Est.getNode());
12228   }
12229   return Est;
12230 }
12231
12232 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12233   if (Level >= AfterLegalizeDAG)
12234     return SDValue();
12235
12236   // Expose the DAG combiner to the target combiner implementations.
12237   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12238   unsigned Iterations = 0;
12239   bool UseOneConstNR = false;
12240   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12241     AddToWorklist(Est.getNode());
12242     if (Iterations) {
12243       Est = UseOneConstNR ?
12244         BuildRsqrtNROneConst(Op, Est, Iterations) :
12245         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12246     }
12247     return Est;
12248   }
12249
12250   return SDValue();
12251 }
12252
12253 /// Return true if base is a frame index, which is known not to alias with
12254 /// anything but itself.  Provides base object and offset as results.
12255 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12256                            const GlobalValue *&GV, const void *&CV) {
12257   // Assume it is a primitive operation.
12258   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12259
12260   // If it's an adding a simple constant then integrate the offset.
12261   if (Base.getOpcode() == ISD::ADD) {
12262     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12263       Base = Base.getOperand(0);
12264       Offset += C->getZExtValue();
12265     }
12266   }
12267
12268   // Return the underlying GlobalValue, and update the Offset.  Return false
12269   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12270   // by multiple nodes with different offsets.
12271   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12272     GV = G->getGlobal();
12273     Offset += G->getOffset();
12274     return false;
12275   }
12276
12277   // Return the underlying Constant value, and update the Offset.  Return false
12278   // for ConstantSDNodes since the same constant pool entry may be represented
12279   // by multiple nodes with different offsets.
12280   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12281     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12282                                          : (const void *)C->getConstVal();
12283     Offset += C->getOffset();
12284     return false;
12285   }
12286   // If it's any of the following then it can't alias with anything but itself.
12287   return isa<FrameIndexSDNode>(Base);
12288 }
12289
12290 /// Return true if there is any possibility that the two addresses overlap.
12291 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12292   // If they are the same then they must be aliases.
12293   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12294
12295   // If they are both volatile then they cannot be reordered.
12296   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12297
12298   // Gather base node and offset information.
12299   SDValue Base1, Base2;
12300   int64_t Offset1, Offset2;
12301   const GlobalValue *GV1, *GV2;
12302   const void *CV1, *CV2;
12303   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12304                                       Base1, Offset1, GV1, CV1);
12305   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12306                                       Base2, Offset2, GV2, CV2);
12307
12308   // If they have a same base address then check to see if they overlap.
12309   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12310     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12311              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12312
12313   // It is possible for different frame indices to alias each other, mostly
12314   // when tail call optimization reuses return address slots for arguments.
12315   // To catch this case, look up the actual index of frame indices to compute
12316   // the real alias relationship.
12317   if (isFrameIndex1 && isFrameIndex2) {
12318     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12319     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12320     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12321     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12322              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12323   }
12324
12325   // Otherwise, if we know what the bases are, and they aren't identical, then
12326   // we know they cannot alias.
12327   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12328     return false;
12329
12330   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12331   // compared to the size and offset of the access, we may be able to prove they
12332   // do not alias.  This check is conservative for now to catch cases created by
12333   // splitting vector types.
12334   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12335       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12336       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12337        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12338       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12339     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12340     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12341
12342     // There is no overlap between these relatively aligned accesses of similar
12343     // size, return no alias.
12344     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12345         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12346       return false;
12347   }
12348
12349   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12350                    ? CombinerGlobalAA
12351                    : DAG.getSubtarget().useAA();
12352 #ifndef NDEBUG
12353   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12354       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12355     UseAA = false;
12356 #endif
12357   if (UseAA &&
12358       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12359     // Use alias analysis information.
12360     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12361                                  Op1->getSrcValueOffset());
12362     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12363         Op0->getSrcValueOffset() - MinOffset;
12364     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12365         Op1->getSrcValueOffset() - MinOffset;
12366     AliasAnalysis::AliasResult AAResult =
12367         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12368                                          Overlap1,
12369                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12370                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12371                                          Overlap2,
12372                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12373     if (AAResult == AliasAnalysis::NoAlias)
12374       return false;
12375   }
12376
12377   // Otherwise we have to assume they alias.
12378   return true;
12379 }
12380
12381 /// Walk up chain skipping non-aliasing memory nodes,
12382 /// looking for aliasing nodes and adding them to the Aliases vector.
12383 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12384                                    SmallVectorImpl<SDValue> &Aliases) {
12385   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12386   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12387
12388   // Get alias information for node.
12389   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12390
12391   // Starting off.
12392   Chains.push_back(OriginalChain);
12393   unsigned Depth = 0;
12394
12395   // Look at each chain and determine if it is an alias.  If so, add it to the
12396   // aliases list.  If not, then continue up the chain looking for the next
12397   // candidate.
12398   while (!Chains.empty()) {
12399     SDValue Chain = Chains.back();
12400     Chains.pop_back();
12401
12402     // For TokenFactor nodes, look at each operand and only continue up the
12403     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12404     // find more and revert to original chain since the xform is unlikely to be
12405     // profitable.
12406     //
12407     // FIXME: The depth check could be made to return the last non-aliasing
12408     // chain we found before we hit a tokenfactor rather than the original
12409     // chain.
12410     if (Depth > 6 || Aliases.size() == 2) {
12411       Aliases.clear();
12412       Aliases.push_back(OriginalChain);
12413       return;
12414     }
12415
12416     // Don't bother if we've been before.
12417     if (!Visited.insert(Chain.getNode()).second)
12418       continue;
12419
12420     switch (Chain.getOpcode()) {
12421     case ISD::EntryToken:
12422       // Entry token is ideal chain operand, but handled in FindBetterChain.
12423       break;
12424
12425     case ISD::LOAD:
12426     case ISD::STORE: {
12427       // Get alias information for Chain.
12428       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12429           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12430
12431       // If chain is alias then stop here.
12432       if (!(IsLoad && IsOpLoad) &&
12433           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12434         Aliases.push_back(Chain);
12435       } else {
12436         // Look further up the chain.
12437         Chains.push_back(Chain.getOperand(0));
12438         ++Depth;
12439       }
12440       break;
12441     }
12442
12443     case ISD::TokenFactor:
12444       // We have to check each of the operands of the token factor for "small"
12445       // token factors, so we queue them up.  Adding the operands to the queue
12446       // (stack) in reverse order maintains the original order and increases the
12447       // likelihood that getNode will find a matching token factor (CSE.)
12448       if (Chain.getNumOperands() > 16) {
12449         Aliases.push_back(Chain);
12450         break;
12451       }
12452       for (unsigned n = Chain.getNumOperands(); n;)
12453         Chains.push_back(Chain.getOperand(--n));
12454       ++Depth;
12455       break;
12456
12457     default:
12458       // For all other instructions we will just have to take what we can get.
12459       Aliases.push_back(Chain);
12460       break;
12461     }
12462   }
12463
12464   // We need to be careful here to also search for aliases through the
12465   // value operand of a store, etc. Consider the following situation:
12466   //   Token1 = ...
12467   //   L1 = load Token1, %52
12468   //   S1 = store Token1, L1, %51
12469   //   L2 = load Token1, %52+8
12470   //   S2 = store Token1, L2, %51+8
12471   //   Token2 = Token(S1, S2)
12472   //   L3 = load Token2, %53
12473   //   S3 = store Token2, L3, %52
12474   //   L4 = load Token2, %53+8
12475   //   S4 = store Token2, L4, %52+8
12476   // If we search for aliases of S3 (which loads address %52), and we look
12477   // only through the chain, then we'll miss the trivial dependence on L1
12478   // (which also loads from %52). We then might change all loads and
12479   // stores to use Token1 as their chain operand, which could result in
12480   // copying %53 into %52 before copying %52 into %51 (which should
12481   // happen first).
12482   //
12483   // The problem is, however, that searching for such data dependencies
12484   // can become expensive, and the cost is not directly related to the
12485   // chain depth. Instead, we'll rule out such configurations here by
12486   // insisting that we've visited all chain users (except for users
12487   // of the original chain, which is not necessary). When doing this,
12488   // we need to look through nodes we don't care about (otherwise, things
12489   // like register copies will interfere with trivial cases).
12490
12491   SmallVector<const SDNode *, 16> Worklist;
12492   for (const SDNode *N : Visited)
12493     if (N != OriginalChain.getNode())
12494       Worklist.push_back(N);
12495
12496   while (!Worklist.empty()) {
12497     const SDNode *M = Worklist.pop_back_val();
12498
12499     // We have already visited M, and want to make sure we've visited any uses
12500     // of M that we care about. For uses that we've not visisted, and don't
12501     // care about, queue them to the worklist.
12502
12503     for (SDNode::use_iterator UI = M->use_begin(),
12504          UIE = M->use_end(); UI != UIE; ++UI)
12505       if (UI.getUse().getValueType() == MVT::Other &&
12506           Visited.insert(*UI).second) {
12507         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12508           // We've not visited this use, and we care about it (it could have an
12509           // ordering dependency with the original node).
12510           Aliases.clear();
12511           Aliases.push_back(OriginalChain);
12512           return;
12513         }
12514
12515         // We've not visited this use, but we don't care about it. Mark it as
12516         // visited and enqueue it to the worklist.
12517         Worklist.push_back(*UI);
12518       }
12519   }
12520 }
12521
12522 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12523 /// (aliasing node.)
12524 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12525   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12526
12527   // Accumulate all the aliases to this node.
12528   GatherAllAliases(N, OldChain, Aliases);
12529
12530   // If no operands then chain to entry token.
12531   if (Aliases.size() == 0)
12532     return DAG.getEntryNode();
12533
12534   // If a single operand then chain to it.  We don't need to revisit it.
12535   if (Aliases.size() == 1)
12536     return Aliases[0];
12537
12538   // Construct a custom tailored token factor.
12539   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12540 }
12541
12542 /// This is the entry point for the file.
12543 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12544                            CodeGenOpt::Level OptLevel) {
12545   /// This is the main entry point to this class.
12546   DAGCombiner(*this, AA, OptLevel).Run(Level);
12547 }